From d378c37fbd1ecec7b43394926f1ca32a695e07de Mon Sep 17 00:00:00 2001 From: vasraz Date: Mon, 22 Mar 2021 15:33:06 +0000 Subject: Reformat openecomp-be Signed-off-by: Vasyl Razinkov Issue-ID: SDC-3449 Change-Id: I13e02322f8e00820cc5a1d85752caaeda9bf10d1 --- .../openecomp/sdcrests/action/rest/Actions.java | 296 +- .../action/rest/ActionsForSwaggerFileUpload.java | 111 +- .../rest/mapping/MapActionToActionResponseDto.java | 21 +- .../sdcrests/action/rest/services/ActionsImpl.java | 1851 +++--- .../sdcrests/action/types/ActionResponseDto.java | 3 - .../sdcrests/action/types/ActionVersionDto.java | 2 - .../sdcrests/action/types/ListResponseWrapper.java | 4 +- .../rest/ApplicationConfiguration.java | 54 +- ...licationConfigEntityToApplicationConfigDto.java | 19 +- ...MapConfigurationDataToConfigurationDataDto.java | 19 +- .../services/ApplicationConfigurationImpl.java | 73 +- .../types/ApplicationConfigDto.java | 2 - .../types/ConfigurationDataDto.java | 6 +- .../sdcrests/conflict/rest/Conflicts.java | 70 +- .../rest/mapping/MapConflictInfoToDto.java | 18 +- .../conflict/rest/mapping/MapConflictToDto.java | 195 +- .../rest/mapping/MapDtoToConflictResolution.java | 18 +- .../rest/mapping/MapItemVersionConflictToDto.java | 25 +- .../conflict/rest/services/ConflictsImpl.java | 66 +- .../sdcrests/conflict/types/ConflictDto.java | 34 +- .../sdcrests/conflict/types/ConflictInfoDto.java | 48 +- .../conflict/types/ConflictResolutionDto.java | 39 +- .../conflict/types/ItemVersionConflictDto.java | 42 +- .../sdcrests/health/rest/HealthCheck.java | 14 +- .../rest/mapping/MapHealthCheckInfoToDto.java | 26 +- .../health/rest/services/HealthCheckImpl.java | 84 +- .../sdcrests/health/types/HealthCheckStatus.java | 27 +- .../sdcrests/health/types/HealthInfoDto.java | 15 +- .../sdcrests/health/types/HealthInfoDtos.java | 11 +- .../sdcrests/health/types/MonitoredModules.java | 28 +- .../itempermissions/rest/ItemPermissions.java | 50 +- .../MapItemPermissionsToItemPermissionsDto.java | 20 +- .../rest/services/ItemPermissionsImpl.java | 48 +- .../itempermissions/types/ItemPermissionsDto.java | 34 +- .../types/ItemPermissionsRequestDto.java | 37 +- .../org/openecomp/sdcrests/item/rest/Items.java | 39 +- .../org/openecomp/sdcrests/item/rest/Versions.java | 102 +- .../rest/mapping/MapActivityLogEntityToDto.java | 23 +- .../sdcrests/item/rest/mapping/MapItemToDto.java | 26 +- .../item/rest/mapping/MapRevisionToDto.java | 20 +- .../item/rest/mapping/MapVersionToDto.java | 30 +- .../sdcrests/item/rest/models/SyncEvent.java | 3 +- .../sdcrests/item/rest/services/ItemsImpl.java | 169 +- .../item/rest/services/ManagersProvider.java | 4 +- .../sdcrests/item/rest/services/VersionsImpl.java | 96 +- .../catalog/notification/AsyncNotifier.java | 26 +- .../notification/EntryNotConfiguredException.java | 1 - .../services/catalog/notification/Notifier.java | 1 - .../catalog/notification/NotifierFactory.java | 29 +- .../notification/http/HttpConfiguration.java | 1 - .../notification/http/HttpNotificationTask.java | 31 +- .../notification/http/HttpTaskProducer.java | 27 +- .../sdcrests/item/types/ActivityLogDto.java | 90 +- .../sdcrests/item/types/CommitRequestDto.java | 20 +- .../openecomp/sdcrests/item/types/ItemAction.java | 10 +- .../sdcrests/item/types/ItemActionRequestDto.java | 14 +- .../sdcrests/item/types/ItemCreationDto.java | 34 +- .../org/openecomp/sdcrests/item/types/ItemDto.java | 133 +- .../openecomp/sdcrests/item/types/RevisionDto.java | 61 +- .../sdcrests/item/types/RevisionRequestDto.java | 19 +- .../sdcrests/item/types/SubmitRequestDto.java | 20 +- .../sdcrests/item/types/VersionAction.java | 9 +- .../item/types/VersionActionRequestDto.java | 43 +- .../openecomp/sdcrests/item/types/VersionDto.java | 179 +- .../sdcrests/item/types/VersionRequestDto.java | 34 +- .../listeners/OnboardingAppStartupListener.java | 25 +- .../rest/mapping/MapNotificationsStatusToDto.java | 30 +- .../rest/mapping/MapNotificationsToDto.java | 28 +- .../notifications/rest/services/Notifications.java | 80 +- .../rest/services/impl/NotificationsImpl.java | 65 +- .../notifications/types/NotificationEntityDto.java | 129 +- .../types/NotificationResponseStatus.java | 6 +- .../types/NotificationsStatusDto.java | 9 +- .../types/UpdateNotificationResponseStatus.java | 14 +- .../server/configuration/CookieConfig.java | 9 +- .../server/filters/ActionAuthenticationFilter.java | 150 +- .../server/filters/ActionAuthorizationFilter.java | 55 +- .../server/filters/ActionLibraryPrivilege.java | 93 +- .../server/filters/BasicAuthenticationFilter.java | 161 +- .../filters/OnboardingSessionContextFilter.java | 26 +- .../server/filters/RestrictionAccessFilter.java | 63 +- .../server/interceptors/DefaultOutput.java | 306 +- .../interceptors/EmptyOutputOutInterceptor.java | 58 +- .../server/interceptors/InternalEmptyObject.java | 6 +- .../listeners/OnboardingAppStartupListener.java | 34 +- .../openecomp/sdcrests/common/RestConstants.java | 18 +- .../sdcrests/common/mapping/MapErrorCodeToDto.java | 18 +- .../common/mapping/MapErrorMessageToDto.java | 16 +- .../sdcrests/common/types/ErrorCodeDto.java | 48 +- .../sdcrests/common/types/ErrorMessageDto.java | 34 +- .../sdcrests/errors/DefaultExceptionMapper.java | 40 +- .../sdcrests/errors/ZusammenExceptionMapper.java | 38 +- .../sdcrests/filters/SessionContextFilter.java | 55 +- .../openecomp/sdcrests/mapping/EchoMapMapping.java | 9 +- .../openecomp/sdcrests/mapping/MappingBase.java | 121 +- .../wrappers/GenericCollectionWrapper.java | 90 +- .../sdcrests/wrappers/StringWrapperResponse.java | 31 +- .../sdcrests/togglz/rest/TogglzFeatures.java | 47 +- .../rest/mapping/MapToggleableFeatureToDto.java | 5 +- .../togglz/rest/services/TogglzFeaturesImpl.java | 20 +- .../sdcrests/togglz/types/FeatureDto.java | 10 +- .../sdcrests/togglz/types/FeatureSetDto.java | 2 +- .../sdcrests/uniquevalue/rest/UniqueTypes.java | 42 +- .../uniquevalue/rest/services/UniqueTypesImpl.java | 88 +- .../uniquevalue/types/UniqueTypesProvider.java | 8 +- .../sdcrests/validation/rest/Validation.java | 27 +- .../validation/rest/ValidationForSwaggerUsage.java | 27 +- ...ionFileResponseToValidationFileResponseDto.java | 14 +- .../validation/rest/services/ValidationImpl.java | 49 +- .../types/ValidationFileResponseDto.java | 27 +- .../vendorlicense/rest/EntitlementPoolLimits.java | 131 +- .../vendorlicense/rest/EntitlementPools.java | 69 +- .../sdcrests/vendorlicense/rest/FeatureGroups.java | 110 +- .../vendorlicense/rest/LicenseAgreements.java | 113 +- .../vendorlicense/rest/LicenseKeyGroupLimits.java | 129 +- .../vendorlicense/rest/LicenseKeyGroups.java | 110 +- .../vendorlicense/rest/VendorLicenseModels.java | 122 +- .../rest/mapping/LimitCreationDto.java | 20 +- .../MapChoiceOrOtherDtoToChoiceOrOther.java | 20 +- .../MapChoiceOrOtherToChoiceOrOtherDto.java | 18 +- ...lementPoolEntityToEntitlementPoolEntityDto.java | 44 +- ...ementPoolRequestDtoToEntitlementPoolEntity.java | 36 +- ...tureGroupDescriptorDtoToFeatureGroupEntity.java | 23 +- ...tureGroupEntityToFeatureGroupDescriptorDto.java | 21 +- ...ementDescriptorDtoToLicenseAgreementEntity.java | 24 +- ...ementEntityToLicenseAgreementDescriptorDto.java | 24 +- ...seKeyGroupEntityToLicenseKeyGroupEntityDto.java | 43 +- ...eKeyGroupRequestDtoToLicenseKeyGroupEntity.java | 37 +- .../mapping/MapLimitEntityToLimitCreationDto.java | 17 +- .../rest/mapping/MapLimitEntityToLimitDto.java | 30 +- .../mapping/MapLimitRequestDtoToLimitEntity.java | 22 +- ...pMultiChoiceOrOtherDtoToMultiChoiceOrOther.java | 20 +- ...pMultiChoiceOrOtherToMultiChoiceOrOtherDto.java | 18 +- .../mapping/MapVendorLicenseModelEntityToDto.java | 19 +- ...eModelRequestDtoToVendorLicenseModelEntity.java | 21 +- .../rest/services/EntitlementPoolLimitsImpl.java | 196 +- .../rest/services/EntitlementPoolsImpl.java | 187 +- .../rest/services/FeatureGroupsImpl.java | 71 +- .../rest/services/LicenseAgreementsImpl.java | 71 +- .../rest/services/LicenseKeyGroupLimitsImpl.java | 195 +- .../rest/services/LicenseKeyGroupsImpl.java | 193 +- .../rest/services/VendorLicenseModelsImpl.java | 164 +- .../rest/services/VlmUniqueTypeProvider.java | 16 +- .../vendorlicense/types/ChoiceOrOtherDto.java | 76 +- .../types/EntitlementPoolEntityDto.java | 50 +- .../types/EntitlementPoolRequestDto.java | 210 +- .../types/FeatureGroupDescriptorDto.java | 69 +- .../vendorlicense/types/FeatureGroupEntityDto.java | 68 +- .../vendorlicense/types/FeatureGroupModelDto.java | 65 +- .../types/FeatureGroupRequestDto.java | 35 +- .../types/FeatureGroupUpdateRequestDto.java | 35 +- .../types/LicenseAgreementDescriptorDto.java | 77 +- .../types/LicenseAgreementEntityDto.java | 41 +- .../types/LicenseAgreementModelDto.java | 37 +- .../types/LicenseAgreementRequestDto.java | 21 +- .../types/LicenseAgreementUpdateRequestDto.java | 22 +- .../types/LicenseKeyGroupEntityDto.java | 49 +- .../types/LicenseKeyGroupRequestDto.java | 213 +- .../vendorlicense/types/LimitEntityDto.java | 167 +- .../vendorlicense/types/LimitRequestDto.java | 166 +- .../vendorlicense/types/MultiChoiceOrOtherDto.java | 83 +- .../types/VendorLicenseModelActionRequestDto.java | 37 +- .../types/VendorLicenseModelEntityDto.java | 21 +- .../types/VendorLicenseModelRequestDto.java | 71 +- .../validation/ChoiceOrOtherSequenceProvider.java | 32 +- .../MultiChoiceOrOtherSequenceProvider.java | 35 +- .../types/validation/OtherChoiceValidation.java | 6 +- .../sdcrests/vsp/rest/ComponentDependencies.java | 108 +- .../vsp/rest/ComponentMonitoringUploads.java | 88 +- .../sdcrests/vsp/rest/ComponentProcesses.java | 201 +- .../openecomp/sdcrests/vsp/rest/Components.java | 156 +- .../org/openecomp/sdcrests/vsp/rest/Compute.java | 169 +- .../sdcrests/vsp/rest/DeploymentFlavors.java | 122 +- .../org/openecomp/sdcrests/vsp/rest/Images.java | 214 +- .../org/openecomp/sdcrests/vsp/rest/Networks.java | 100 +- .../java/org/openecomp/sdcrests/vsp/rest/Nics.java | 160 +- .../vsp/rest/OrchestrationTemplateCandidate.java | 119 +- .../org/openecomp/sdcrests/vsp/rest/Processes.java | 178 +- .../sdcrests/vsp/rest/VendorSoftwareProducts.java | 278 +- ...VendorSoftwareProductsForSwaggerFileUpload.java | 48 +- .../openecomp/sdcrests/vsp/rest/VspEntities.java | 1 - .../mapping/MapComponentDataToComponentDto.java | 15 +- .../MapComponentDependencyEntityToCreationDto.java | 18 +- .../mapping/MapComponentDependencyEntityToDto.java | 23 +- .../MapComponentDependencyModelEntityToDto.java | 21 +- ...MapComponentDependencyModelRequestToEntity.java | 31 +- .../MapComponentEntityToComponentCreationDto.java | 17 +- .../mapping/MapComponentEntityToComponentDto.java | 20 +- .../MapComponentRequestDtoToComponentEntity.java | 21 +- .../mapping/MapCompositionEntityResponseToDto.java | 36 +- .../MapCompositionEntityValidationDataToDto.java | 33 +- .../mapping/MapComputeDataToComputeDetailsDto.java | 16 +- .../MapComputeDetailsDtoToComputeEntity.java | 14 +- .../MapComputeEntityToComputeCreationDto.java | 17 +- .../rest/mapping/MapComputeEntityToComputeDto.java | 25 +- .../mapping/MapComputeEntityToVspComputeDto.java | 23 +- ...FlavorEntityDeploymentFlavorToListResponse.java | 26 +- ...tFlavorEntityToDeploymentFlavorCreationDto.java | 18 +- ...eploymentFlavorEntityToDeploymentFlavorDto.java | 13 +- ...ntFlavorRequestDtoToDeploymentFlavorEntity.java | 26 +- .../MapDeploymentFlavorToDeploymentDto.java | 21 +- .../rest/mapping/MapFilesDataStructureToDto.java | 22 +- .../vsp/rest/mapping/MapImageDataToImageDto.java | 22 +- .../mapping/MapImageEntityToImageCreationDto.java | 16 +- .../vsp/rest/mapping/MapImageEntityToImageDto.java | 21 +- .../mapping/MapImageRequestDtoToImageEntity.java | 16 +- .../vsp/rest/mapping/MapItemToVspDetailsDto.java | 28 +- .../mapping/MapMonitoringUploadStatusToDto.java | 21 +- .../rest/mapping/MapNetworkEntityToNetworkDto.java | 20 +- .../MapNetworkRequestDtoToNetworkEntity.java | 23 +- .../vsp/rest/mapping/MapNetworkToNetworkDto.java | 16 +- .../MapNicEntityToNicCreationResponseDto.java | 18 +- .../vsp/rest/mapping/MapNicEntityToNicDto.java | 20 +- .../rest/mapping/MapNicRequestDtoToNicEntity.java | 26 +- .../sdcrests/vsp/rest/mapping/MapNicToNicDto.java | 26 +- .../mapping/MapPackageInfoToPackageInfoDto.java | 34 +- .../MapProcessEntityToProcessEntityDto.java | 25 +- .../MapProcessRequestDtoToProcessEntity.java | 21 +- ...ionnaireResponseToQuestionnaireResponseDto.java | 20 +- .../MapQuestionnaireToQuestionnaireDto.java | 21 +- ...pUploadFileResponseToUploadFileResponseDto.java | 24 +- .../rest/mapping/MapValidationResponseToDto.java | 92 +- .../rest/mapping/MapVspDescriptionDtoToItem.java | 20 +- .../mapping/MapVspDescriptionDtoToVspDetails.java | 47 +- .../vsp/rest/mapping/MapVspDetailsToDto.java | 51 +- .../rest/services/ComponentDependenciesImpl.java | 146 +- .../services/ComponentMonitoringUploadsImpl.java | 121 +- .../vsp/rest/services/ComponentProcessesImpl.java | 247 +- .../sdcrests/vsp/rest/services/ComponentsImpl.java | 180 +- .../sdcrests/vsp/rest/services/ComputeImpl.java | 213 +- .../vsp/rest/services/DeploymentFlavorsImpl.java | 163 +- .../sdcrests/vsp/rest/services/ImagesImpl.java | 210 +- .../sdcrests/vsp/rest/services/NetworksImpl.java | 131 +- .../sdcrests/vsp/rest/services/NicsImpl.java | 206 +- .../OrchestrationTemplateCandidateException.java | 4 +- .../OrchestrationTemplateCandidateImpl.java | 255 +- .../sdcrests/vsp/rest/services/ProcessesImpl.java | 95 +- .../rest/services/VendorSoftwareProductsImpl.java | 412 +- .../vsp/rest/services/VspItemProperty.java | 11 +- .../vsp/rest/services/VspUniqueTypeProvider.java | 16 +- .../types/ComponentCreationDto.java | 30 +- .../types/ComponentDependencyCreationDto.java | 30 +- .../types/ComponentDependencyModel.java | 29 +- .../types/ComponentDependencyModelRequestDto.java | 34 +- .../types/ComponentDependencyResponseDto.java | 30 +- .../vendorsoftwareproducts/types/ComponentDto.java | 30 +- .../types/ComponentRelationType.java | 34 +- .../types/ComponentRequestDto.java | 33 +- .../types/ComponentValidationResultDto.java | 34 +- .../types/CompositionDataEntityDto.java | 2 +- .../types/CompositionEntityResponseDto.java | 30 +- .../types/CompositionEntityValidationDataDto.java | 33 +- .../types/ComputeCreationDto.java | 30 +- .../types/ComputeDescription.java | 30 +- .../types/ComputeDetailsDto.java | 34 +- .../vendorsoftwareproducts/types/ComputeDto.java | 30 +- .../types/DeploymentFlavorCreationDto.java | 30 +- .../types/DeploymentFlavorDto.java | 30 +- .../types/DeploymentFlavorListResponseDto.java | 30 +- .../types/DeploymentFlavorRequestDto.java | 37 +- .../types/DeploymentFlavorValidationResultDto.java | 34 +- .../types/FileDataStructureDto.java | 34 +- .../types/ImageCreationDto.java | 30 +- .../vendorsoftwareproducts/types/ImageDto.java | 30 +- .../types/ImageRequestDto.java | 30 +- .../types/MonitoringUploadStatusDto.java | 31 +- .../vendorsoftwareproducts/types/NetworkDto.java | 30 +- .../types/NetworkRequestDto.java | 33 +- .../types/NicCreationResponseDto.java | 30 +- .../vendorsoftwareproducts/types/NicDto.java | 30 +- .../types/NicRequestDto.java | 36 +- .../types/OrchestrationTemplateAction.java | 33 +- .../OrchestrationTemplateActionResponseDto.java | 35 +- .../types/PackageInfoDto.java | 30 +- .../types/ProcessEntityDto.java | 30 +- .../types/ProcessRequestDto.java | 33 +- .../types/QuestionnaireDto.java | 34 +- .../types/QuestionnaireResponseDto.java | 31 +- .../types/QuestionnaireValidationResultDto.java | 34 +- .../types/TranslatedFileDataDto.java | 30 +- .../types/UploadFileResponseDto.java | 36 +- .../types/ValidationResponseDto.java | 38 +- .../types/VendorSoftwareProductAction.java | 34 +- .../VersionSoftwareProductActionRequestDto.java | 31 +- .../vendorsoftwareproducts/types/VmSizing.java | 42 +- .../types/VspComputeDto.java | 30 +- .../types/VspDescriptionDto.java | 34 +- .../types/VspDetailsDto.java | 46 +- .../types/VspRequestDto.java | 34 +- .../types/validation/CustomJsonValidator.java | 25 +- .../types/validation/IsValidJson.java | 68 +- .../types/validation/StringValidator.java | 52 +- .../types/validation/ValidateString.java | 49 +- .../sdcrests/vsp/rest/VnfPackageRepository.java | 47 +- .../rest/services/VnfPackageRepositoryImpl.java | 68 +- .../org/openecomp/sdc/action/ActionManager.java | 43 +- .../sdc/action/impl/ActionManagerImpl.java | 673 +-- .../sdc/activitylog/ActivityLogManager.java | 8 +- .../sdc/activitylog/ActivityLogManagerFactory.java | 2 +- .../impl/ActivityLogManagerFactoryImpl.java | 22 +- .../activitylog/impl/ActivityLogManagerImpl.java | 31 +- .../ApplicationConfigManager.java | 14 +- .../impl/ApplicationConfigManagerImpl.java | 50 +- .../openecomp/sdc/conflicts/ConflictsManager.java | 16 +- .../sdc/conflicts/ConflictsManagerFactory.java | 2 +- .../impl/ConflictsManagerFactoryImpl.java | 13 +- .../sdc/conflicts/impl/ConflictsManagerImpl.java | 139 +- .../org/openecomp/sdc/health/HealthCheckDao.java | 11 +- .../sdc/health/HealthCheckDaoFactory.java | 12 +- .../openecomp/sdc/health/HealthCheckManager.java | 5 +- .../sdc/health/HealthCheckManagerFactory.java | 2 +- .../sdc/health/data/HealthCheckResult.java | 14 +- .../sdc/health/data/HealthCheckStatus.java | 27 +- .../org/openecomp/sdc/health/data/HealthInfo.java | 14 +- .../sdc/health/data/MonitoredModules.java | 21 +- .../org/openecomp/sdc/health/data/SiteMode.java | 18 +- .../sdc/health/impl/HealthCheckDaoFactoryImpl.java | 21 +- .../sdc/health/impl/HealthCheckDaoImpl.java | 12 +- .../health/impl/HealthCheckManagerFactoryImpl.java | 9 +- .../sdc/health/impl/HealthCheckManagerImpl.java | 63 +- .../sdc/itempermissions/PermissionsManager.java | 18 +- .../itempermissions/PermissionsManagerFactory.java | 9 +- .../dao/impl/PermissionsManagerFactoryImpl.java | 9 +- .../dao/impl/PermissionsManagerImpl.java | 243 +- .../sdc/securityutil/AuthenticationCookie.java | 47 +- .../securityutil/AuthenticationCookieUtils.java | 32 +- .../org/openecomp/sdc/securityutil/CipherUtil.java | 26 +- .../sdc/securityutil/CipherUtilException.java | 5 +- .../ISessionValidationCookieConfiguration.java | 10 +- .../ISessionValidationFilterConfiguration.java | 12 +- .../org/openecomp/sdc/securityutil/Passwords.java | 319 +- .../sdc/securityutil/RepresentationUtils.java | 10 +- .../filters/FilterServletOutputStream.java | 16 +- .../sdc/securityutil/filters/ResponceWrapper.java | 27 +- .../sdc/securityutil/filters/SampleFilter.java | 97 +- .../filters/SessionValidationFilter.java | 165 +- .../sdc/validation/UploadValidationManager.java | 13 +- .../impl/UploadValidationManagerImpl.java | 111 +- .../validation/types/ValidationFileResponse.java | 20 +- .../sdc/validation/types/ValidationFileStatus.java | 8 +- .../sdc/validation/util/ValidationManagerUtil.java | 65 +- .../sdc/vendorlicense/VendorLicenseManager.java | 86 +- .../vendorlicense/VendorLicenseManagerFactory.java | 14 +- .../vendorlicense/errors/LimitErrorBuilder.java | 48 +- .../impl/VendorLicenseManagerFactoryImpl.java | 35 +- .../impl/VendorLicenseManagerImpl.java | 1061 ++-- .../ComponentDependencyModelManager.java | 19 +- .../ComponentDependencyModelManagerFactory.java | 15 +- .../vendorsoftwareproduct/ComponentManager.java | 24 +- .../ComponentManagerFactory.java | 7 +- .../CompositionEntityDataManager.java | 50 +- .../CompositionEntityDataManagerFactory.java | 14 +- .../sdc/vendorsoftwareproduct/ComputeManager.java | 25 +- .../ComputeManagerFactory.java | 7 +- .../DeploymentFlavorManager.java | 26 +- .../DeploymentFlavorManagerFactory.java | 15 +- .../sdc/vendorsoftwareproduct/ImageManager.java | 28 +- .../vendorsoftwareproduct/ImageManagerFactory.java | 12 +- .../ManualVspToscaManager.java | 9 +- .../MonitoringUploadsManager.java | 13 +- .../MonitoringUploadsManagerFactory.java | 10 +- .../sdc/vendorsoftwareproduct/NetworkManager.java | 15 +- .../NetworkManagerFactory.java | 7 +- .../sdc/vendorsoftwareproduct/NicManager.java | 21 +- .../vendorsoftwareproduct/NicManagerFactory.java | 7 +- .../OrchestrationTemplateCandidateManager.java | 16 +- ...chestrationTemplateCandidateManagerFactory.java | 10 +- .../sdc/vendorsoftwareproduct/ProcessManager.java | 26 +- .../ProcessManagerFactory.java | 7 +- .../VendorSoftwareProductManager.java | 17 +- .../vendorsoftwareproduct/VspManagerFactory.java | 10 +- .../ComponentDependencyModelErrorBuilder.java | 81 +- .../errors/ComponentErrorBuilder.java | 25 +- .../CompositionEditNotAllowedErrorBuilder.java | 54 +- .../errors/ComputeErrorBuilder.java | 6 +- ...rNonFinalVendorSoftwareProductErrorBuilder.java | 52 +- .../errors/DeleteNicErrorBuilder.java | 7 +- .../errors/DeploymentFlavorErrorBuilder.java | 59 +- .../DuplicateComputeInComponentErrorBuilder.java | 36 +- .../DuplicateNicInComponentErrorBuilder.java | 27 +- .../errors/FileCreationErrorBuilder.java | 42 +- .../errors/ImageErrorBuilder.java | 139 +- .../InformationArtifactCreationErrorBuilder.java | 31 +- .../errors/MonitoringUploadErrorBuilder.java | 59 +- .../errors/NicErrorBuilder.java | 14 +- .../errors/NicInternalNetworkErrorBuilder.java | 76 +- ...orkIdNotAllowedExternalNetworkErrorBuilder.java | 28 +- .../NotSupportedHeatOnboardMethodErrorBuilder.java | 118 +- .../errors/OnboardingMethodErrorBuilder.java | 37 +- .../OrchestrationTemplateNotFoundErrorBuilder.java | 39 +- .../errors/PackageInvalidErrorBuilder.java | 55 +- .../errors/PackageNotFoundErrorBuilder.java | 63 +- .../TranslationFileCreationErrorBuilder.java | 46 +- .../errors/UploadInvalidErrorBuilder.java | 82 +- .../VendorSoftwareProductInvalidErrorBuilder.java | 107 +- .../exception/OnboardPackageException.java | 1 - ...ComponentDependencyModelManagerFactoryImpl.java | 24 +- .../impl/ComponentDependencyModelManagerImpl.java | 120 +- .../impl/ComponentManagerFactoryImpl.java | 20 +- .../impl/ComponentManagerImpl.java | 339 +- .../CompositionEntityDataManagerFactoryImpl.java | 33 +- .../impl/CompositionEntityDataManagerImpl.java | 864 ++- .../impl/ComputeManagerFactoryImpl.java | 22 +- .../impl/ComputeManagerImpl.java | 427 +- .../impl/DeploymentFlavorManagerFactoryImpl.java | 21 +- .../impl/DeploymentFlavorManagerImpl.java | 404 +- .../impl/ImageManagerFactoryImpl.java | 23 +- .../impl/ImageManagerImpl.java | 327 +- .../impl/ManualVspToscaManagerImpl.java | 141 +- .../impl/MonitoringUploadsManagerFactoryImpl.java | 14 +- .../impl/MonitoringUploadsManagerImpl.java | 256 +- .../impl/NetworkManagerFactoryImpl.java | 17 +- .../impl/NetworkManagerImpl.java | 130 +- .../impl/NicManagerFactoryImpl.java | 19 +- .../vendorsoftwareproduct/impl/NicManagerImpl.java | 331 +- ...trationTemplateCandidateManagerFactoryImpl.java | 19 +- .../OrchestrationTemplateCandidateManagerImpl.java | 158 +- .../impl/ProcessManagerFactoryImpl.java | 15 +- .../impl/ProcessManagerImpl.java | 330 +- .../impl/VendorSoftwareProductManagerImpl.java | 314 +- .../impl/VspManagerFactoryImpl.java | 48 +- .../impl/onboarding/ManifestAnalyzer.java | 5 +- .../OnboardingPackageContentHandler.java | 18 +- .../onboarding/OnboardingPackageProcessor.java | 84 +- .../onboarding/validation/CnfPackageValidator.java | 6 - .../BaseOrchestrationTemplateHandler.java | 110 +- .../OrchestrationTemplateCSARHandler.java | 50 +- .../OrchestrationTemplateFileHandler.java | 5 +- .../OrchestrationTemplateZipHandler.java | 58 +- .../orchestration/OrchestrationUploadFactory.java | 36 +- .../impl/orchestration/OrchestrationUtil.java | 582 +- .../csar/validation/CsarSecurityValidator.java | 2 - .../csar/validation/ManifestBuilder.java | 40 +- .../csar/validation/ONAPCsarValidator.java | 43 +- .../csar/validation/PMDictionaryValidator.java | 14 +- .../validation/SOL004MetaDirectoryValidator.java | 121 +- .../SOL004Version3MetaDirectoryValidator.java | 7 +- .../SOL004Version4MetaDirectoryValidator.java | 5 +- .../orchestration/csar/validation/Validator.java | 7 +- .../csar/validation/ValidatorFactory.java | 6 +- .../exception/MissingCertificateException.java | 1 - .../csar/validation/utils/FileExtractor.java | 3 +- .../csar/validation/utils/InternalFilesFilter.java | 4 +- .../csar/validation/utils/ValidatorUtils.java | 11 +- .../InvalidManifestMetadataException.java | 5 +- .../OrchestrationTemplateHandlerException.java | 5 +- .../process/OrchestrationProcessFactory.java | 70 +- .../OrchestrationTemplateProcessCsarHandler.java | 205 +- .../OrchestrationTemplateProcessHandler.java | 5 +- .../OrchestrationTemplateProcessZipHandler.java | 263 +- .../security/SecurityManager.java | 91 +- .../types/ComponentValidationResult.java | 34 +- .../types/CompositionEntityResponse.java | 47 +- .../types/ConfigConstants.java | 9 +- .../types/DeploymentFlavorValidationResult.java | 33 +- .../vendorsoftwareproduct/types/LicensingData.java | 33 +- .../types/ListComputeResponse.java | 36 +- .../types/OnboardPackage.java | 4 +- .../types/OnboardPackageInfo.java | 14 +- .../types/OnboardSignedPackage.java | 6 +- .../types/OrchestrationTemplateActionResponse.java | 145 +- .../types/QuestionnaireResponse.java | 48 +- .../types/QuestionnaireValidationResult.java | 33 +- .../types/UploadFileResponse.java | 142 +- .../types/UploadFileStatus.java | 8 +- .../types/UploadFileStructure.java | 25 +- .../types/ValidationResponse.java | 134 +- .../schemagenerator/MonitoringUploadStatus.java | 65 +- .../types/zusammen/ItemProperties.java | 13 +- .../utils/ComponentDependencyTracker.java | 78 +- .../utils/VendorSoftwareProductUtils.java | 151 +- .../sdc/common/errors/BaseErrorBuilder.java | 20 +- .../openecomp/sdc/common/errors/CoreException.java | 27 +- .../openecomp/sdc/common/errors/ErrorCategory.java | 78 +- .../org/openecomp/sdc/common/errors/ErrorCode.java | 139 +- .../sdc/common/errors/ErrorCodeAndMessage.java | 58 +- .../sdc/common/errors/GeneralErrorBuilder.java | 38 +- .../sdc/common/errors/JsonMappingErrorBuilder.java | 41 +- .../org/openecomp/sdc/common/errors/Messages.java | 119 +- .../common/errors/SdcConfigurationException.java | 18 +- .../sdc/common/errors/SdcRuntimeException.java | 19 +- .../sdc/common/errors/ValidationErrorBuilder.java | 58 +- .../sdc/common/exception/ZipException.java | 1 - .../org/openecomp/sdc/common/utils/CommonUtil.java | 188 +- .../org/openecomp/sdc/common/utils/SdcCommon.java | 31 +- .../org/openecomp/conflicts/ItemMergeHandler.java | 24 +- .../conflicts/ItemMergeHandlerFactory.java | 19 +- .../org/openecomp/conflicts/dao/ConflictsDao.java | 14 +- .../conflicts/dao/ConflictsDaoFactory.java | 10 +- .../org/openecomp/conflicts/types/Conflict.java | 45 +- .../openecomp/conflicts/types/ConflictInfo.java | 64 +- .../conflicts/types/ConflictResolution.java | 46 +- .../conflicts/types/ItemVersionConflict.java | 43 +- .../org/openecomp/conflicts/types/Resolution.java | 7 +- .../conflicts/ItemMergeHandlerFactoryImpl.java | 45 +- .../dao/impl/zusammen/ConflictsDaoFactoryImpl.java | 18 +- .../dao/impl/zusammen/ConflictsDaoImpl.java | 261 +- .../ItemVersionConflictConvertorFromZusammen.java | 84 +- .../openecomp/conflicts/impl/VspMergeHandler.java | 298 +- .../applicationconfig/ApplicationConfig.java | 15 +- .../ApplicationConfigFactory.java | 12 +- .../dao/ApplicationConfigDao.java | 10 +- .../dao/ApplicationConfigDaoFactory.java | 14 +- .../impl/ApplicationConfigDaoCassandraImpl.java | 134 +- .../dao/impl/ApplicationConfigDaoFactoryImpl.java | 17 +- .../dao/type/ApplicationConfigEntity.java | 16 +- .../impl/ApplicationConfigFactoryImpl.java | 16 +- .../impl/ApplicationConfigImpl.java | 63 +- .../applicationconfig/type/ConfigurationData.java | 5 +- .../core/factory/api/AbstractFactory.java | 52 +- .../core/factory/impl/AbstractFactoryBase.java | 38 +- .../core/factory/impl/FactoryManager.java | 33 +- .../core/factory/AbstractContextFactory.java | 8 +- .../core/factory/FactoriesConfigImpl.java | 48 +- .../org/openecomp/core/factory/FactoryConfig.java | 20 +- .../core/factory/api/AbstractComponentFactory.java | 6 +- .../core/factory/api/FactoriesConfiguration.java | 8 +- .../main/java/org/openecomp/core/dao/BaseDao.java | 1 - .../org/openecomp/core/dao/UniqueValueDao.java | 1 - .../openecomp/core/dao/UniqueValueDaoFactory.java | 1 - .../core/dao/types/UniqueValueEntity.java | 3 - .../org/openecomp/core/nosqldb/api/NoSqlDb.java | 2 - .../core/nosqldb/factory/NoSqlDbFactory.java | 3 - .../org/openecomp/core/util/UniqueValueUtil.java | 56 +- .../openecomp/core/dao/impl/CassandraBaseDao.java | 42 +- .../core/dao/impl/UniqueValueCassandraDaoImpl.java | 54 +- .../core/dao/impl/UniqueValueDaoFactoryImpl.java | 16 +- .../cassandra/CassandraNoSqlDbFactoryImpl.java | 27 +- .../impl/cassandra/CassandraNoSqlDbImpl.java | 42 +- .../impl/cassandra/CassandraSessionFactory.java | 77 +- .../core/nosqldb/util/CassandraUtils.java | 120 +- .../core/nosqldb/util/ConfigurationManager.java | 420 +- .../sdc/common/session/SessionContext.java | 1 - .../sdc/common/session/SessionContextProvider.java | 1 - .../session/SessionContextProviderFactory.java | 4 +- .../org/openecomp/sdc/common/session/User.java | 1 - .../session/impl/AsdcSessionContextProvider.java | 10 +- .../impl/SessionContextProviderFactoryImpl.java | 1 - .../openecomp/core/utilities/CommonMethods.java | 56 +- .../RequirementDefinitionDeserializer.java | 115 +- .../exception/NewInstanceRuntimeException.java | 1 - .../core/utilities/file/FileContentHandler.java | 10 +- .../openecomp/core/utilities/file/FileUtils.java | 477 +- .../utilities/json/JsonSchemaDataGenerator.java | 253 +- .../openecomp/core/utilities/json/JsonUtil.java | 33 +- .../orchestration/OnboardingTypesEnum.java | 15 +- .../org/openecomp/convertor/ElementConvertor.java | 36 +- .../core/zusammen/api/ZusammenAdaptor.java | 100 +- .../core/zusammen/api/ZusammenAdaptorFactory.java | 11 +- .../openecomp/core/zusammen/api/ZusammenUtil.java | 64 +- .../main/java/org/openecomp/types/AsdcElement.java | 226 +- .../org/openecomp/types/ElementPropertyName.java | 3 +- .../core/zusammen/db/ZusammenConnector.java | 81 +- .../core/zusammen/db/ZusammenConnectorFactory.java | 11 +- .../db/impl/ZusammenConnectorFactoryImpl.java | 20 +- .../zusammen/db/impl/ZusammenConnectorImpl.java | 594 +- .../impl/CassandraConnectionInitializer.java | 18 +- .../impl/ItemElementLoggerTargetServiceName.java | 23 +- .../zusammen/impl/ZusammenAdaptorFactoryImpl.java | 17 +- .../core/zusammen/impl/ZusammenAdaptorImpl.java | 452 +- .../openecomp/sdc/healing/api/HealingManager.java | 17 +- .../org/openecomp/sdc/healing/dao/HealingDao.java | 9 +- .../sdc/healing/factory/HealingManagerFactory.java | 8 +- .../openecomp/sdc/healing/interfaces/Healer.java | 5 +- .../sdc/healing/types/ConfigConstants.java | 8 +- .../org/openecomp/sdc/healing/types/HealCode.java | 10 +- .../openecomp/sdc/healing/types/HealerType.java | 8 +- .../sdc/healing/dao/impl/HealingDaoImpl.java | 50 +- .../healing/impl/HealingManagerFactoryImpl.java | 9 +- .../sdc/healing/impl/HealingManagerImpl.java | 354 +- .../sdc/healing/utils/HealingConfiguration.java | 6 +- .../openecomp/sdc/healing/utils/HealingUtil.java | 6 +- .../sdc/healing/healers/ComponentDataHealer.java | 53 +- .../healers/ManufacturerReferenceNumberHealer.java | 131 +- .../sdc/healing/healers/NetworkPackageHealer.java | 278 +- .../openecomp/sdc/healing/healers/OwnerHealer.java | 105 +- .../healing/healers/ToscaServiceModelHealer.java | 146 +- .../heat/datatypes/DefinedHeatParameterTypes.java | 31 +- .../openecomp/sdc/heat/datatypes/HeatBoolean.java | 21 +- .../heat/datatypes/ToscaScalarUnitFrequency.java | 7 +- .../sdc/heat/datatypes/ToscaScalarUnitSize.java | 7 +- .../sdc/heat/datatypes/ToscaScalarUnitTime.java | 8 +- .../sdc/heat/datatypes/ToscaScalarUnitTypes.java | 7 +- .../sdc/heat/datatypes/manifest/FileData.java | 8 +- .../heat/datatypes/manifest/ManifestContent.java | 2 - .../sdc/heat/datatypes/manifest/ManifestFile.java | 1 - .../sdc/heat/datatypes/model/Constraint.java | 5 +- .../datatypes/model/ContrailResourceTypes.java | 8 +- .../datatypes/model/ContrailV2ResourceTypes.java | 4 +- .../sdc/heat/datatypes/model/Environment.java | 2 - .../datatypes/model/HeatOrchestrationTemplate.java | 2 - .../heat/datatypes/model/HeatPseudoParameters.java | 6 +- .../heat/datatypes/model/HeatResourcesTypes.java | 17 +- .../openecomp/sdc/heat/datatypes/model/Output.java | 1 - .../sdc/heat/datatypes/model/Parameter.java | 2 - .../sdc/heat/datatypes/model/ParameterGroup.java | 2 - .../sdc/heat/datatypes/model/ParameterType.java | 1 - .../sdc/heat/datatypes/model/PolicyTypes.java | 3 - .../datatypes/model/PropertiesMapKeyTypes.java | 7 +- .../sdc/heat/datatypes/model/Resource.java | 12 +- .../model/ResourceReferenceFunctions.java | 8 +- .../model/ResourceTypeToMessageString.java | 5 +- .../sdc/heat/datatypes/structure/Artifact.java | 5 - .../datatypes/structure/HeatStructureTree.java | 49 +- .../structure/ValidationStructureList.java | 1 - .../openecomp/sdc/heat/services/ErrorCodes.java | 9 +- .../openecomp/sdc/heat/services/HeatConstants.java | 14 +- .../sdc/heat/services/HeatResourceUtil.java | 52 +- .../sdc/heat/services/HeatStructureUtil.java | 34 +- .../sdc/heat/services/manifest/ManifestUtil.java | 28 +- .../sdc/heat/services/tree/HeatTreeManager.java | 65 +- .../heat/services/tree/HeatTreeManagerUtil.java | 89 +- .../sdc/heat/services/tree/ToscaTreeManager.java | 17 +- .../sdc/itempermissions/PermissionsRules.java | 8 +- .../itempermissions/PermissionsRulesFactory.java | 10 +- .../sdc/itempermissions/PermissionsServices.java | 18 +- .../PermissionsServicesFactory.java | 10 +- .../itempermissions/dao/ItemPermissionsDao.java | 12 +- .../dao/ItemPermissionsDaoFactory.java | 7 +- .../itempermissions/dao/UserPermissionsDao.java | 6 +- .../dao/UserPermissionsDaoFactory.java | 1 - .../errors/PermissionsErrorMessages.java | 22 +- .../errors/PermissionsErrorMessagesBuilder.java | 31 +- .../notifications/NotificationConstants.java | 3 +- .../type/ItemPermissionsEntity.java | 19 +- .../dao/impl/ItemPermissionsDaoFactoryImpl.java | 1 - .../dao/impl/ItemPermissionsDaoImpl.java | 23 +- .../dao/impl/PermissionsServicesImpl.java | 40 +- .../dao/impl/PrmissionsServicesFactoryImpl.java | 15 +- .../dao/impl/UserPermissionsDaoFactoryImpl.java | 1 - .../dao/impl/UserPermissionsDaoImpl.java | 19 +- .../itempermissions/servlet/PermissionsFilter.java | 24 +- .../impl/PermissionsRulesFactoryImpl.java | 14 +- .../itempermissions/impl/PermissionsRulesImpl.java | 79 +- .../impl/types/PermissionActionTypes.java | 5 +- .../impl/types/PermissionTypes.java | 10 +- .../org/openecomp/sdc/action/ActionConstants.java | 147 +- .../sdc/action/dao/ActionArtifactDao.java | 12 +- .../sdc/action/dao/ActionArtifactDaoFactory.java | 12 +- .../org/openecomp/sdc/action/dao/ActionDao.java | 26 +- .../openecomp/sdc/action/dao/ActionDaoFactory.java | 11 +- .../sdc/action/dao/types/ActionArtifactEntity.java | 62 +- .../sdc/action/dao/types/ActionEntity.java | 158 +- .../action/dao/types/OpenEcompComponentEntity.java | 39 +- .../sdc/action/errors/ActionErrorConstants.java | 198 +- .../sdc/action/errors/ActionException.java | 74 +- .../sdc/action/errors/ActionExceptionMapper.java | 194 +- .../sdc/action/errors/ActionExceptionResponse.java | 72 +- .../sdc/action/logging/CategoryLogLevel.java | 13 +- .../org/openecomp/sdc/action/types/Action.java | 476 +- .../openecomp/sdc/action/types/ActionArtifact.java | 230 +- .../sdc/action/types/ActionArtifactProtection.java | 10 +- .../sdc/action/types/ActionLogResponseCode.java | 118 +- .../openecomp/sdc/action/types/ActionRequest.java | 5 +- .../openecomp/sdc/action/types/ActionStatus.java | 12 +- .../sdc/action/types/ActionSubOperation.java | 75 +- .../sdc/action/types/OpenEcompComponent.java | 139 +- .../org/openecomp/sdc/action/util/ActionUtil.java | 127 +- .../openecomp/sdc/healthcheck/dao/ActionDao.java | 26 +- .../sdc/healthcheck/dao/ActionDaoFactory.java | 11 +- .../dao/impl/ActionArtifactDaoFactoryImpl.java | 17 +- .../sdc/action/dao/impl/ActionArtifactDaoImpl.java | 184 +- .../sdc/action/dao/impl/ActionDaoFactoryImpl.java | 17 +- .../sdc/action/dao/impl/ActionDaoImpl.java | 246 +- .../sdc/activitylog/dao/ActivityLogDao.java | 2 +- .../sdc/activitylog/dao/ActivityLogDaoFactory.java | 2 +- .../activitylog/dao/type/ActivityLogEntity.java | 62 +- .../sdc/activitylog/dao/type/ActivityType.java | 6 +- .../dao/impl/ActivityLogDaoCassandraImpl.java | 58 +- .../dao/impl/ActivityLogDaoFactoryImpl.java | 11 +- .../configuration/ImplementationConfiguration.java | 27 +- .../openecomp/sdc/datatypes/error/ErrorLevel.java | 10 +- .../sdc/datatypes/error/ErrorMessage.java | 58 +- .../openecomp/sdc/datatypes/model/AsdcModel.java | 6 +- .../openecomp/sdc/datatypes/model/ElementType.java | 55 +- .../openecomp/sdc/datatypes/model/ItemType.java | 10 +- .../model/heat/ForbiddenHeatResourceTypes.java | 47 +- .../core/enrichment/api/EnrichmentManager.java | 27 +- .../factory/EnrichmentManagerFactory.java | 14 +- .../core/enrichment/types/ArtifactCategory.java | 65 +- .../core/enrichment/types/CeilometerMetric.java | 13 +- .../core/enrichment/types/CeilometerMetrics.java | 2 +- .../types/ComponentMonitoringUploadInfo.java | 39 +- .../enrichment/types/ComponentProcessInfo.java | 6 - .../core/enrichment/types/EntityInfo.java | 7 +- .../types/InformationArtifactFolderNames.java | 9 +- .../enrichment/types/MonitoringArtifactInfo.java | 3 - .../enrichment/types/MonitoringUploadType.java | 13 +- .../impl/EnrichmentManagerFactoryImpl.java | 15 +- .../sdc/enrichment/impl/EnrichmentManagerImpl.java | 91 +- .../openecomp/sdc/enrichment/EnrichmentInfo.java | 11 +- .../enrichment/factory/EnricherHandlerFactory.java | 7 +- .../impl/EnricherHandlerFactoryImpl.java | 6 +- .../sdc/enrichment/impl/EnricherHandlerImpl.java | 11 +- .../artifact/ExternalArtifactEnricher.java | 69 +- .../external/artifact/MonitoringMibEnricher.java | 377 +- .../external/artifact/ProcessArtifactEnricher.java | 153 +- .../artifact/VspInformationArtifactEnricher.java | 102 +- .../tosca/AbstractSubstituteToscaEnricher.java | 169 +- .../impl/tosca/ComponentQuestionnaireData.java | 155 +- .../impl/tosca/PortMirroringEnricher.java | 125 +- .../sdc/enrichment/impl/tosca/ToscaEnricher.java | 75 +- .../PortMirroringConnectionPointDescription.java | 154 +- .../enrichment/impl/util/EnrichmentConstants.java | 23 +- .../openecomp/sdc/enrichment/inter/Enricher.java | 8 +- .../sdc/enrichment/inter/EnricherHandler.java | 6 +- .../inter/ExternalArtifactEnricherInterface.java | 17 +- .../externaltesting/api/ClientConfiguration.java | 10 +- .../api/ExternalTestingManager.java | 14 +- .../api/RemoteTestingEndpointDefinition.java | 36 +- .../core/externaltesting/api/TestErrorBody.java | 27 +- .../core/externaltesting/api/TestTreeNode.java | 31 +- .../api/VtpNameDescriptionPair.java | 19 +- .../core/externaltesting/api/VtpTestCase.java | 30 +- .../core/externaltesting/api/VtpTestCaseInput.java | 28 +- .../externaltesting/api/VtpTestCaseOutput.java | 4 +- .../api/VtpTestExecutionRequest.java | 21 +- .../api/VtpTestExecutionResponse.java | 52 +- .../errors/ExternalTestingException.java | 50 +- .../ExternalTestingInitializationException.java | 14 +- .../factory/ExternalTestingManagerFactory.java | 8 +- .../impl/ExternalTestingManagerImpl.java | 156 +- .../externaltesting/impl/TestingAccessConfig.java | 7 +- .../openecomp/sdc/logging/LoggingConstants.java | 2 - .../org/openecomp/sdc/logging/api/AuditData.java | 29 +- .../org/openecomp/sdc/logging/api/ContextData.java | 25 +- .../java/org/openecomp/sdc/logging/api/Logger.java | 5 +- .../openecomp/sdc/logging/api/LoggerFactory.java | 39 +- .../openecomp/sdc/logging/api/LoggingContext.java | 9 +- .../org/openecomp/sdc/logging/api/MetricsData.java | 28 +- .../openecomp/sdc/logging/api/ServiceBinder.java | 17 +- .../openecomp/sdc/logging/api/package-info.java | 8 +- .../sdc/logging/servlet/AuditTracker.java | 23 +- .../sdc/logging/servlet/CombinedTracker.java | 9 +- .../sdc/logging/servlet/ContextTracker.java | 24 +- .../openecomp/sdc/logging/servlet/HttpHeader.java | 18 +- .../logging/servlet/RequestProcessingResult.java | 1 - .../sdc/logging/servlet/ServiceNameFormatter.java | 1 - .../org/openecomp/sdc/logging/servlet/Tracker.java | 7 +- .../servlet/jaxrs/LoggingRequestFilter.java | 12 +- .../servlet/jaxrs/LoggingResponseFilter.java | 12 +- .../sdc/logging/spi/LoggerCreationService.java | 5 +- .../sdc/logging/spi/LoggingContextService.java | 19 +- .../sdc/logging/spi/LoggingServiceProvider.java | 9 +- .../sdc/logging/context/HostAddressCache.java | 67 +- .../openecomp/sdc/logging/context/InstanceId.java | 7 +- .../logging/logback/EventTypeDiscriminator.java | 20 +- .../openecomp/sdc/logging/slf4j/AuditField.java | 4 +- .../org/openecomp/sdc/logging/slf4j/Context.java | 9 +- .../openecomp/sdc/logging/slf4j/ContextField.java | 4 +- .../sdc/logging/slf4j/ContextProvider.java | 2 +- .../sdc/logging/slf4j/GlobalContextProvider.java | 4 - .../sdc/logging/slf4j/MDCCallableWrapper.java | 4 - .../openecomp/sdc/logging/slf4j/MDCDelegate.java | 23 +- .../org/openecomp/sdc/logging/slf4j/MDCField.java | 2 - .../sdc/logging/slf4j/MDCRunnableWrapper.java | 4 - .../org/openecomp/sdc/logging/slf4j/Markers.java | 9 +- .../openecomp/sdc/logging/slf4j/MetricsField.java | 5 +- .../sdc/logging/slf4j/RequestContextProvider.java | 10 +- .../sdc/logging/slf4j/SLF4JLoggerWrapper.java | 33 +- .../logging/slf4j/SLF4JLoggingServiceProvider.java | 1 - .../logging/servlet/spring/LoggingInterceptor.java | 24 +- .../core/model/dao/EnrichedServiceModelDao.java | 16 +- .../model/dao/EnrichedServiceModelDaoFactory.java | 14 +- .../core/model/dao/ServiceArtifactDaoInter.java | 24 +- .../openecomp/core/model/dao/ServiceModelDao.java | 22 +- .../core/model/dao/ServiceModelDaoFactory.java | 11 +- .../RetrieveServiceTemplateFromDbErrorBuilder.java | 22 +- .../model/types/EnrichedServiceArtifactEntity.java | 17 +- .../model/types/EnrichedServiceTemplateEntity.java | 17 +- .../core/model/types/ServiceArtifact.java | 5 +- .../core/model/types/ServiceArtifactEntity.java | 19 +- .../openecomp/core/model/types/ServiceElement.java | 2 - .../core/model/types/ServiceElementEntity.java | 13 +- .../core/model/types/ServiceTemplate.java | 2 - .../core/model/types/ServiceTemplateEntity.java | 17 +- .../impl/EnrichedServiceModelDaoFactoryImpl.java | 18 +- .../sdc/model/impl/ServiceModelDaoFactoryImpl.java | 17 +- .../sdc/model/impl/zusammen/ElementType.java | 11 +- .../EnrichedServiceModelDaoZusammenImpl.java | 59 +- .../impl/zusammen/ServiceModelDaoZusammenImpl.java | 410 +- .../sdc/model/impl/zusammen/StructureElement.java | 14 +- .../destinationprovider/DestinationProvider.java | 1 + .../sdc/notification/dao/LastNotificationDao.java | 9 +- .../sdc/notification/dao/NotificationsDao.java | 11 +- .../sdc/notification/dao/SubscribersDao.java | 6 +- .../dao/types/LastSeenNotificationEntity.java | 6 - .../notification/dao/types/NotificationEntity.java | 9 - .../notification/dao/types/SubscribersEntity.java | 4 - .../sdc/notification/dtos/NotificationsStatus.java | 14 +- .../exceptons/NotificationNotExistException.java | 5 +- .../factories/LastNotificationDaoFactory.java | 9 +- .../NotificationPropagationManagerFactory.java | 3 - .../factories/NotificationsDaoFactory.java | 9 +- .../factories/NotificationsServiceFactory.java | 9 +- .../factories/PropagationServiceFactory.java | 3 - .../factories/SubscribersDaoFactory.java | 3 - .../factories/SubscriptionServiceFactory.java | 3 - .../services/NotificationPropagationManager.java | 4 +- .../services/NotificationsService.java | 14 +- .../notification/services/SubscriptionService.java | 1 + .../impl/MulticastDestination.java | 15 +- .../impl/UnicastDestination.java | 8 +- .../dao/impl/LastNotificationDaoCassandraImpl.java | 96 +- .../dao/impl/NotificationsDaoCassandraImpl.java | 135 +- .../dao/impl/SubscribersDaoCassandraImpl.java | 25 +- .../impl/LastNotificationDaoFactoryImpl.java | 17 +- .../NotificationPropagationManagerFactoryImpl.java | 12 +- .../impl/NotificationsDaoFactoryImpl.java | 16 +- .../impl/NotificationsServiceFactoryImpl.java | 19 +- .../impl/PropagationServiceFactoryImpl.java | 9 +- .../factories/impl/SubscribersDaoFactoryImpl.java | 7 +- .../impl/SubscriptionServiceFactoryImpl.java | 10 +- .../impl/NotificationPropagationManagerImpl.java | 13 +- .../services/impl/NotificationsServiceImpl.java | 69 +- .../services/impl/PropagationServiceImpl.java | 36 +- .../services/impl/SubscriptionServiceImpl.java | 6 +- .../websocket/NotificationWebsocketHandler.java | 109 +- .../notification/config/ConfigurationManager.java | 44 +- .../notification/types/NotificationEntityDto.java | 1 - .../notification/types/NotificationsStatusDto.java | 5 +- .../workers/NewNotificationsReader.java | 7 +- .../notification/workers/NotificationReceiver.java | 17 +- .../notification/workers/NotificationWorker.java | 164 +- .../impl/NewNotificationsReaderRestImpl.java | 19 +- .../generator/datatypes/tosca/ComputeFlavor.java | 2 - .../datatypes/tosca/DeploymentFlavorModel.java | 3 - .../generator/datatypes/tosca/LicenseFlavor.java | 2 - .../datatypes/tosca/MultiFlavorVfcImage.java | 2 - .../sdc/generator/datatypes/tosca/VendorInfo.java | 2 - .../generator/datatypes/tosca/VspModelInfo.java | 2 - .../sdc/generator/util/GeneratorConstants.java | 13 +- .../services/ManualVspToscaGenerationService.java | 559 +- .../sdc/generator/core/utils/GeneratorUtils.java | 112 +- .../core/translator/api/HeatToToscaTranslator.java | 33 +- .../translator/datatypes/TranslatorOutput.java | 13 +- .../factory/HeatToToscaTranslatorFactory.java | 16 +- .../datatypes/heattotosca/AttachedPropertyVal.java | 72 +- .../datatypes/heattotosca/AttachedResourceId.java | 73 +- .../heattotosca/PropertyRegexMatcher.java | 92 +- .../datatypes/heattotosca/ReferenceType.java | 9 +- .../datatypes/heattotosca/TranslationContext.java | 1106 ++-- .../heattotosca/to/ContrailServiceInstanceTo.java | 7 +- .../heattotosca/to/FileDataCollection.java | 217 +- .../heattotosca/to/ResourceFileDataAndIDs.java | 78 +- .../datatypes/heattotosca/to/TranslateTo.java | 204 +- .../heattotosca/to/TranslatedHeatResource.java | 42 +- .../composition/NodeTemplateInformation.java | 55 +- .../composition/UnifiedCompositionData.java | 181 +- .../composition/UnifiedCompositionEntity.java | 22 +- .../composition/UnifiedCompositionMode.java | 8 +- .../composition/UnifiedSubstitutionData.java | 322 +- .../composition/commands/CommandImplNames.java | 15 +- ...UnifiedSubstitutionNodeTemplateIdGenerator.java | 7 +- .../impl/ComputeNewNodeTemplateIdGenerator.java | 14 +- .../impl/PortNewNodeTemplateIdGenerator.java | 35 +- .../SubInterfaceNewNodeTemplateIdGenerator.java | 68 +- .../composition/to/UnifiedCompositionTo.java | 95 +- .../consolidation/ComputeConsolidationData.java | 19 +- .../ComputeConsolidationDataHandler.java | 135 +- .../ComputeTemplateConsolidationData.java | 13 +- .../consolidation/ConsolidationData.java | 13 +- .../consolidation/ConsolidationDataHandler.java | 28 +- .../consolidation/EntityConsolidationData.java | 84 +- .../FileComputeConsolidationData.java | 25 +- .../consolidation/FileNestedConsolidationData.java | 18 +- .../consolidation/FilePortConsolidationData.java | 74 +- .../consolidation/GetAttrFuncData.java | 90 +- .../consolidation/NestedConsolidationData.java | 16 +- .../NestedConsolidationDataHandler.java | 123 +- .../NestedTemplateConsolidationData.java | 5 +- .../consolidation/PortConsolidationData.java | 52 +- .../PortConsolidationDataHandler.java | 96 +- .../PortTemplateConsolidationData.java | 86 +- .../consolidation/RequirementAssignmentData.java | 94 +- .../SubInterfaceConsolidationDataHandler.java | 152 +- .../SubInterfaceTemplateConsolidationData.java | 87 +- .../TypeComputeConsolidationData.java | 58 +- .../HeatToToscaTranslatorFactoryImpl.java | 16 +- .../heattotosca/HeatToToscaTranslatorImpl.java | 162 +- .../services/heattotosca/ConfigConstants.java | 57 +- .../heattotosca/ConsolidationDataUtil.java | 218 +- .../heattotosca/ConsolidationEntityType.java | 36 +- .../services/heattotosca/ConsolidationService.java | 1336 ++--- .../ConsolidationTypesConnectivity.java | 22 +- .../translator/services/heattotosca/Constants.java | 17 +- .../services/heattotosca/FunctionTranslation.java | 2 - .../heattotosca/FunctionTranslationFactory.java | 25 +- .../heattotosca/HeatToToscaLogConstants.java | 194 +- .../services/heattotosca/HeatToToscaUtil.java | 575 +- .../services/heattotosca/NameExtractor.java | 8 +- .../services/heattotosca/NameExtractorUtil.java | 79 +- .../services/heattotosca/ResourceTranslation.java | 18 +- .../heattotosca/ResourceTranslationFactory.java | 75 +- .../services/heattotosca/TranslationService.java | 232 +- .../services/heattotosca/UnifiedComposition.java | 16 +- .../heattotosca/UnifiedCompositionManager.java | 144 +- .../heattotosca/UnifiedCompositionService.java | 6044 ++++++++------------ .../heattotosca/UnifiedCompositionUtil.java | 294 +- ...ateResourceIdsInDifferentFilesErrorBuilder.java | 12 +- .../IncorrectResourceReferenceErrorBuilder.java | 48 +- .../errors/InvalidPropertyValueErrorBuilder.java | 36 +- .../MissingMandatoryPropertyErrorBuilder.java | 30 +- .../NotInSyncNumberOfInterfacesErrorBuilder.java | 32 +- ...ReferenceToUnsupportedResourceErrorBuilder.java | 46 +- .../ResourceNotFoundInHeatFileErrorBuilder.java | 48 +- .../heattotosca/errors/TranslatorErrorCodes.java | 22 +- .../globaltypes/GlobalTypesGenerator.java | 91 +- .../globaltypes/GlobalTypesServiceTemplates.java | 52 +- .../helper/ContrailTranslationHelper.java | 179 +- .../ContrailV2VirtualMachineInterfaceHelper.java | 233 +- .../ResourceTranslationNeutronPortHelper.java | 91 +- .../helper/VolumeTranslationHelper.java | 210 +- .../FunctionTranslationGetAttrImpl.java | 114 +- .../FunctionTranslationGetFileImpl.java | 17 +- .../FunctionTranslationGetParamImpl.java | 18 +- .../FunctionTranslationGetResourceImpl.java | 12 +- .../functiontranslation/FunctionTranslator.java | 13 +- .../NameExtractorContrailComputeImpl.java | 22 +- .../nameextractor/NameExtractorNovaServerImpl.java | 21 +- .../BaseResourceConnection.java | 192 +- .../ContrailPortToNetResourceConnection.java | 115 +- ...ontrailV2VlanToInterfaceResourceConnection.java | 73 +- ...ntrailV2VmInterfaceToNetResourceConnection.java | 80 +- .../NovaToVolResourceConnection.java | 120 +- .../PortToNetResourceConnection.java | 66 +- .../ResourceConnectionUsingCapabilityHelper.java | 132 +- .../ResourceConnectionUsingRequirementHelper.java | 84 +- .../ResourceTranslationBase.java | 179 +- ...ourceTranslationCinderVolumeAttachmentImpl.java | 136 +- .../ResourceTranslationCinderVolumeImpl.java | 17 +- ...esourceTranslationContrailAttachPolicyImpl.java | 57 +- ...sourceTranslationContrailNetworkPolicyImpl.java | 12 +- ...urceTranslationContrailServiceInstanceImpl.java | 433 +- ...urceTranslationContrailServiceTemplateImpl.java | 41 +- ...urceTranslationContrailV2NetworkPolicyImpl.java | 9 +- ...rceTranslationContrailV2VirtualNetworkImpl.java | 63 +- ...eTranslationContrailV2VlanSubInterfaceImpl.java | 72 +- ...sourceTranslationContrailV2VmInterfaceImpl.java | 57 +- ...ourceTranslationContrailVirtualNetworkImpl.java | 9 +- .../ResourceTranslationDefaultImpl.java | 12 +- .../ResourceTranslationNestedImpl.java | 187 +- .../ResourceTranslationNeutronNetImpl.java | 27 +- .../ResourceTranslationNeutronPortImpl.java | 159 +- ...esourceTranslationNeutronSecurityGroupImpl.java | 16 +- .../ResourceTranslationNeutronSubnetImpl.java | 76 +- .../ResourceTranslationNovaServerGroupsImpl.java | 61 +- .../ResourceTranslationNovaServerImpl.java | 305 +- .../ResourceTranslationResourceGroupImpl.java | 95 +- .../SecurityRulesToPortResourceConnection.java | 60 +- .../UnifiedCompositionCatalogInstance.java | 92 +- .../UnifiedCompositionNestedSingleCompute.java | 49 +- .../UnifiedCompositionScalingInstances.java | 71 +- .../UnifiedCompositionSingleSubstitution.java | 103 +- .../TranslatorHeatToToscaParameterConverter.java | 528 +- .../TranslatorHeatToToscaPropertyConverter.java | 235 +- .../sdc/translator/utils/ResourceWalker.java | 182 +- .../core/validation/ErrorMessageCode.java | 4 +- .../core/validation/api/ValidationManager.java | 17 +- .../errors/ErrorMessagesFormatBuilder.java | 41 +- .../factory/ValidationManagerFactory.java | 12 +- .../validation/types/FileValidationContext.java | 45 +- .../validation/types/GlobalValidationContext.java | 155 +- .../core/validation/types/MessageContainer.java | 13 +- .../core/validation/util/MessageContainerUtil.java | 91 +- .../impl/ValidationManagerFactoryImpl.java | 15 +- .../sdc/validation/impl/ValidationManagerImpl.java | 73 +- .../sdc/validation/services/ValidationFactory.java | 69 +- .../impl/util/HeatValidationService.java | 518 +- .../validation/impl/util/YamlValidatorUtil.java | 37 +- .../impl/validators/ContrailValidator.java | 206 +- .../impl/validators/FileExtensionUtils.java | 10 +- .../ForbiddenResourceGuideLineValidator.java | 152 +- .../impl/validators/GlobalContextUtil.java | 25 +- .../impl/validators/HeatResourceValidator.java | 307 +- .../validation/impl/validators/HeatValidator.java | 888 ++- .../impl/validators/ManifestValidator.java | 251 +- .../NamingConventionGuideLineValidator.java | 23 +- .../impl/validators/PmDictionaryValidator.java | 38 +- .../SharedResourceGuideLineValidator.java | 284 +- .../validation/impl/validators/YamlValidator.java | 32 +- .../ContrailNetworkPolicyResourceValidator.java | 87 +- .../heatresource/NestedResourceValidator.java | 92 +- .../heatresource/NeutronPortResourceValidator.java | 122 +- .../NeutronSecurityGroupResourceValidator.java | 66 +- .../NovaServerGroupResourceValidator.java | 141 +- .../heatresource/NovaServerResourceValidator.java | 132 +- .../ResourceGroupResourceValidator.java | 165 +- .../VirtualMachineInterfaceValidator.java | 201 +- ...ilServiceInstanceNamingConventionValidator.java | 81 +- ...ilServiceTemplateNamingConventionValidator.java | 242 +- .../NeutronPortNamingConventionValidator.java | 81 +- ...vaServerNamingConventionGuideLineValidator.java | 769 +-- .../VirtualMachineInterfaceGuidelineValidator.java | 290 +- .../validation/tos/ContrailResourcesMappingTo.java | 148 +- .../sdc/validation/type/ValidatorConstants.java | 7 +- .../sdc/validation/ResourceValidator.java | 7 +- .../org/openecomp/sdc/validation/Validator.java | 11 +- .../sdc/validation/base/ResourceBaseValidator.java | 203 +- .../sdc/validation/type/ConfigConstants.java | 17 +- .../type/HeatResourceValidationContext.java | 33 +- .../type/NamingConventionValidationContext.java | 9 +- .../sdc/validation/util/ValidationUtil.java | 304 +- .../sdc/vendorlicense/HealingServiceFactory.java | 11 +- .../VendorLicenseArtifactServiceFactory.java | 14 +- .../sdc/vendorlicense/VendorLicenseConstants.java | 36 +- .../sdc/vendorlicense/VendorLicenseUtil.java | 17 +- .../sdc/vendorlicense/dao/EntitlementPoolDao.java | 19 +- .../dao/EntitlementPoolDaoFactory.java | 15 +- .../sdc/vendorlicense/dao/FeatureGroupDao.java | 29 +- .../vendorlicense/dao/FeatureGroupDaoFactory.java | 14 +- .../sdc/vendorlicense/dao/LicenseAgreementDao.java | 56 +- .../dao/LicenseAgreementDaoFactory.java | 15 +- .../sdc/vendorlicense/dao/LicenseKeyGroupDao.java | 26 +- .../dao/LicenseKeyGroupDaoFactory.java | 15 +- .../openecomp/sdc/vendorlicense/dao/LimitDao.java | 2 +- .../sdc/vendorlicense/dao/LimitDaoFactory.java | 7 +- .../vendorlicense/dao/VendorLicenseModelDao.java | 6 +- .../dao/VendorLicenseModelDaoFactory.java | 14 +- .../dao/types/AggregationFunction.java | 11 +- .../sdc/vendorlicense/dao/types/ChoiceOrOther.java | 203 +- .../vendorlicense/dao/types/EntitlementMetric.java | 5 +- .../dao/types/EntitlementPoolEntity.java | 706 ++- .../dao/types/EntitlementPoolType.java | 7 +- .../vendorlicense/dao/types/EntitlementTime.java | 12 +- .../dao/types/FeatureGroupEntity.java | 364 +- .../vendorlicense/dao/types/FeatureGroupModel.java | 81 +- .../dao/types/LicenseAgreementEntity.java | 302 +- .../dao/types/LicenseAgreementModel.java | 34 +- .../dao/types/LicenseKeyGroupEntity.java | 708 ++- .../vendorlicense/dao/types/LicenseKeyType.java | 11 +- .../sdc/vendorlicense/dao/types/LicenseTerm.java | 12 +- .../sdc/vendorlicense/dao/types/LimitEntity.java | 373 +- .../sdc/vendorlicense/dao/types/LimitType.java | 6 +- .../dao/types/MultiChoiceOrOther.java | 244 +- .../vendorlicense/dao/types/OperationalScope.java | 16 +- .../sdc/vendorlicense/dao/types/ThresholdUnit.java | 10 +- .../dao/types/VendorLicenseModelEntity.java | 233 +- .../dao/types/xml/AggregationFunctionForXml.java | 20 +- .../dao/types/xml/EntitlementMetricForXml.java | 20 +- .../dao/types/xml/EntitlementTimeForXml.java | 20 +- .../dao/types/xml/LicenseKeyTypeForXml.java | 20 +- .../vendorlicense/dao/types/xml/LimitForXml.java | 21 +- .../sdc/vendorlicense/dao/types/xml/LimitXml.java | 39 +- .../dao/types/xml/OperationalScopeForXml.java | 19 +- .../dao/types/xml/ThresholdForXml.java | 34 +- .../errors/InvalidDateErrorBuilder.java | 24 +- .../sdc/vendorlicense/errors/JsonErrorBuilder.java | 46 +- .../errors/LicensingDataInvalidErrorBuilder.java | 39 +- .../SubmitUncompletedLicenseModelErrorBuilder.java | 8 +- .../UncompletedVendorLicenseModelErrorType.java | 11 +- .../errors/VendorLicenseErrorCodes.java | 26 +- .../VendorLicenseModelNotFoundErrorBuilder.java | 36 +- .../vendorlicense/facade/VendorLicenseFacade.java | 62 +- .../facade/VendorLicenseFacadeFactory.java | 14 +- .../sdc/vendorlicense/healing/HealingService.java | 11 +- .../VendorLicenseArtifactsService.java | 11 +- .../types/VersionedVendorLicenseModel.java | 47 +- .../SimpleHealingServiceServiceFactoryImpl.java | 11 +- .../VendorLicenseArtifactServiceFactoryImpl.java | 11 +- .../dao/impl/EntitlementPoolDaoFactoryImpl.java | 14 +- .../dao/impl/FeatureGroupDaoFactoryImpl.java | 14 +- .../dao/impl/LicenseAgreementDaoFactoryImpl.java | 14 +- .../dao/impl/LicenseKeyGroupDaoFactoryImpl.java | 13 +- .../dao/impl/LimitDaoFactoryImpl.java | 11 +- .../dao/impl/VendorLicenseModelDaoFactoryImpl.java | 16 +- .../dao/impl/zusammen/ElementPropertyName.java | 5 +- .../dao/impl/zusammen/ElementType.java | 5 +- .../zusammen/EntitlementPoolZusammenDaoImpl.java | 345 +- .../impl/zusammen/FeatureGroupDaoZusammenImpl.java | 439 +- .../zusammen/LicenseAgreementDaoZusammenImpl.java | 288 +- .../zusammen/LicenseKeyGroupZusammenDaoImpl.java | 315 +- .../dao/impl/zusammen/LimitZusammenDaoImpl.java | 254 +- .../VendorLicenseModelDaoZusammenImpl.java | 206 +- .../dao/impl/zusammen/VlmZusammenUtil.java | 59 +- .../ElementToEntitlementPoolConvertor.java | 135 +- .../convertor/ElementToFeatureGroupConvertor.java | 115 +- .../ElementToLicenseAgreementConvertor.java | 108 +- .../ElementToLicenseKeyGroupConvertor.java | 141 +- .../convertor/ElementToLimitConvertor.java | 56 +- .../convertor/ElementToVLMGeneralConvertor.java | 64 +- .../impl/VendorLicenseFacadeFactoryImpl.java | 16 +- .../facade/impl/VendorLicenseFacadeImpl.java | 507 +- .../healing/impl/SimpleHealingServiceImpl.java | 66 +- .../impl/VendorLicenseArtifactsServiceImpl.java | 249 +- .../impl/types/VendorLicenseArtifact.java | 76 +- .../impl/types/VnfLicenseArtifact.java | 98 +- .../licenseartifacts/impl/types/XmlArtifact.java | 44 +- ...itlementPoolEntityForVendorLicenseArtifact.java | 130 +- .../MixinEntitlementPoolEntityForVnfArtifact.java | 130 +- .../impl/types/mixins/MixinFeatureGroupEntity.java | 55 +- .../impl/types/mixins/MixinFeatureGroupModel.java | 50 +- ...enseKeyGroupEntityForVendorLicenseArtifact.java | 97 +- .../MixinLicenseKeyGroupEntityForVnfArtifact.java | 103 +- .../impl/types/mixins/MixinLimitArtifact.java | 18 +- .../util/VendorLicenseArtifactsServiceUtils.java | 221 +- .../VersionableEntitySortByVlmMajorVersion.java | 17 +- .../VendorSoftwareProductConstants.java | 37 +- .../dao/ComponentArtifactDao.java | 24 +- .../vendorsoftwareproduct/dao/ComponentDao.java | 19 +- .../dao/ComponentDaoFactory.java | 11 +- .../dao/ComponentDependencyModelDao.java | 9 +- .../dao/ComponentDependencyModelDaoFactory.java | 15 +- .../sdc/vendorsoftwareproduct/dao/ComputeDao.java | 18 +- .../dao/ComputeDaoFactory.java | 12 +- .../dao/DeploymentFlavorDao.java | 10 +- .../dao/DeploymentFlavorDaoFactory.java | 7 +- .../sdc/vendorsoftwareproduct/dao/ImageDao.java | 20 +- .../vendorsoftwareproduct/dao/ImageDaoFactory.java | 11 +- .../dao/MonitoringUploadDaoFactory.java | 14 +- .../sdc/vendorsoftwareproduct/dao/NetworkDao.java | 17 +- .../dao/NetworkDaoFactory.java | 11 +- .../sdc/vendorsoftwareproduct/dao/NicDao.java | 20 +- .../vendorsoftwareproduct/dao/NicDaoFactory.java | 11 +- .../dao/OrchestrationTemplateCandidateDao.java | 20 +- .../OrchestrationTemplateCandidateDaoFactory.java | 14 +- .../dao/OrchestrationTemplateDao.java | 13 +- .../dao/OrchestrationTemplateDaoFactory.java | 14 +- .../vendorsoftwareproduct/dao/PackageInfoDao.java | 11 +- .../dao/PackageInfoDaoFactory.java | 11 +- .../sdc/vendorsoftwareproduct/dao/ProcessDao.java | 16 +- .../dao/ProcessDaoFactory.java | 11 +- .../dao/VendorSoftwareProductInfoDao.java | 11 +- .../dao/VendorSoftwareProductInfoDaoFactory.java | 14 +- .../sdc/vendorsoftwareproduct/dao/VspMergeDao.java | 17 +- .../dao/VspMergeDaoFactory.java | 11 +- .../dao/VspQuestionnaireDao.java | 9 +- .../dao/VspQuestionnaireDaoFactory.java | 14 +- .../sdc/vendorsoftwareproduct/dao/type/Action.java | 12 +- .../dao/type/ComponentDependencyModelEntity.java | 84 +- .../dao/type/ComponentEntity.java | 114 +- .../dao/type/ComponentMonitoringUploadEntity.java | 252 +- .../dao/type/CompositionEntity.java | 17 +- .../dao/type/ComputeEntity.java | 105 +- .../dao/type/DeploymentFlavorEntity.java | 18 +- .../dao/type/ImageEntity.java | 117 +- .../dao/type/LicenseType.java | 7 +- .../dao/type/NetworkEntity.java | 108 +- .../vendorsoftwareproduct/dao/type/NicEntity.java | 114 +- .../dao/type/OnboardingMethod.java | 10 +- .../type/OrchestrationTemplateCandidateData.java | 12 +- .../OrchestrationTemplateCandidateDataEntity.java | 197 +- .../dao/type/OrchestrationTemplateEntity.java | 234 +- .../dao/type/PackageInfo.java | 86 +- .../dao/type/ProcessEntity.java | 382 +- .../dao/type/ProcessType.java | 7 +- .../dao/type/TranslatedFileData.java | 2 - .../vendorsoftwareproduct/dao/type/VspDetails.java | 8 +- .../dao/type/VspQuestionnaireEntity.java | 3 - .../errors/utils/ErrorsUtil.java | 8 +- .../factory/CandidateServiceFactory.java | 11 +- .../factory/CompositionDataExtractorFactory.java | 14 +- .../InformationArtifactGeneratorFactory.java | 12 +- .../factory/ManifestCreatorFactory.java | 13 +- .../factory/QuestionnnaireDataServiceFactory.java | 12 +- .../InformationArtifactData.java | 2 - .../InformationArtifactGenerator.java | 10 +- .../questionnaire/QuestionnaireDataService.java | 7 +- .../services/HeatFileAnalyzer.java | 28 +- .../composition/CompositionDataExtractor.java | 5 +- .../filedatastructuremodule/CandidateService.java | 69 +- .../filedatastructuremodule/ManifestCreator.java | 19 +- .../services/impl/HeatFileAnalyzerRowDataImpl.java | 218 +- .../services/impl/etsi/ETSIService.java | 24 +- .../services/schemagenerator/SchemaGenerator.java | 63 +- .../schemagenerator/SchemaGeneratorConfig.java | 203 +- .../services/utils/CandidateEntityBuilder.java | 107 +- .../types/CandidateDataEntityTo.java | 5 +- .../types/candidateheat/AnalyzedZipHeatFiles.java | 2 - .../types/candidateheat/Constants.java | 12 +- .../types/candidateheat/FilesDataStructure.java | 2 - .../types/candidateheat/Module.java | 2 - .../types/composition/Component.java | 2 - .../composition/ComponentComputeAssociation.java | 2 - .../types/composition/ComponentData.java | 2 - .../types/composition/CompositionData.java | 2 - .../types/composition/CompositionDataEntity.java | 6 +- .../types/composition/CompositionEntityId.java | 6 +- .../types/composition/CompositionEntityType.java | 16 +- .../CompositionEntityValidationData.java | 2 - .../types/composition/ComputeData.java | 2 - .../types/composition/DeploymentFlavor.java | 3 - .../composition/ExtractCompositionDataContext.java | 1 - .../types/composition/Image.java | 2 - .../types/composition/ImageData.java | 2 - .../types/composition/ImageFormat.java | 17 +- .../types/composition/Network.java | 2 - .../types/composition/NetworkType.java | 10 +- .../types/composition/Nic.java | 2 - .../component/ComponentQuestionnaire.java | 3 - .../questionnaire/component/compute/Compute.java | 2 - .../questionnaire/component/compute/GuestOS.java | 2 - .../questionnaire/component/compute/NumOfVMs.java | 3 - .../questionnaire/component/compute/VmSizing.java | 2 - .../questionnaire/component/general/General.java | 4 +- .../component/general/Hypervisor.java | 2 - .../questionnaire/component/general/Image.java | 2 - .../questionnaire/component/general/Recovery.java | 2 - .../HighAvailabilityAndLoadBalancing.java | 2 - .../component/image/ImageDetails.java | 2 - .../questionnaire/component/network/Network.java | 2 - .../component/network/NetworkCapacity.java | 2 - .../questionnaire/component/storage/Backup.java | 2 - .../questionnaire/component/storage/LogBackup.java | 2 - .../component/storage/SnapshotBackup.java | 2 - .../questionnaire/component/storage/Storage.java | 2 - .../types/questionnaire/nic/AcceptableJitter.java | 2 - .../types/questionnaire/nic/IpConfiguration.java | 2 - .../types/questionnaire/nic/Network.java | 2 - .../types/questionnaire/nic/NicQuestionnaire.java | 2 - .../types/questionnaire/nic/PacketsAndBytes.java | 2 - .../types/questionnaire/nic/PeakAndAvg.java | 2 - .../types/questionnaire/nic/Protocols.java | 2 - .../types/questionnaire/nic/Sizing.java | 2 - .../types/questionnaire/vsp/VspQuestionnaire.java | 3 - .../questionnaire/vsp/general/Availability.java | 2 - .../types/questionnaire/vsp/general/General.java | 2 - .../questionnaire/vsp/general/RegionsData.java | 2 - .../vsp/general/StorageDataReplication.java | 2 - .../ComponentCompositionSchemaInput.java | 2 - .../ComponentQuestionnaireSchemaInput.java | 2 - .../ComputeCompositionSchemaInput.java | 2 - .../DeploymentFlavorCompositionSchemaInput.java | 3 - .../ImageCompositionSchemaInput.java | 2 - .../NetworkCompositionSchemaInput.java | 2 - .../schemagenerator/NicCompositionSchemaInput.java | 2 - .../schemagenerator/SchemaTemplateContext.java | 10 +- .../types/schemagenerator/SchemaTemplateInput.java | 5 +- ...estrationTemplateFileExtensionErrorBuilder.java | 31 +- ...VendorSoftwareProductCreationFailedBuilder.java | 34 +- .../VendorSoftwareProductNotFoundErrorBuilder.java | 39 +- .../dao/impl/ComponentDaoFactoryImpl.java | 17 +- .../ComponentDependencyModelDaoFactoryImpl.java | 18 +- .../dao/impl/ComputeDaoFactoryImpl.java | 17 +- .../dao/impl/DeploymentFlavorDaoFactoryImpl.java | 10 +- .../dao/impl/ImageDaoFactoryImpl.java | 16 +- .../dao/impl/MonitoringUploadDaoFactoryImpl.java | 17 +- .../dao/impl/NetworkDaoFactoryImpl.java | 17 +- .../dao/impl/NicDaoFactoryImpl.java | 17 +- ...chestrationTemplateCandidateDaoFactoryImpl.java | 22 +- .../impl/OrchestrationTemplateDaoFactoryImpl.java | 21 +- .../dao/impl/PackageInfoDaoFactoryImpl.java | 16 +- .../dao/impl/PackageInfoDaoImpl.java | 89 +- .../dao/impl/ProcessDaoFactoryImpl.java | 17 +- .../VendorSoftwareProductInfoDaoFactoryImpl.java | 19 +- .../dao/impl/VspMergeDaoFactoryImpl.java | 17 +- .../dao/impl/VspMergeDaoImpl.java | 257 +- .../zusammen/ComponentArtifactDaoZusammenImpl.java | 310 +- .../impl/zusammen/ComponentDaoZusammenImpl.java | 364 +- .../ComponentDependencyModelDaoZusammenImpl.java | 221 +- .../ComponentDependencyModelPropertyName.java | 13 +- .../dao/impl/zusammen/ComputeDaoZusammenImpl.java | 341 +- .../zusammen/DeploymentFlavorDaoZusammenImpl.java | 235 +- .../dao/impl/zusammen/ImageDaoZusammenImpl.java | 339 +- .../dao/impl/zusammen/NetworkDaoZusammenImpl.java | 223 +- .../dao/impl/zusammen/NicDaoZusammenImpl.java | 376 +- ...hestrationTemplateCandidateDaoZusammenImpl.java | 377 +- .../OrchestrationTemplateDaoZusammenImpl.java | 309 +- .../dao/impl/zusammen/ProcessDaoZusammenImpl.java | 365 +- .../VendorSoftwareProductInfoDaoZusammenImpl.java | 403 +- .../dao/impl/zusammen/VspZusammenUtil.java | 62 +- .../convertor/ElementToComponentConvertor.java | 50 +- ...ElementToComponentDependencyModelConvertor.java | 59 +- ...lementToComponentMonitoringUploadConvertor.java | 61 +- .../ElementToComponentQuestionnnaireConvertor.java | 20 +- .../ElementToCompositionEntityConvertor.java | 69 +- .../convertor/ElementToComputeConvertor.java | 56 +- .../ElementToComputeQuestionnaireConvertor.java | 23 +- .../ElementToDeploymentFlavorConvertor.java | 56 +- .../convertor/ElementToImageConvertor.java | 56 +- .../ElementToImageQuestionnaireConvertor.java | 23 +- .../ElementToMonitoringUploadMapConvertor.java | 27 +- .../convertor/ElementToNetworkConvertor.java | 54 +- .../zusammen/convertor/ElementToNicConvertor.java | 55 +- .../ElementToNicQuestionnaireConvertor.java | 25 +- ...OrchestrationTemplateCandidateMapConvertor.java | 17 +- .../convertor/ElementToProcessConvertor.java | 68 +- .../ElementToServiceModelMapConvertor.java | 25 +- .../convertor/ElementToVSPGeneralConvertor.java | 104 +- .../ElementToVSPQuestionnaireConvertor.java | 14 +- .../errors/VendorSoftwareProductErrorCodes.java | 167 +- .../InformationArtifactGeneratorFactoryImpl.java | 15 +- .../QuestionnaireDataServiceFactoryImpl.java | 15 +- .../factory/impl/CandidateServiceFactoryImpl.java | 16 +- .../impl/CompositionDataExtractorFactoryImpl.java | 13 +- .../factory/impl/ManifestCreatorFactoryImpl.java | 13 +- .../impl/TxtInformationArtifactConstants.java | 129 +- .../impl/TxtInformationArtifactGeneratorImpl.java | 380 +- .../QuestionnaireDataServiceImpl.java | 102 +- .../services/ManualVspDataCollectionService.java | 611 +- .../composition/CompositionDataExtractorImpl.java | 686 +-- .../services/impl/etsi/ETSIServiceImpl.java | 92 +- .../CandidateServiceImpl.java | 1006 ++-- .../ManifestCreatorNamingConventionImpl.java | 513 +- .../services/utils/CandidateServiceValidator.java | 69 +- .../sdc/versioning/ActionVersioningManager.java | 52 +- .../versioning/ActionVersioningManagerFactory.java | 10 +- .../openecomp/sdc/versioning/AsdcItemManager.java | 1 - .../sdc/versioning/AsdcItemManagerFactory.java | 7 +- .../org/openecomp/sdc/versioning/ItemManager.java | 25 +- .../sdc/versioning/ItemManagerFactory.java | 7 +- .../sdc/versioning/VersioningManager.java | 27 +- .../sdc/versioning/VersioningManagerFactory.java | 11 +- .../VersioningNotificationConstansts.java | 1 + .../openecomp/sdc/versioning/VersioningUtil.java | 271 +- .../org/openecomp/sdc/versioning/dao/ItemDao.java | 14 +- .../sdc/versioning/dao/ItemDaoFactory.java | 8 +- .../openecomp/sdc/versioning/dao/VersionDao.java | 23 +- .../sdc/versioning/dao/VersionDaoFactory.java | 8 +- .../sdc/versioning/dao/VersionInfoDao.java | 5 +- .../sdc/versioning/dao/VersionInfoDaoFactory.java | 12 +- .../sdc/versioning/dao/VersionInfoDeletedDao.java | 5 +- .../dao/VersionInfoDeletedDaoFactory.java | 16 +- .../sdc/versioning/dao/VersionableDao.java | 8 +- .../sdc/versioning/dao/VersionableEntityDao.java | 14 +- .../dao/VersionableEntityDaoFactory.java | 17 +- .../sdc/versioning/dao/types/Revision.java | 11 +- .../versioning/dao/types/SynchronizationState.java | 19 +- .../versioning/dao/types/UserCandidateVersion.java | 13 +- .../sdc/versioning/dao/types/Version.java | 223 +- .../versioning/dao/types/VersionHistoryEntity.java | 33 +- .../dao/types/VersionInfoDeletedEntity.java | 63 +- .../versioning/dao/types/VersionInfoEntity.java | 62 +- .../sdc/versioning/dao/types/VersionState.java | 5 +- .../sdc/versioning/dao/types/VersionStatus.java | 12 +- .../sdc/versioning/dao/types/VersionType.java | 10 +- .../versioning/dao/types/VersionableEntity.java | 27 +- .../versioning/dao/types/VersionableEntityId.java | 10 +- .../CheckinOnEntityLockedByOtherErrorBuilder.java | 36 +- .../CheckinOnUnlockedEntityErrorBuilder.java | 31 +- .../errors/CheckoutOnLockedEntityErrorBuilder.java | 38 +- .../errors/DeleteOnLockedEntityErrorBuilder.java | 35 +- .../EditOnEntityLockedByOtherErrorBuilder.java | 36 +- .../errors/EditOnUnlockedEntityErrorBuilder.java | 39 +- .../errors/EntityAlreadyExistErrorBuilder.java | 31 +- .../errors/EntityAlreadyFinalizedErrorBuilder.java | 33 +- .../errors/EntityNotExistErrorBuilder.java | 31 +- .../RequestedVersionInvalidErrorBuilder.java | 25 +- .../errors/RevisionIdNotFoundErrorBuilder.java | 22 +- .../SubmitLockedEntityNotAllowedErrorBuilder.java | 36 +- ...oCheckoutOnEntityLockedByOtherErrorBuilder.java | 38 +- .../UndoCheckoutOnUnlockedEntityErrorBuilder.java | 31 +- .../VersionableSubEntityNotFoundErrorBuilder.java | 83 +- .../versioning/errors/VersioningErrorCodes.java | 44 +- .../org/openecomp/sdc/versioning/types/Item.java | 61 +- .../openecomp/sdc/versioning/types/ItemStatus.java | 5 +- .../versioning/types/NotificationEventTypes.java | 7 +- .../sdc/versioning/types/UniqueValueMetadata.java | 12 +- .../versioning/types/VersionCreationMethod.java | 8 +- .../sdc/versioning/types/VersionInfo.java | 47 +- .../versioning/types/VersionableEntityAction.java | 10 +- .../types/VersionableEntityMetadata.java | 40 +- .../types/VersionableEntityStoreType.java | 5 +- .../sdc/versioning/VersionCalculator.java | 8 +- .../sdc/versioning/VersionCalculatorFactory.java | 7 +- .../versioning/dao/impl/ItemDaoFactoryImpl.java | 13 +- .../versioning/dao/impl/VersionDaoFactoryImpl.java | 13 +- .../dao/impl/VersionInfoDaoFactoryImpl.java | 12 +- .../versioning/dao/impl/VersionInfoDaoImpl.java | 61 +- .../dao/impl/VersionInfoDeletedDaoFactoryImpl.java | 17 +- .../dao/impl/VersionInfoDeletedDaoImpl.java | 54 +- .../impl/VersionableEntityDaoCassandraImpl.java | 203 +- .../dao/impl/VersionableEntityDaoFactoryImpl.java | 43 +- .../dao/impl/VersionableEntityDaoZusammenImpl.java | 79 +- .../dao/impl/zusammen/ItemZusammenDaoImpl.java | 180 +- .../dao/impl/zusammen/VersionZusammenDaoImpl.java | 312 +- .../convertor/ItemVersionToVersionConvertor.java | 57 +- .../impl/ActionVersioningManagerFactoryImpl.java | 17 +- .../impl/ActionVersioningManagerImpl.java | 1057 ++-- .../impl/AsdcItemManagerFactoryImpl.java | 16 +- .../sdc/versioning/impl/AsdcItemManagerImpl.java | 67 +- .../versioning/impl/ItemManagerFactoryImpl.java | 13 +- .../sdc/versioning/impl/ItemManagerImpl.java | 141 +- .../impl/MajorVersionCalculatorFactoryImpl.java | 12 +- .../impl/MajorVersionCalculatorImpl.java | 69 +- .../impl/VersionCalculatorFactoryImpl.java | 13 +- .../sdc/versioning/impl/VersionCalculatorImpl.java | 97 +- .../impl/VersioningManagerFactoryImpl.java | 14 +- .../sdc/versioning/impl/VersioningManagerImpl.java | 285 +- .../converter/ServiceTemplateReaderService.java | 1 - .../openecomp/core/converter/ToscaConverter.java | 11 +- .../core/converter/datatypes/Constants.java | 6 +- .../core/converter/datatypes/CsarFileTypes.java | 5 +- .../errors/CreateToscaObjectErrorBuilder.java | 22 +- .../SubstitutionMappingsConverterErrorBuilder.java | 23 +- .../converter/factory/ToscaConverterFactory.java | 11 +- .../converter/pnfd/PnfdTransformationEngine.java | 2 - .../QueryOperationNotSupportedException.java | 2 - .../converter/pnfd/model/ConversionDefinition.java | 4 +- .../core/converter/pnfd/model/ConversionQuery.java | 5 +- .../pnfd/model/ConversionStrategyType.java | 21 +- .../pnfd/model/PnfTransformationToken.java | 3 +- .../core/converter/pnfd/model/Transformation.java | 13 +- .../converter/pnfd/model/TransformationBlock.java | 10 +- .../pnfd/model/TransformationDescription.java | 2 - .../pnfd/model/TransformationProperty.java | 2 - .../pnfd/model/TransformationPropertyType.java | 6 +- .../converter/pnfd/parser/PnfdBlockParser.java | 1 - .../strategy/AbstractPnfdConversionStrategy.java | 2 - .../pnfd/strategy/PnfdConversionStrategy.java | 1 - .../pnfd/AbstractPnfdTransformationEngine.java | 16 +- .../pnfd/PnfdNodeTemplateTransformationEngine.java | 65 +- .../pnfd/PnfdNodeTypeTransformationEngine.java | 14 +- .../converter/impl/pnfd/PnfdQueryExecutor.java | 43 +- .../pnfd/PnfdTransformationDescriptorReader.java | 24 +- .../impl/pnfd/factory/PnfdBlockParserFactory.java | 6 +- .../impl/pnfd/parser/AbstractPnfdBlockParser.java | 83 +- .../parser/ConversionDefinitionYamlParser.java | 17 +- .../pnfd/parser/ConversionQueryYamlParser.java | 9 +- .../impl/pnfd/parser/NodeTemplateYamlParser.java | 10 +- .../impl/pnfd/parser/NodeTypeYamlParser.java | 19 +- .../pnfd/parser/ParameterDefinitionYamlParser.java | 9 +- .../parser/PnfdConversionStrategyYamlParser.java | 28 +- .../pnfd/parser/PnfdCustomNodeTypeBlockParser.java | 22 +- .../impl/pnfd/parser/PnfdInputBlockParser.java | 12 +- .../pnfd/parser/PnfdNodeTemplateBlockParser.java | 18 +- .../impl/pnfd/parser/PnfdNodeTypeBlockParser.java | 22 +- .../impl/pnfd/parser/TransformationYamlParser.java | 53 +- .../impl/pnfd/strategy/CopyConversionStrategy.java | 3 +- .../pnfd/strategy/ReplaceConversionStrategy.java | 4 +- .../strategy/ReplaceInListConversionStrategy.java | 16 +- .../core/impl/AbstractToscaConverter.java | 97 +- .../core/impl/AbstractToscaSolConverter.java | 19 +- .../impl/GlobalSubstitutionServiceTemplate.java | 53 +- .../InvalidToscaDefinitionImportException.java | 7 +- .../openecomp/core/impl/ToscaConverterImpl.java | 77 +- .../openecomp/core/impl/ToscaConverterUtil.java | 79 +- .../core/impl/ToscaDefinitionImportHandler.java | 94 +- .../openecomp/core/impl/ToscaSolConverterVnf.java | 2 - .../core/impl/ToscaSolModelDrivenConverterPnf.java | 16 +- .../core/impl/VnfTopologyTemplateConverter.java | 87 +- .../impl/factory/ToscaConverterFactoryImpl.java | 14 +- .../services/ServiceTemplateReaderServiceImpl.java | 9 +- .../sdc/tosca/csar/AbstractOnboardingManifest.java | 38 +- .../openecomp/sdc/tosca/csar/AlgorithmDigest.java | 2 +- .../openecomp/sdc/tosca/csar/CSARConstants.java | 38 +- .../org/openecomp/sdc/tosca/csar/Manifest.java | 20 +- .../sdc/tosca/csar/ManifestTokenType.java | 12 +- .../sdc/tosca/csar/ONAPManifestOnboarding.java | 4 - .../sdc/tosca/csar/OnboardingToscaMetadata.java | 141 +- .../sdc/tosca/csar/SOL004ManifestOnboarding.java | 62 +- .../openecomp/sdc/tosca/csar/SignatureData.java | 2 +- .../openecomp/sdc/tosca/csar/ToscaMetaEntry.java | 3 +- .../openecomp/sdc/tosca/csar/ToscaMetadata.java | 6 +- .../sdc/tosca/csar/ToscaMetadataFileInfo.java | 3 - .../sdc/tosca/datatypes/ToscaArtifactType.java | 9 +- .../sdc/tosca/datatypes/ToscaCapabilityType.java | 10 +- .../sdc/tosca/datatypes/ToscaDataType.java | 84 +- .../sdc/tosca/datatypes/ToscaElementTypes.java | 16 +- .../sdc/tosca/datatypes/ToscaFlatData.java | 3 - .../sdc/tosca/datatypes/ToscaFunctions.java | 13 +- .../sdc/tosca/datatypes/ToscaGroupType.java | 9 +- .../sdc/tosca/datatypes/ToscaInterfaceType.java | 4 +- .../sdc/tosca/datatypes/ToscaNodeType.java | 82 +- .../sdc/tosca/datatypes/ToscaPolicyType.java | 9 +- .../sdc/tosca/datatypes/ToscaRelationshipType.java | 12 +- .../sdc/tosca/datatypes/ToscaServiceModel.java | 28 +- .../datatypes/ToscaTopologyTemplateElements.java | 14 +- .../datatypes/extend/ToscaAnnotationType.java | 13 +- .../datatypes/model/Old1610ServiceTemplate.java | 261 +- .../errors/CreateInterfaceObjectErrorBuilder.java | 29 +- ...CreateInterfaceOperationObjectErrorBuilder.java | 29 +- .../InvalidAddActionNullEntityErrorBuilder.java | 44 +- .../InvalidRequirementAssignmentErrorBuilder.java | 43 +- .../sdc/tosca/errors/InvalidToscaFile.java | 5 +- .../sdc/tosca/errors/InvalidToscaMetaFile.java | 2 - .../ToscaElementTypeNotFoundErrorBuilder.java | 45 +- .../errors/ToscaEntryDefinitionWasNotFound.java | 2 - .../sdc/tosca/errors/ToscaErrorCodes.java | 32 +- .../errors/ToscaFileNotFoundErrorBuilder.java | 43 +- .../ToscaInvalidEntryNotFoundErrorBuilder.java | 51 +- .../ToscaInvalidInterfaceValueErrorBuilder.java | 26 +- ...aInvalidSubstituteNodeTemplateErrorBuilder.java | 50 +- ...bstituteNodeTemplatePropertiesErrorBuilder.java | 52 +- ...lidSubstitutionServiceTemplateErrorBuilder.java | 50 +- ...ngSubstitutionMappingForReqCapErrorBuilder.java | 77 +- .../errors/ToscaNodeTypeNotFoundErrorBuilder.java | 49 +- .../tosca/exceptions/CsarCreationErrorBuilder.java | 26 +- .../CsarMissingEntryPointErrorBuilder.java | 28 +- .../OnboardingManifestInstantiationException.java | 3 +- .../sdc/tosca/services/ConfigConstants.java | 41 +- .../sdc/tosca/services/DataModelUtil.java | 248 +- .../sdc/tosca/services/ToscaAnalyzerService.java | 54 +- .../sdc/tosca/services/ToscaConstants.java | 9 +- .../sdc/tosca/services/ToscaFileOutputService.java | 12 +- .../openecomp/sdc/tosca/services/ToscaUtil.java | 46 +- .../services/impl/ToscaAnalyzerServiceImpl.java | 517 +- .../impl/ToscaFileOutputServiceCsarImpl.java | 213 +- .../core/tools/commands/AddContributorCommand.java | 81 +- .../core/tools/commands/CleanUserDataCommand.java | 31 +- .../org/openecomp/core/tools/commands/Command.java | 10 +- .../openecomp/core/tools/commands/CommandName.java | 15 +- .../core/tools/commands/CommandsHolder.java | 18 +- .../tools/commands/DeletePublicVersionCommand.java | 31 +- .../org/openecomp/core/tools/commands/HealAll.java | 86 +- .../tools/commands/PopulateUserPermissions.java | 8 +- .../core/tools/commands/SetHealingFlag.java | 15 +- .../SetHealingFlagByItemVersionCommand.java | 54 +- .../tools/concurrent/ItemAddContributorsTask.java | 77 +- .../CommandExecutionRuntimeException.java | 6 +- .../tools/exceptions/HealingRuntimeException.java | 6 +- .../core/tools/exportinfo/ExportDataCommand.java | 108 +- .../core/tools/exportinfo/ExportSerializer.java | 24 +- .../core/tools/importinfo/ImportDataCommand.java | 7 +- .../core/tools/importinfo/ImportProperties.java | 8 +- .../core/tools/importinfo/ImportSingleTable.java | 58 +- .../core/tools/itemvalidation/ItemValidation.java | 154 +- .../tools/loaders/VersionInfoCassandraLoader.java | 29 +- .../core/tools/main/ZusammenMainTool.java | 12 +- .../core/tools/model/ColumnDefinition.java | 14 +- .../org/openecomp/core/tools/model/TableData.java | 5 +- .../core/tools/store/ElementCassandraLoader.java | 70 +- .../core/tools/store/ElementNamespaceHandler.java | 15 +- .../openecomp/core/tools/store/HealingHandler.java | 63 +- .../openecomp/core/tools/store/ItemHandler.java | 34 +- .../core/tools/store/NotificationHandler.java | 33 +- .../core/tools/store/PermissionHandler.java | 81 +- .../core/tools/store/VersionCassandraLoader.java | 35 +- .../store/VersionElementsCassandraLoader.java | 37 +- .../tools/store/VersionInfoCassandraLoader.java | 20 +- .../store/zusammen/datatypes/ElementEntity.java | 54 +- .../store/zusammen/datatypes/HealingEntity.java | 30 +- .../zusammen/datatypes/VersionElementsEntity.java | 78 +- .../store/zusammen/datatypes/VersionEntity.java | 19 +- .../org/openecomp/core/tools/util/ToolsUtil.java | 20 +- .../java/org/openecomp/core/tools/util/Utils.java | 51 +- 1526 files changed, 45344 insertions(+), 59074 deletions(-) diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/Actions.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/Actions.java index dfcbee67a1..884077b30f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/Actions.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/Actions.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,34 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.rest; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.action.types.ActionResponseDto; import org.openecomp.sdcrests.action.types.ListResponseWrapper; import org.springframework.validation.annotation.Validated; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - /** * Defines various CRUD API that can be performed on Action. */ @@ -49,152 +55,136 @@ import javax.ws.rs.core.Response; @Validated public interface Actions { - /** - * List All Major, Last Minor and Candidate version if any for Given Action Invariant UuId - * - * @return List of All Major, Last Minor and Candidate version if any Of Action with given - actionInvariantUuId. If actionUuId is provided then only action with given actionInvariantUuId - and actionUuId - */ - @GET - @Path("/{actionInvariantUuId}") - @Operation(description = "List Actions For Given Action Invariant UuId", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) - Response getActionsByActionInvariantUuId( - @PathParam("actionInvariantUuId") String actionInvariantUuId, - @QueryParam("version") String actionUuId, @Context HttpServletRequest servletRequest); - - /** - * Get list of actions based on a filter criteria. If no filter is sent all actions will be - * returned - * - * @return List Of Last Major and Last Minor of All Actions based on filter criteria - */ - @GET - @Operation(description = "List Filtered Actions ", - summary = "Get list of actions based on a filter criteria | If no filter is sent all actions " - + "will be returned", - responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) - Response getFilteredActions(@QueryParam("vendor") String vendor, - @QueryParam("category") String category, - @QueryParam("name") String name, - @QueryParam("modelId") String modelId, - @QueryParam("componentId") String componentId, - @Context HttpServletRequest servletRequest); - - /** - * List OPENECOMP Components supported by Action Library. - * - * @return List of OPENECOMP Components supported by Action Library - */ - @GET - @Path("/components") - @Operation(description = "List OPENECOMP Components supported by Action Library", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) - Response getOpenEcompComponents(@Context HttpServletRequest servletRequest); - - /** - * Create a new Action based on request JSON. - * - * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action - */ - @POST - @Operation(description = "Create a new Action") - Response createAction(String requestJson, @Context HttpServletRequest servletRequest); - - /** - * Update an existing action with parameters provided in requestJson. - * - * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action - */ - @PUT - @Path("/{actionInvariantUuId}") - @Operation(description = "Update an existing action") - Response updateAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, - String requestJson, @Context HttpServletRequest servletRequest); - - /** - * Delete an action. - * - * @param actionInvariantUuId Invariant UuId of the action to be deleted - * @param servletRequest Servlet request object - * @return Empty response object - */ - @DELETE - @Path("/{actionInvariantUuId}") - @Operation(description = "Delete Action") - Response deleteAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @Context HttpServletRequest servletRequest); - - /** - * Performs Checkout/Undo_Checkout/Checkin/Submit Operation on Action. - * - * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action - */ - @POST - @Path("/{actionInvariantUuId}") - @Operation(description = "Actions on a action", - summary = "Performs one of the following actions on a action: |" - + "Checkout: Locks it for edits by other users. Only the locking user sees the edited " - + "version.|" - + "Undo_Checkout: Unlocks it and deletes the edits that were done.|" - + "Checkin: Unlocks it and activates the edited version to all users.| " - + "Submit: Finalize its active version.|") - Response actOnAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, - String requestJson, @Context HttpServletRequest servletRequest); - - /** - * Upload an artifact to an action. - * - * @param actionInvariantUuId Invariant UuId of the action to which the artifact is uploaded - * @param artifactName Name of the artifact - * @param artifactLabel Label of the artifact - * @param artifactCategory Category of the artifact - * @param artifactDescription Description of the artifact - * @param artifactProtection Artifact protection mode - * @param checksum Checksum of the artifact - * @param artifactToUpload Artifact content object - * @param servletRequest Servlet request object - * @return Generated UuId of the uploaded artifact - */ - @POST - @Path("/{actionInvariantUuId}/artifacts") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response uploadArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @Multipart(value = "artifactName", required = false) String artifactName, - @Multipart(value = "artifactLabel", required = false) String artifactLabel, - @Multipart(value = "artifactCategory", required = false) String artifactCategory, - @Multipart(value = "artifactDescription", required = false) String artifactDescription, - @Multipart(value = "artifactProtection", required = false) String artifactProtection, - @HeaderParam("Content-MD5") String checksum, - @Multipart(value = "uploadArtifact", required = false) Attachment artifactToUpload, - @Context HttpServletRequest servletRequest); + /** + * List All Major, Last Minor and Candidate version if any for Given Action Invariant UuId + * + * @return List of All Major, Last Minor and Candidate version if any Of Action with given actionInvariantUuId. If actionUuId is provided then + * only action with given actionInvariantUuId and actionUuId + */ + @GET + @Path("/{actionInvariantUuId}") + @Operation(description = "List Actions For Given Action Invariant UuId", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) + Response getActionsByActionInvariantUuId(@PathParam("actionInvariantUuId") String actionInvariantUuId, @QueryParam("version") String actionUuId, + @Context HttpServletRequest servletRequest); + + /** + * Get list of actions based on a filter criteria. If no filter is sent all actions will be returned + * + * @return List Of Last Major and Last Minor of All Actions based on filter criteria + */ + @GET + @Operation(description = "List Filtered Actions ", summary = "Get list of actions based on a filter criteria | If no filter is sent all actions " + + "will be returned", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) + Response getFilteredActions(@QueryParam("vendor") String vendor, @QueryParam("category") String category, @QueryParam("name") String name, + @QueryParam("modelId") String modelId, @QueryParam("componentId") String componentId, + @Context HttpServletRequest servletRequest); + + /** + * List OPENECOMP Components supported by Action Library. + * + * @return List of OPENECOMP Components supported by Action Library + */ + @GET + @Path("/components") + @Operation(description = "List OPENECOMP Components supported by Action Library", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ListResponseWrapper.class)))) + Response getOpenEcompComponents(@Context HttpServletRequest servletRequest); + + /** + * Create a new Action based on request JSON. + * + * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action + */ + @POST + @Operation(description = "Create a new Action") + Response createAction(String requestJson, @Context HttpServletRequest servletRequest); + + /** + * Update an existing action with parameters provided in requestJson. + * + * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action + */ + @PUT + @Path("/{actionInvariantUuId}") + @Operation(description = "Update an existing action") + Response updateAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, String requestJson, + @Context HttpServletRequest servletRequest); - @GET - @Path("/{actionUuId}/artifacts/{artifactUuId}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Downloads artifact for action") - Response downloadArtifact(@PathParam("actionUuId") String actionUuId, - @PathParam("artifactUuId") String artifactUuId, + /** + * Delete an action. + * + * @param actionInvariantUuId Invariant UuId of the action to be deleted + * @param servletRequest Servlet request object + * @return Empty response object + */ + @DELETE + @Path("/{actionInvariantUuId}") + @Operation(description = "Delete Action") + Response deleteAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, @Context HttpServletRequest servletRequest); + + /** + * Performs Checkout/Undo_Checkout/Checkin/Submit Operation on Action. + * + * @return Metadata object {@link ActionResponseDto ActionResponseDto} object for created Action + */ + @POST + @Path("/{actionInvariantUuId}") + @Operation(description = "Actions on a action", summary = "Performs one of the following actions on a action: |" + + "Checkout: Locks it for edits by other users. Only the locking user sees the edited " + "version.|" + + "Undo_Checkout: Unlocks it and deletes the edits that were done.|" + "Checkin: Unlocks it and activates the edited version to all users.| " + + "Submit: Finalize its active version.|") + Response actOnAction(@PathParam("actionInvariantUuId") String actionInvariantUuId, String requestJson, + @Context HttpServletRequest servletRequest); + + /** + * Upload an artifact to an action. + * + * @param actionInvariantUuId Invariant UuId of the action to which the artifact is uploaded + * @param artifactName Name of the artifact + * @param artifactLabel Label of the artifact + * @param artifactCategory Category of the artifact + * @param artifactDescription Description of the artifact + * @param artifactProtection Artifact protection mode + * @param checksum Checksum of the artifact + * @param artifactToUpload Artifact content object + * @param servletRequest Servlet request object + * @return Generated UuId of the uploaded artifact + */ + @POST + @Path("/{actionInvariantUuId}/artifacts") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response uploadArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, + @Multipart(value = "artifactName", required = false) String artifactName, + @Multipart(value = "artifactLabel", required = false) String artifactLabel, + @Multipart(value = "artifactCategory", required = false) String artifactCategory, + @Multipart(value = "artifactDescription", required = false) String artifactDescription, + @Multipart(value = "artifactProtection", required = false) String artifactProtection, + @HeaderParam("Content-MD5") String checksum, + @Multipart(value = "uploadArtifact", required = false) Attachment artifactToUpload, @Context HttpServletRequest servletRequest); - @DELETE - @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") - @Operation(description = "Delete Artifact") - Response deleteArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @PathParam("artifactUuId") String artifactUuId, - @Context HttpServletRequest servletRequest); + @GET + @Path("/{actionUuId}/artifacts/{artifactUuId}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Downloads artifact for action") + Response downloadArtifact(@PathParam("actionUuId") String actionUuId, @PathParam("artifactUuId") String artifactUuId, + @Context HttpServletRequest servletRequest); - @PUT - @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response updateArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @PathParam("artifactUuId") String artifactUuId, - @Multipart(value = "artifactName", required = false) String artifactName, - @Multipart(value = "artifactLabel", required = false) String artifactLabel, - @Multipart(value = "artifactCategory", required = false) String artifactCategory, - @Multipart(value = "artifactDescription", required = false) String artifactDescription, - @Multipart(value = "artifactProtection", required = false) String artifactProtection, - @HeaderParam("Content-MD5") String checksum, - @Multipart(value = "updateArtifact", required = false) Attachment artifactToUpdate, - @Context HttpServletRequest servletRequest); + @DELETE + @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") + @Operation(description = "Delete Artifact") + Response deleteArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, @PathParam("artifactUuId") String artifactUuId, + @Context HttpServletRequest servletRequest); + @PUT + @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response updateArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, @PathParam("artifactUuId") String artifactUuId, + @Multipart(value = "artifactName", required = false) String artifactName, + @Multipart(value = "artifactLabel", required = false) String artifactLabel, + @Multipart(value = "artifactCategory", required = false) String artifactCategory, + @Multipart(value = "artifactDescription", required = false) String artifactDescription, + @Multipart(value = "artifactProtection", required = false) String artifactProtection, + @HeaderParam("Content-MD5") String checksum, + @Multipart(value = "updateArtifact", required = false) Attachment artifactToUpdate, + @Context HttpServletRequest servletRequest); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/ActionsForSwaggerFileUpload.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/ActionsForSwaggerFileUpload.java index 76ab6f4b88..45d39390a1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/ActionsForSwaggerFileUpload.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/ActionsForSwaggerFileUpload.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.rest; import com.sun.jersey.multipart.FormDataParam; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.apache.cxf.jaxrs.ext.multipart.Multipart; -import org.springframework.validation.annotation.Validated; - +import java.io.InputStream; import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.InputStream; - +import org.apache.cxf.jaxrs.ext.multipart.Multipart; +import org.springframework.validation.annotation.Validated; @Path("/workflow/v1.0/actions") @Produces(MediaType.APPLICATION_JSON) @@ -43,56 +45,43 @@ import java.io.InputStream; @Validated public interface ActionsForSwaggerFileUpload { - /** - * Upload an artifact to an action. - * - * @param actionInvariantUuId Invariant UuId of the action to which the artifact is uploaded - * @param artifactName Name of the artifact - * @param artifactLabel Label of the artifact - * @param artifactCategory Category of the artifact - * @param artifactDescription Description of the artifact - * @param artifactProtection Artifact protection mode - * @param checksum Checksum of the artifact - * @param artifactToUpload Artifact content object - * @param servletRequest Servlet request object - * @return Generated UuId of the uploaded artifact - */ - @POST - @Path("/{actionInvariantUuId}/artifacts") - @Operation(description = "Upload new Artifact") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response uploadArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @Multipart(value = "artifactName", required = false) String artifactName, - @Multipart(value = "artifactLabel", required = false) - String artifactLabel, - @Multipart(value = "artifactCategory", required = false) - String artifactCategory, - @Multipart(value = "artifactDescription", required = false) - String artifactDescription, - @Multipart(value = "artifactProtection", required = false) - String artifactProtection, - @HeaderParam("Content-MD5") String checksum, - @FormDataParam(value = "uploadArtifact") InputStream artifactToUpload, - @Context HttpServletRequest servletRequest); - - - @PUT - @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") - @Operation(description = "Update an existing artifact") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response updateArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, - @PathParam("artifactUuId") String artifactUuId, - @Multipart(value = "artifactName", required = false) String artifactName, - @Multipart(value = "artifactLabel", required = false) - String artifactLabel, - @Multipart(value = "artifactCategory", required = false) - String artifactCategory, - @Multipart(value = "artifactDescription", required = false) - String artifactDescription, - @Multipart(value = "artifactProtection", required = false) - String artifactProtection, - @HeaderParam("Content-MD5") String checksum, - @FormDataParam(value = "updateArtifact") InputStream artifactToUpdate, - @Context HttpServletRequest servletRequest); + /** + * Upload an artifact to an action. + * + * @param actionInvariantUuId Invariant UuId of the action to which the artifact is uploaded + * @param artifactName Name of the artifact + * @param artifactLabel Label of the artifact + * @param artifactCategory Category of the artifact + * @param artifactDescription Description of the artifact + * @param artifactProtection Artifact protection mode + * @param checksum Checksum of the artifact + * @param artifactToUpload Artifact content object + * @param servletRequest Servlet request object + * @return Generated UuId of the uploaded artifact + */ + @POST + @Path("/{actionInvariantUuId}/artifacts") + @Operation(description = "Upload new Artifact") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response uploadArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, + @Multipart(value = "artifactName", required = false) String artifactName, + @Multipart(value = "artifactLabel", required = false) String artifactLabel, + @Multipart(value = "artifactCategory", required = false) String artifactCategory, + @Multipart(value = "artifactDescription", required = false) String artifactDescription, + @Multipart(value = "artifactProtection", required = false) String artifactProtection, + @HeaderParam("Content-MD5") String checksum, @FormDataParam(value = "uploadArtifact") InputStream artifactToUpload, + @Context HttpServletRequest servletRequest); + @PUT + @Path("/{actionInvariantUuId}/artifacts/{artifactUuId}") + @Operation(description = "Update an existing artifact") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response updateArtifact(@PathParam("actionInvariantUuId") String actionInvariantUuId, @PathParam("artifactUuId") String artifactUuId, + @Multipart(value = "artifactName", required = false) String artifactName, + @Multipart(value = "artifactLabel", required = false) String artifactLabel, + @Multipart(value = "artifactCategory", required = false) String artifactCategory, + @Multipart(value = "artifactDescription", required = false) String artifactDescription, + @Multipart(value = "artifactProtection", required = false) String artifactProtection, + @HeaderParam("Content-MD5") String checksum, @FormDataParam(value = "updateArtifact") InputStream artifactToUpdate, + @Context HttpServletRequest servletRequest); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/mapping/MapActionToActionResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/mapping/MapActionToActionResponseDto.java index 9ef1f119f0..c6a97acae0 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/mapping/MapActionToActionResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/mapping/MapActionToActionResponseDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.rest.mapping; import org.openecomp.sdc.action.types.Action; @@ -29,13 +28,13 @@ import org.openecomp.sdcrests.mapping.MappingBase; */ public class MapActionToActionResponseDto extends MappingBase { - @Override - public void doMapping(Action source, ActionResponseDto target) { - target.setActionUuId(source.getActionUuId()); - target.setActionInvariantUuId(source.getActionInvariantUuId()); - target.setVersion(source.getVersion()); - if (source.getStatus() != null) { - target.setStatus(source.getStatus().name()); + @Override + public void doMapping(Action source, ActionResponseDto target) { + target.setActionUuId(source.getActionUuId()); + target.setActionInvariantUuId(source.getActionInvariantUuId()); + target.setVersion(source.getVersion()); + if (source.getStatus() != null) { + target.setStatus(source.getStatus().name()); + } } - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java index 12a3aa564a..7a60ce705e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-services/src/main/java/org/openecomp/sdcrests/action/rest/services/ActionsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdcrests.action.rest.services; import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; @@ -104,7 +103,9 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import javax.inject.Named; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.Response; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.apache.cxf.jaxrs.ext.multipart.Attachment; @@ -134,10 +135,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; -import javax.inject.Named; -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.Response; - /** * Implements various CRUD API that can be performed on Action */ @@ -148,1070 +145,944 @@ import javax.ws.rs.core.Response; @Validated public class ActionsImpl implements Actions { - private static final Logger LOGGER = LoggerFactory.getLogger(ActionsImpl.class); - - private final ActionManager actionManager; - - private String whitespaceCharacters = "\\s" /* dummy empty string for homogeneity */ - + "\\u0009" // CHARACTER TABULATION - + "\\u000A" // LINE FEED (LF) - + "\\u000B" // LINE TABULATION - + "\\u000C" // FORM FEED (FF) - + "\\u000D" // CARRIAGE RETURN (CR) - + "\\u0020" // SPACE - + "\\u0085" // NEXT LINE (NEL) - + "\\u00A0" // NO-BREAK SPACE - + "\\u1680" // OGHAM SPACE MARK - + "\\u180E" // MONGOLIAN VOWEL SEPARATOR - + "\\u2000" // EN QUAD - + "\\u2001" // EM QUAD - + "\\u2002" // EN SPACE - + "\\u2003" // EM SPACE - + "\\u2004" // THREE-PER-EM SPACE - + "\\u2005" // FOUR-PER-EM SPACE - + "\\u2006" // SIX-PER-EM SPACE - + "\\u2007" // FIGURE SPACE - + "\\u2008" // PUNCTUATION SPACE - + "\\u2009" // THIN SPACE - + "\\u200A" // HAIR SPACE - + "\\u2028" // LINE SEPARATOR - + "\\u2029" // PARAGRAPH SEPARATOR - + "\\u202F" // NARROW NO-BREAK SPACE - + "\\u205F" // MEDIUM MATHEMATICAL SPACE - + "\\u3000" // IDEOGRAPHIC SPACE - ; - private String invalidFilenameChars = "#<>$+%!`&*'|{}?\"=/:@\\\\"; - private String whitespaceRegex = ".*[" + whitespaceCharacters + "].*"; - private String invalidFilenameRegex = ".*[" + whitespaceCharacters + invalidFilenameChars + "].*"; - - @Autowired - public ActionsImpl(ActionManager actionManager) { - this.actionManager = actionManager; - } - - /** - * Calculate the checksum for a given input - * - * @param input Byte array for which the checksum has to be calculated - * @return Calculated checksum of the input byte array - */ - private static String calculateCheckSum(byte[] input) { - String checksum = null; - if (input != null) { - checksum = DigestUtils.md5Hex(input); - } - return checksum; - } - - @Override - public Response getActionsByActionInvariantUuId(String invariantID, String actionUUID, - HttpServletRequest servletRequest) { - ListResponseWrapper responseList = new ListResponseWrapper(); - - try { - LOGGER.debug(" entering getActionsByActionInvariantUuId "); - initializeRequestMDC(servletRequest, invariantID, ActionRequest.GET_ACTIONS_INVARIANT_ID); - MDC.put(SERVICE_INSTANCE_ID, invariantID); - - if (StringUtils.isEmpty(servletRequest.getQueryString())) { - responseList = getActionsByInvId(servletRequest, invariantID); - } else { - Response response = getActionByUUID(servletRequest, invariantID, actionUUID); - actionLogPostProcessor(COMPLETE, true); - return response; - } - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(""); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(""); - throw exception; + private static final Logger LOGGER = LoggerFactory.getLogger(ActionsImpl.class); + private final ActionManager actionManager; + private String whitespaceCharacters = "\\s" /* dummy empty string for homogeneity */ + + "\\u0009" // CHARACTER TABULATION + + "\\u000A" // LINE FEED (LF) + + "\\u000B" // LINE TABULATION + + "\\u000C" // FORM FEED (FF) + + "\\u000D" // CARRIAGE RETURN (CR) + + "\\u0020" // SPACE + + "\\u0085" // NEXT LINE (NEL) + + "\\u00A0" // NO-BREAK SPACE + + "\\u1680" // OGHAM SPACE MARK + + "\\u180E" // MONGOLIAN VOWEL SEPARATOR + + "\\u2000" // EN QUAD + + "\\u2001" // EM QUAD + + "\\u2002" // EN SPACE + + "\\u2003" // EM SPACE + + "\\u2004" // THREE-PER-EM SPACE + + "\\u2005" // FOUR-PER-EM SPACE + + "\\u2006" // SIX-PER-EM SPACE + + "\\u2007" // FIGURE SPACE + + "\\u2008" // PUNCTUATION SPACE + + "\\u2009" // THIN SPACE + + "\\u200A" // HAIR SPACE + + "\\u2028" // LINE SEPARATOR + + "\\u2029" // PARAGRAPH SEPARATOR + + "\\u202F" // NARROW NO-BREAK SPACE + + "\\u205F" // MEDIUM MATHEMATICAL SPACE + + "\\u3000" // IDEOGRAPHIC SPACE + ; + private String invalidFilenameChars = "#<>$+%!`&*'|{}?\"=/:@\\\\"; + private String whitespaceRegex = ".*[" + whitespaceCharacters + "].*"; + private String invalidFilenameRegex = ".*[" + whitespaceCharacters + invalidFilenameChars + "].*"; + + @Autowired + public ActionsImpl(ActionManager actionManager) { + this.actionManager = actionManager; } - LOGGER.debug(" exit getActionsByActionInvariantUuId "); - actionLogPostProcessor(COMPLETE, true); - return Response.ok(responseList).build(); - } - - private ListResponseWrapper getActionsByInvId(HttpServletRequest servletRequest, - String invariantID) { - LOGGER.debug(" entering getActionsByInvId with invariantID= " + invariantID); - ListResponseWrapper responseList = new ListResponseWrapper(); - if (StringUtils.isEmpty(servletRequest.getQueryString())) { - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(invariantID); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = actionManager.getActionsByActionInvariantUuId(invariantID); - List versionList = new ArrayList<>(); - for (Action action : actions) { - ActionResponseDto responseDTO = createResponseDTO(action); - versionList.add(responseDTO); + /** + * Calculate the checksum for a given input + * + * @param input Byte array for which the checksum has to be calculated + * @return Calculated checksum of the input byte array + */ + private static String calculateCheckSum(byte[] input) { + String checksum = null; + if (input != null) { + checksum = DigestUtils.md5Hex(input); } - responseList.setVersions(versionList); - responseList.setActionList(null); - - } else { - checkAndThrowError(errorMap); - } - } - LOGGER.debug(" exit getActionsByInvId with invariantID= " + invariantID); - return responseList; - } - - private Response getActionByUUID(HttpServletRequest servletRequest, String invariantID, - String actionUUID) throws ActionException { - int noOfFilterParams = 0; - Response response = null; - LOGGER.debug(" entering getActionByUUID with invariantID= " + invariantID + " and actionUUID= " + - actionUUID); - if (!StringUtils.isEmpty(actionUUID)) { - noOfFilterParams++; - response = getActionsByUniqueID(actionUUID, servletRequest, invariantID); - } - if (noOfFilterParams == 0) { - throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA, - ACTION_REQUEST_FILTER_PARAM_INVALID); - } - - LOGGER.debug(" exit getActionByUUID with invariantID= " + invariantID + " and actionUUID= " + - actionUUID); - return response; - } - - @Override - public Response getOpenEcompComponents(HttpServletRequest servletRequest) { - try { - LOGGER.debug(" entering getEcompComponents "); - initializeRequestMDC(servletRequest, "", ActionRequest.GET_OPEN_ECOMP_COMPONENTS); - //Validate request syntax before passing to the manager - Map errorMap = validateRequestHeaders(servletRequest); - checkAndThrowError(errorMap); - ListResponseWrapper response = new ListResponseWrapper(); - List openEcompComponents = actionManager.getOpenEcompComponents(); - response.setActionList(null); - response.setComponentList(openEcompComponents); - LOGGER.debug(" exit getEcompComponents "); - actionLogPostProcessor(COMPLETE, true); - return Response.ok(response).build(); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(""); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(""); - throw exception; + return checksum; } - } - @Override - public Response getFilteredActions(String vendor, String category, String name, String modelID, - String componentID, HttpServletRequest servletRequest) { - try { - LOGGER.debug(" entering getFilteredActions "); - Response response; - initializeRequestMDC(servletRequest, "", ActionRequest.GET_FILTERED_ACTIONS); - int noOfFilterParams = getNoOfFilterParams(vendor, category, name, modelID, componentID); - if (StringUtils.isEmpty(servletRequest.getQueryString())) { - response = getAllActions(servletRequest); - LOGGER.debug(" exit getFilteredActions "); + @Override + public Response getActionsByActionInvariantUuId(String invariantID, String actionUUID, HttpServletRequest servletRequest) { + ListResponseWrapper responseList = new ListResponseWrapper(); + try { + LOGGER.debug(" entering getActionsByActionInvariantUuId "); + initializeRequestMDC(servletRequest, invariantID, ActionRequest.GET_ACTIONS_INVARIANT_ID); + MDC.put(SERVICE_INSTANCE_ID, invariantID); + if (StringUtils.isEmpty(servletRequest.getQueryString())) { + responseList = getActionsByInvId(servletRequest, invariantID); + } else { + Response response = getActionByUUID(servletRequest, invariantID, actionUUID); + actionLogPostProcessor(COMPLETE, true); + return response; + } + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(""); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(""); + throw exception; + } + LOGGER.debug(" exit getActionsByActionInvariantUuId "); actionLogPostProcessor(COMPLETE, true); - return response; - } - validateNoOfFilterParamsExactly1(noOfFilterParams); - if (!StringUtils.isEmpty(vendor)) { - response = getActionsByVendor(vendor, servletRequest); - } else if (!StringUtils.isEmpty(category)) { - response = getActionsByCategory(category, servletRequest); - } else if (!StringUtils.isEmpty(name)) { - response = getActionsByName(name, servletRequest); - } else if (!StringUtils.isEmpty(modelID)) { - response = getActionsByModel(modelID, servletRequest); - } else if (!StringUtils.isEmpty(componentID)) { - response = getActionsByOpenEcompComponents(componentID, servletRequest); - } else { - throw new ActionException(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_FILTER_PARAM_INVALID); - } - - LOGGER.debug(" exit getFilteredActions "); - actionLogPostProcessor(COMPLETE, true); - return response; - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(""); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(""); - throw exception; + return Response.ok(responseList).build(); } - } - private void validateNoOfFilterParamsExactly1(int noOfFilterParams) { - if (noOfFilterParams > 1) { - throw new ActionException(ACTION_MULT_SEARCH_CRITERIA, - ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED); - } - if (noOfFilterParams == 0) { - throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA, - ACTION_REQUEST_FILTER_PARAM_INVALID); - } - } - - private int getNoOfFilterParams(String vendor, String category, String name, String modelID, String componentID) { - int noOfFilterParams = 0; - if (!StringUtils.isEmpty(vendor)) { - noOfFilterParams++; - } - if (!StringUtils.isEmpty(category)) { - noOfFilterParams++; - } - if (!StringUtils.isEmpty(name)) { - noOfFilterParams++; - } - if (!StringUtils.isEmpty(modelID)) { - noOfFilterParams++; - } - if (!StringUtils.isEmpty(componentID)) { - noOfFilterParams++; - } - return noOfFilterParams; - } - - @Override - public Response createAction(String requestJSON, HttpServletRequest servletRequest) { - try { - initializeRequestMDC(servletRequest, null, ActionRequest.CREATE_ACTION); - LOGGER.debug(" entering API createAction "); - Map errorMap = validateRequestHeaders(servletRequest); - Map requestBodyErrors = - validateRequestBody(REQUEST_TYPE_CREATE_ACTION, requestJSON); - errorMap.putAll(requestBodyErrors); - ActionResponseDto actionResponseDTO = new ActionResponseDto(); - if (errorMap.isEmpty()) { - String user = servletRequest.getRemoteUser(); - Action action = JsonUtil.json2Object(requestJSON, Action.class); - action.setData(requestJSON); - Action responseAction = actionManager.createAction(action, user); - MDC.put(SERVICE_INSTANCE_ID, responseAction.getActionInvariantUuId()); - new MapActionToActionResponseDto().doMapping(responseAction, actionResponseDTO); - } else { - checkAndThrowError(errorMap); - } - actionLogPostProcessor(COMPLETE, true); - LOGGER.debug(" exit API createAction with ActionInvariantUUID= " + MDC.get(SERVICE_INSTANCE_ID)); - return Response.ok(actionResponseDTO).build(); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(""); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; - } - - } - - @Override - public Response updateAction(String invariantUUID, String requestJSON, - HttpServletRequest servletRequest) { - ActionResponseDto actionResponseDTO = null; - try { - initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.UPDATE_ACTION); - Map errorMap = validateRequestHeaders(servletRequest); - Map requestBodyErrors = - validateRequestBody(REQUEST_TYPE_UPDATE_ACTION, requestJSON); - errorMap.putAll(requestBodyErrors); - actionResponseDTO = new ActionResponseDto(); - if (errorMap.isEmpty()) { - String user = servletRequest.getRemoteUser(); - Action action = JsonUtil.json2Object(requestJSON, Action.class); - action.setActionInvariantUuId(invariantUUID); - action.setData(requestJSON); - Action updatedAction = actionManager.updateAction(action, user); - new MapActionToActionResponseDto().doMapping(updatedAction, actionResponseDTO); - } else { - checkAndThrowError(errorMap); - } - actionLogPostProcessor(COMPLETE, true); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(""); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; - } - - return Response.ok(actionResponseDTO).build(); - } - - @Override - public Response deleteAction(String actionInvariantUUID, HttpServletRequest servletRequest) { - try { - initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ACTION); - Map errorMap = validateRequestHeaders(servletRequest); - if (errorMap.isEmpty()) { - String user = servletRequest.getRemoteUser(); - actionManager.deleteAction(actionInvariantUUID, user); - } else { - checkAndThrowError(errorMap); - } - - actionLogPostProcessor(COMPLETE, true); - return Response.ok(new ActionResponseDto()).build(); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; - } - } - - @Override - public Response actOnAction(String invariantUUID, String requestJSON, - HttpServletRequest servletRequest) { - Response response = null; - try { - initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.ACTION_VERSIONING); - LOGGER.debug("entering actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " + - requestJSON); - Map errorMap = validateRequestHeaders(servletRequest); - Map requestBodyErrors = - validateRequestBody(REQUEST_TYPE_VERSION_ACTION, requestJSON); - errorMap.putAll(requestBodyErrors); - - ActionVersionDto versionDTO = JsonUtil.json2Object(requestJSON, ActionVersionDto.class); - checkAndThrowError(errorMap); - - String status = versionDTO.getStatus(); - Action action = new Action(); - String user = servletRequest.getRemoteUser(); - switch (status) { - case "Checkout": - action = actionManager.checkout(invariantUUID, user); - break; - case "Undo_Checkout": - actionManager.undoCheckout(invariantUUID, user); - StringWrapperResponse responseText = new StringWrapperResponse(); - responseText.setValue(ActionConstants.UNDO_CHECKOUT_RESPONSE_TEXT); - response = Response - .status(Response.Status.OK) - .entity(responseText) - .build(); - return response; - case "Checkin": - action = actionManager.checkin(invariantUUID, user); - break; - case "Submit": - action = actionManager.submit(invariantUUID, user); - break; - default: - throw new ActionException(ACTION_INVALID_PARAM_CODE, - String.format(ACTION_UNSUPPORTED_OPERATION, status)); - } - - ActionResponseDto actionResponseDTO = new ActionResponseDto(); - new MapActionToActionResponseDto().doMapping(action, actionResponseDTO); - response = Response.ok(actionResponseDTO).build(); - actionLogPostProcessor(COMPLETE, true); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; - } finally { - LOGGER.debug("exit actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " + - requestJSON); - } - return response; - } - - @Override - public Response uploadArtifact(String actionInvariantUUID, - String artifactName, - String artifactLabel, - String artifactCategory, - String artifactDescription, - String artifactProtection, - String checksum, - Attachment artifactToUpload, - HttpServletRequest servletRequest) { - Response response = null; - try { - initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPLOAD_ARTIFACT); - LOGGER.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + - "artifactName= " + artifactName); - response = - uploadArtifactInternal(actionInvariantUUID, artifactName, artifactLabel, artifactCategory, - artifactDescription, artifactProtection, checksum, artifactToUpload, servletRequest); - actionLogPostProcessor(COMPLETE, true); - LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + - "artifactName= " + artifactName); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; + private ListResponseWrapper getActionsByInvId(HttpServletRequest servletRequest, String invariantID) { + LOGGER.debug(" entering getActionsByInvId with invariantID= " + invariantID); + ListResponseWrapper responseList = new ListResponseWrapper(); + if (StringUtils.isEmpty(servletRequest.getQueryString())) { + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(invariantID); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getActionsByActionInvariantUuId(invariantID); + List versionList = new ArrayList<>(); + for (Action action : actions) { + ActionResponseDto responseDTO = createResponseDTO(action); + versionList.add(responseDTO); + } + responseList.setVersions(versionList); + responseList.setActionList(null); + } else { + checkAndThrowError(errorMap); + } + } + LOGGER.debug(" exit getActionsByInvId with invariantID= " + invariantID); + return responseList; } - LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + - "artifactName= " + artifactName); - return response; - } - - private Response uploadArtifactInternal(String actionInvariantUUID, String artifactName, - String artifactLabel, String artifactCategory, - String artifactDescription, String artifactProtection, - String checksum, Attachment artifactToUpload, - HttpServletRequest servletRequest) { - byte[] payload = null; - Map errorMap = validateRequestHeaders(servletRequest); - //Artifact name empty validation - if (StringUtils.isEmpty(artifactName)) { - errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, - ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME); - } else { - //Artifact name syntax check for whitespaces and invalid characters - if (artifactName.matches(invalidFilenameRegex)) { - errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME); - } + private Response getActionByUUID(HttpServletRequest servletRequest, String invariantID, String actionUUID) throws ActionException { + int noOfFilterParams = 0; + Response response = null; + LOGGER.debug(" entering getActionByUUID with invariantID= " + invariantID + " and actionUUID= " + actionUUID); + if (!StringUtils.isEmpty(actionUUID)) { + noOfFilterParams++; + response = getActionsByUniqueID(actionUUID, servletRequest, invariantID); + } + if (noOfFilterParams == 0) { + throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA, ACTION_REQUEST_FILTER_PARAM_INVALID); + } + LOGGER.debug(" exit getActionByUUID with invariantID= " + invariantID + " and actionUUID= " + actionUUID); + return response; } - //Content-Type Header Validation - String contentType = servletRequest.getContentType(); - if (StringUtils.isEmpty(contentType)) { - errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID); + @Override + public Response getOpenEcompComponents(HttpServletRequest servletRequest) { + try { + LOGGER.debug(" entering getEcompComponents "); + initializeRequestMDC(servletRequest, "", ActionRequest.GET_OPEN_ECOMP_COMPONENTS); + //Validate request syntax before passing to the manager + Map errorMap = validateRequestHeaders(servletRequest); + checkAndThrowError(errorMap); + ListResponseWrapper response = new ListResponseWrapper(); + List openEcompComponents = actionManager.getOpenEcompComponents(); + response.setActionList(null); + response.setComponentList(openEcompComponents); + LOGGER.debug(" exit getEcompComponents "); + actionLogPostProcessor(COMPLETE, true); + return Response.ok(response).build(); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(""); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(""); + throw exception; + } } - if (artifactToUpload == null) { - throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE, - ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE); + @Override + public Response getFilteredActions(String vendor, String category, String name, String modelID, String componentID, + HttpServletRequest servletRequest) { + try { + LOGGER.debug(" entering getFilteredActions "); + Response response; + initializeRequestMDC(servletRequest, "", ActionRequest.GET_FILTERED_ACTIONS); + int noOfFilterParams = getNoOfFilterParams(vendor, category, name, modelID, componentID); + if (StringUtils.isEmpty(servletRequest.getQueryString())) { + response = getAllActions(servletRequest); + LOGGER.debug(" exit getFilteredActions "); + actionLogPostProcessor(COMPLETE, true); + return response; + } + validateNoOfFilterParamsExactly1(noOfFilterParams); + if (!StringUtils.isEmpty(vendor)) { + response = getActionsByVendor(vendor, servletRequest); + } else if (!StringUtils.isEmpty(category)) { + response = getActionsByCategory(category, servletRequest); + } else if (!StringUtils.isEmpty(name)) { + response = getActionsByName(name, servletRequest); + } else if (!StringUtils.isEmpty(modelID)) { + response = getActionsByModel(modelID, servletRequest); + } else if (!StringUtils.isEmpty(componentID)) { + response = getActionsByOpenEcompComponents(componentID, servletRequest); + } else { + throw new ActionException(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_FILTER_PARAM_INVALID); + } + LOGGER.debug(" exit getFilteredActions "); + actionLogPostProcessor(COMPLETE, true); + return response; + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(""); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(""); + throw exception; + } } - try (InputStream artifactInputStream = artifactToUpload.getDataHandler().getInputStream()) { - payload = FileUtils.toByteArray(artifactInputStream); - } catch (IOException exception) { - LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); - throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); + private void validateNoOfFilterParamsExactly1(int noOfFilterParams) { + if (noOfFilterParams > 1) { + throw new ActionException(ACTION_MULT_SEARCH_CRITERIA, ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED); + } + if (noOfFilterParams == 0) { + throw new ActionException(ACTION_INVALID_SEARCH_CRITERIA, ACTION_REQUEST_FILTER_PARAM_INVALID); + } } - //Validate Artifact size - if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { - throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR); + private int getNoOfFilterParams(String vendor, String category, String name, String modelID, String componentID) { + int noOfFilterParams = 0; + if (!StringUtils.isEmpty(vendor)) { + noOfFilterParams++; + } + if (!StringUtils.isEmpty(category)) { + noOfFilterParams++; + } + if (!StringUtils.isEmpty(name)) { + noOfFilterParams++; + } + if (!StringUtils.isEmpty(modelID)) { + noOfFilterParams++; + } + if (!StringUtils.isEmpty(componentID)) { + noOfFilterParams++; + } + return noOfFilterParams; } - //Validate Checksum - if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) { - errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR); + @Override + public Response createAction(String requestJSON, HttpServletRequest servletRequest) { + try { + initializeRequestMDC(servletRequest, null, ActionRequest.CREATE_ACTION); + LOGGER.debug(" entering API createAction "); + Map errorMap = validateRequestHeaders(servletRequest); + Map requestBodyErrors = validateRequestBody(REQUEST_TYPE_CREATE_ACTION, requestJSON); + errorMap.putAll(requestBodyErrors); + ActionResponseDto actionResponseDTO = new ActionResponseDto(); + if (errorMap.isEmpty()) { + String user = servletRequest.getRemoteUser(); + Action action = JsonUtil.json2Object(requestJSON, Action.class); + action.setData(requestJSON); + Action responseAction = actionManager.createAction(action, user); + MDC.put(SERVICE_INSTANCE_ID, responseAction.getActionInvariantUuId()); + new MapActionToActionResponseDto().doMapping(responseAction, actionResponseDTO); + } else { + checkAndThrowError(errorMap); + } + actionLogPostProcessor(COMPLETE, true); + LOGGER.debug(" exit API createAction with ActionInvariantUUID= " + MDC.get(SERVICE_INSTANCE_ID)); + return Response.ok(actionResponseDTO).build(); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(""); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } } - //Validate artifact protection values - if (StringUtils.isEmpty(artifactProtection)) { - artifactProtection = ActionArtifactProtection.readWrite.name(); + @Override + public Response updateAction(String invariantUUID, String requestJSON, HttpServletRequest servletRequest) { + ActionResponseDto actionResponseDTO = null; + try { + initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.UPDATE_ACTION); + Map errorMap = validateRequestHeaders(servletRequest); + Map requestBodyErrors = validateRequestBody(REQUEST_TYPE_UPDATE_ACTION, requestJSON); + errorMap.putAll(requestBodyErrors); + actionResponseDTO = new ActionResponseDto(); + if (errorMap.isEmpty()) { + String user = servletRequest.getRemoteUser(); + Action action = JsonUtil.json2Object(requestJSON, Action.class); + action.setActionInvariantUuId(invariantUUID); + action.setData(requestJSON); + Action updatedAction = actionManager.updateAction(action, user); + new MapActionToActionResponseDto().doMapping(updatedAction, actionResponseDTO); + } else { + checkAndThrowError(errorMap); + } + actionLogPostProcessor(COMPLETE, true); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(""); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } + return Response.ok(actionResponseDTO).build(); } - if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) && - !artifactProtection.equals(ActionArtifactProtection.readWrite.name())) { - errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, - ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE); + @Override + public Response deleteAction(String actionInvariantUUID, HttpServletRequest servletRequest) { + try { + initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ACTION); + Map errorMap = validateRequestHeaders(servletRequest); + if (errorMap.isEmpty()) { + String user = servletRequest.getRemoteUser(); + actionManager.deleteAction(actionInvariantUUID, user); + } else { + checkAndThrowError(errorMap); + } + actionLogPostProcessor(COMPLETE, true); + return Response.ok(new ActionResponseDto()).build(); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } } - ActionArtifact uploadedArtifact = new ActionArtifact(); - if (errorMap.isEmpty()) { - String user = servletRequest.getRemoteUser(); - ActionArtifact upload = new ActionArtifact(); - upload.setArtifactName(artifactName); - upload.setArtifactLabel(artifactLabel); - upload.setArtifactDescription(artifactDescription); - upload.setArtifact(payload); - upload.setArtifactCategory(artifactCategory); - upload.setArtifactProtection(artifactProtection); - uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUUID, user); - } else { - checkAndThrowError(errorMap); + @Override + public Response actOnAction(String invariantUUID, String requestJSON, HttpServletRequest servletRequest) { + Response response = null; + try { + initializeRequestMDC(servletRequest, invariantUUID, ActionRequest.ACTION_VERSIONING); + LOGGER.debug("entering actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " + requestJSON); + Map errorMap = validateRequestHeaders(servletRequest); + Map requestBodyErrors = validateRequestBody(REQUEST_TYPE_VERSION_ACTION, requestJSON); + errorMap.putAll(requestBodyErrors); + ActionVersionDto versionDTO = JsonUtil.json2Object(requestJSON, ActionVersionDto.class); + checkAndThrowError(errorMap); + String status = versionDTO.getStatus(); + Action action = new Action(); + String user = servletRequest.getRemoteUser(); + switch (status) { + case "Checkout": + action = actionManager.checkout(invariantUUID, user); + break; + case "Undo_Checkout": + actionManager.undoCheckout(invariantUUID, user); + StringWrapperResponse responseText = new StringWrapperResponse(); + responseText.setValue(ActionConstants.UNDO_CHECKOUT_RESPONSE_TEXT); + response = Response.status(Response.Status.OK).entity(responseText).build(); + return response; + case "Checkin": + action = actionManager.checkin(invariantUUID, user); + break; + case "Submit": + action = actionManager.submit(invariantUUID, user); + break; + default: + throw new ActionException(ACTION_INVALID_PARAM_CODE, String.format(ACTION_UNSUPPORTED_OPERATION, status)); + } + ActionResponseDto actionResponseDTO = new ActionResponseDto(); + new MapActionToActionResponseDto().doMapping(action, actionResponseDTO); + response = Response.ok(actionResponseDTO).build(); + actionLogPostProcessor(COMPLETE, true); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } finally { + LOGGER.debug("exit actOnAction with invariantUUID= " + invariantUUID + " and requestJSON= " + requestJSON); + } + return response; } - return Response.ok(uploadedArtifact).build(); - } - @Override - public Response downloadArtifact(String actionUUID, String artifactUUID, + @Override + public Response uploadArtifact(String actionInvariantUUID, String artifactName, String artifactLabel, String artifactCategory, + String artifactDescription, String artifactProtection, String checksum, Attachment artifactToUpload, HttpServletRequest servletRequest) { - Response response = null; - try { - initializeRequestMDC(servletRequest, "", ActionRequest.DOWNLOAD_ARTIFACT); - LOGGER.debug( - " entering downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " + - artifactUUID); - response = downloadArtifactInternal(actionUUID, artifactUUID, servletRequest); - actionLogPostProcessor(COMPLETE, true); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; + Response response = null; + try { + initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPLOAD_ARTIFACT); + LOGGER.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + "artifactName= " + artifactName); + response = uploadArtifactInternal(actionInvariantUUID, artifactName, artifactLabel, artifactCategory, artifactDescription, + artifactProtection, checksum, artifactToUpload, servletRequest); + actionLogPostProcessor(COMPLETE, true); + LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + "artifactName= " + artifactName); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } + LOGGER.debug("exiting uploadArtifact with actionInvariantUuId= " + actionInvariantUUID + "artifactName= " + artifactName); + return response; } - LOGGER.debug(" exit downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " + - artifactUUID); - return response; - } - - private Response downloadArtifactInternal(String actionUUID, String artifactUUID, + private Response uploadArtifactInternal(String actionInvariantUUID, String artifactName, String artifactLabel, String artifactCategory, + String artifactDescription, String artifactProtection, String checksum, Attachment artifactToUpload, HttpServletRequest servletRequest) { - Response response; - ActionArtifact actionartifact = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(actionUUID); - errorMap.putAll(queryParamErrors); - queryParamErrors = validateQueryParam(artifactUUID); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - actionartifact = actionManager.downloadArtifact(actionUUID, artifactUUID); - } else { - checkAndThrowError(errorMap); - } - response = createArtifactDownloadResponse(actionartifact); - return response; - } - - @Override - public Response deleteArtifact(String actionInvariantUUID, String artifactUUID, - HttpServletRequest servletRequest) { - Response response = null; - try { - initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ARTIFACT); - LOGGER.debug(" entering deleteArtifact with actionInvariantUuId= " + actionInvariantUUID + - " and artifactUUID= " + artifactUUID); - response = deleteArtifactInternal(actionInvariantUUID, artifactUUID, servletRequest); - LOGGER.debug(" exit deleteArtifact with actionInvariantUuId= " + actionInvariantUUID + - " and artifactUUID= " + artifactUUID); - actionLogPostProcessor(COMPLETE, true); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; - } - - return response; - } - - private Response deleteArtifactInternal(String actionInvariantUUID, String artifactUUID, - HttpServletRequest servletRequest) { - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(actionInvariantUUID); - errorMap.putAll(queryParamErrors); - queryParamErrors = validateQueryParam(artifactUUID); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - actionManager - .deleteArtifact(actionInvariantUUID, artifactUUID, servletRequest.getRemoteUser()); - } else { - checkAndThrowError(errorMap); + byte[] payload = null; + Map errorMap = validateRequestHeaders(servletRequest); + //Artifact name empty validation + if (StringUtils.isEmpty(artifactName)) { + errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_NAME); + } else { + //Artifact name syntax check for whitespaces and invalid characters + if (artifactName.matches(invalidFilenameRegex)) { + errorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_ARTIFACT_INVALID_NAME); + } + } + //Content-Type Header Validation + String contentType = servletRequest.getContentType(); + if (StringUtils.isEmpty(contentType)) { + errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID); + } + if (artifactToUpload == null) { + throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + ARTIFACT_FILE); + } + try (InputStream artifactInputStream = artifactToUpload.getDataHandler().getInputStream()) { + payload = FileUtils.toByteArray(artifactInputStream); + } catch (IOException exception) { + LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); + throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); + } + //Validate Artifact size + if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { + throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR); + } + //Validate Checksum + if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) { + errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR); + } + //Validate artifact protection values + if (StringUtils.isEmpty(artifactProtection)) { + artifactProtection = ActionArtifactProtection.readWrite.name(); + } + if (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) && !artifactProtection + .equals(ActionArtifactProtection.readWrite.name())) { + errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE); + } + ActionArtifact uploadedArtifact = new ActionArtifact(); + if (errorMap.isEmpty()) { + String user = servletRequest.getRemoteUser(); + ActionArtifact upload = new ActionArtifact(); + upload.setArtifactName(artifactName); + upload.setArtifactLabel(artifactLabel); + upload.setArtifactDescription(artifactDescription); + upload.setArtifact(payload); + upload.setArtifactCategory(artifactCategory); + upload.setArtifactProtection(artifactProtection); + uploadedArtifact = actionManager.uploadArtifact(upload, actionInvariantUUID, user); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(uploadedArtifact).build(); } - return Response.ok().build(); - } - @Override - public Response updateArtifact(String actionInvariantUUID, String artifactUUID, - String artifactName, String artifactLabel, String artifactCategory, - String artifactDescription, String artifactProtection, - String checksum, Attachment artifactToUpdate, - HttpServletRequest servletRequest) { - Response response = null; - LOGGER.debug(" entering updateArtifact with actionInvariantUuId= " + actionInvariantUUID + - " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName + - " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory + - " and artifactDescription= " + artifactDescription + " and artifactProtection= " + - artifactProtection + " and checksum= " + checksum); - try { - initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPDATE_ARTIFACT); - response = - updateArtifactInternal(actionInvariantUUID, artifactUUID, artifactName, artifactLabel, - artifactCategory, artifactDescription, artifactProtection, checksum, artifactToUpdate, - servletRequest); - actionLogPostProcessor(COMPLETE, true); - } catch (ActionException exception) { - actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); - LOGGER.error(MDC.get(ERROR_DESCRIPTION)); - throw exception; - } catch (Exception exception) { - actionLogPostProcessor(ERROR, true); - actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, - ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - LOGGER.error(exception.getMessage()); - throw exception; + @Override + public Response downloadArtifact(String actionUUID, String artifactUUID, HttpServletRequest servletRequest) { + Response response = null; + try { + initializeRequestMDC(servletRequest, "", ActionRequest.DOWNLOAD_ARTIFACT); + LOGGER.debug(" entering downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " + artifactUUID); + response = downloadArtifactInternal(actionUUID, artifactUUID, servletRequest); + actionLogPostProcessor(COMPLETE, true); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } + LOGGER.debug(" exit downloadArtifact with actionUUID= " + actionUUID + " and artifactUUID= " + artifactUUID); + return response; } - LOGGER.debug(" exit updateArtifact with actionInvariantUuId= " + actionInvariantUUID + - " and artifactUUID= " + artifactUUID + " and artifactName= " + artifactName + - " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory + - " and artifactDescription= " + artifactDescription + " and artifactProtection= " + - artifactProtection + " and checksum= " + checksum); - return response; - } - - private Response updateArtifactInternal(String actionInvariantUUID, String artifactUUID, - String artifactName, String artifactLabel, - String artifactCategory, String artifactDescription, - String artifactProtection, String checksum, - Attachment artifactToUpdate, - HttpServletRequest servletRequest) { - byte[] payload = null; - Map errorMap = validateRequestHeaders(servletRequest); - - //Content-Type Header Validation - String contentType = servletRequest.getContentType(); - if (StringUtils.isEmpty(contentType)) { - errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID); + private Response downloadArtifactInternal(String actionUUID, String artifactUUID, HttpServletRequest servletRequest) { + Response response; + ActionArtifact actionartifact = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(actionUUID); + errorMap.putAll(queryParamErrors); + queryParamErrors = validateQueryParam(artifactUUID); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + actionartifact = actionManager.downloadArtifact(actionUUID, artifactUUID); + } else { + checkAndThrowError(errorMap); + } + response = createArtifactDownloadResponse(actionartifact); + return response; } - if (artifactToUpdate != null) { - - try (InputStream artifactInputStream = artifactToUpdate.getDataHandler().getInputStream()) { - payload = FileUtils.toByteArray(artifactInputStream); - } catch (IOException exception) { - LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); - throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); - } - - //Validate Artifact size - if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { - throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, - ACTION_ARTIFACT_TOO_BIG_ERROR); - } - - //Validate Checksum - if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) { - errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR); - } + @Override + public Response deleteArtifact(String actionInvariantUUID, String artifactUUID, HttpServletRequest servletRequest) { + Response response = null; + try { + initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.DELETE_ARTIFACT); + LOGGER.debug(" entering deleteArtifact with actionInvariantUuId= " + actionInvariantUUID + " and artifactUUID= " + artifactUUID); + response = deleteArtifactInternal(actionInvariantUUID, artifactUUID, servletRequest); + LOGGER.debug(" exit deleteArtifact with actionInvariantUuId= " + actionInvariantUUID + " and artifactUUID= " + artifactUUID); + actionLogPostProcessor(COMPLETE, true); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } + return response; } - if (artifactProtection != null && (artifactProtection.isEmpty() || - (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) && - !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) { - errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, - ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE); + private Response deleteArtifactInternal(String actionInvariantUUID, String artifactUUID, HttpServletRequest servletRequest) { + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(actionInvariantUUID); + errorMap.putAll(queryParamErrors); + queryParamErrors = validateQueryParam(artifactUUID); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + actionManager.deleteArtifact(actionInvariantUUID, artifactUUID, servletRequest.getRemoteUser()); + } else { + checkAndThrowError(errorMap); + } + return Response.ok().build(); } - ActionArtifact updateArtifact = new ActionArtifact(); - if (errorMap.isEmpty()) { - String user = servletRequest.getRemoteUser(); - ActionArtifact update = new ActionArtifact(); - update.setArtifactUuId(artifactUUID); - update.setArtifactName(artifactName); - update.setArtifactLabel(artifactLabel); - update.setArtifactDescription(artifactDescription); - update.setArtifact(payload); - update.setArtifactCategory(artifactCategory); - update.setArtifactProtection(artifactProtection); - actionManager.updateArtifact(update, actionInvariantUUID, user); - } else { - checkAndThrowError(errorMap); + @Override + public Response updateArtifact(String actionInvariantUUID, String artifactUUID, String artifactName, String artifactLabel, + String artifactCategory, String artifactDescription, String artifactProtection, String checksum, + Attachment artifactToUpdate, HttpServletRequest servletRequest) { + Response response = null; + LOGGER.debug( + " entering updateArtifact with actionInvariantUuId= " + actionInvariantUUID + " and artifactUUID= " + artifactUUID + " and artifactName= " + + artifactName + " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory + " and artifactDescription= " + + artifactDescription + " and artifactProtection= " + artifactProtection + " and checksum= " + checksum); + try { + initializeRequestMDC(servletRequest, actionInvariantUUID, ActionRequest.UPDATE_ARTIFACT); + response = updateArtifactInternal(actionInvariantUUID, artifactUUID, artifactName, artifactLabel, artifactCategory, artifactDescription, + artifactProtection, checksum, artifactToUpdate, servletRequest); + actionLogPostProcessor(COMPLETE, true); + } catch (ActionException exception) { + actionLogPostProcessor(ERROR, exception.getErrorCode(), exception.getDescription(), true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, exception.getErrorCode(), exception.getDescription()); + LOGGER.error(MDC.get(ERROR_DESCRIPTION)); + throw exception; + } catch (Exception exception) { + actionLogPostProcessor(ERROR, true); + actionErrorLogProcessor(CategoryLogLevel.ERROR, ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + LOGGER.error(exception.getMessage()); + throw exception; + } + LOGGER.debug( + " exit updateArtifact with actionInvariantUuId= " + actionInvariantUUID + " and artifactUUID= " + artifactUUID + " and artifactName= " + + artifactName + " and artifactLabel= " + artifactLabel + " and artifactCategory= " + artifactCategory + " and artifactDescription= " + + artifactDescription + " and artifactProtection= " + artifactProtection + " and checksum= " + checksum); + return response; } - return Response.ok().build(); - } - /** - * Get List of all actions - */ - private Response getAllActions(HttpServletRequest servletRequest) { - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - if (errorMap.isEmpty()) { - List actions = actionManager.getFilteredActions(FILTER_TYPE_NONE, null); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + private Response updateArtifactInternal(String actionInvariantUUID, String artifactUUID, String artifactName, String artifactLabel, + String artifactCategory, String artifactDescription, String artifactProtection, String checksum, + Attachment artifactToUpdate, HttpServletRequest servletRequest) { + byte[] payload = null; + Map errorMap = validateRequestHeaders(servletRequest); + //Content-Type Header Validation + String contentType = servletRequest.getContentType(); + if (StringUtils.isEmpty(contentType)) { + errorMap.put(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_CONTENT_TYPE_INVALID); + } + if (artifactToUpdate != null) { + try (InputStream artifactInputStream = artifactToUpdate.getDataHandler().getInputStream()) { + payload = FileUtils.toByteArray(artifactInputStream); + } catch (IOException exception) { + LOGGER.error(ACTION_ARTIFACT_READ_FILE_ERROR, exception); + throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ARTIFACT_READ_FILE_ERROR); + } + //Validate Artifact size + if (payload != null && payload.length > MAX_ACTION_ARTIFACT_SIZE) { + throw new ActionException(ACTION_ARTIFACT_TOO_BIG_ERROR_CODE, ACTION_ARTIFACT_TOO_BIG_ERROR); + } + //Validate Checksum + if (StringUtils.isEmpty(checksum) || !checksum.equalsIgnoreCase(calculateCheckSum(payload))) { + errorMap.put(ACTION_ARTIFACT_CHECKSUM_ERROR_CODE, ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR); + } + } + if (artifactProtection != null && (artifactProtection.isEmpty() || (!artifactProtection.equals(ActionArtifactProtection.readOnly.name()) + && !artifactProtection.equals(ActionArtifactProtection.readWrite.name())))) { + errorMap.put(ACTION_ARTIFACT_INVALID_PROTECTION_CODE, ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE); + } + ActionArtifact updateArtifact = new ActionArtifact(); + if (errorMap.isEmpty()) { + String user = servletRequest.getRemoteUser(); + ActionArtifact update = new ActionArtifact(); + update.setArtifactUuId(artifactUUID); + update.setArtifactName(artifactName); + update.setArtifactLabel(artifactLabel); + update.setArtifactDescription(artifactDescription); + update.setArtifact(payload); + update.setArtifactCategory(artifactCategory); + update.setArtifactProtection(artifactProtection); + actionManager.updateArtifact(update, actionInvariantUUID, user); + } else { + checkAndThrowError(errorMap); + } + return Response.ok().build(); } - return Response.ok(responseList).build(); - } - - /** - * Get Actions by OPENECOMP component ID - */ - private Response getActionsByOpenEcompComponents(String componentID, - HttpServletRequest servletRequest) { - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(componentID); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = - actionManager.getFilteredActions(FILTER_TYPE_OPEN_ECOMP_COMPONENT, componentID); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + /** + * Get List of all actions + */ + private Response getAllActions(HttpServletRequest servletRequest) { + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_NONE, null); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - return Response.ok(responseList).build(); - } - /** - * Get Actions by Model ID - */ - private Response getActionsByModel(String modelId, HttpServletRequest servletRequest) { - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(modelId); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = actionManager.getFilteredActions(FILTER_TYPE_MODEL, modelId); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + /** + * Get Actions by OPENECOMP component ID + */ + private Response getActionsByOpenEcompComponents(String componentID, HttpServletRequest servletRequest) { + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(componentID); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_OPEN_ECOMP_COMPONENT, componentID); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - return Response.ok(responseList).build(); - } - /** - * Get all actions with given action name - */ - private Response getActionsByName(String name, HttpServletRequest servletRequest) { - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(name); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = actionManager.getFilteredActions(FILTER_TYPE_NAME, name); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + /** + * Get Actions by Model ID + */ + private Response getActionsByModel(String modelId, HttpServletRequest servletRequest) { + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(modelId); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_MODEL, modelId); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - return Response.ok(responseList).build(); - } - /** - * Get an action with given ActionUUID - */ - private Response getActionsByUniqueID(String actionUUID, HttpServletRequest servletRequest, - String actionInvariantUUID) { - LOGGER.debug( - " entering getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " + - actionUUID); - Map responseDTO = new LinkedHashMap<>(); - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(actionUUID); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - Action action = actionManager.getActionsByActionUuId(actionUUID); - if (action.getActionInvariantUuId() != null && - action.getActionInvariantUuId().equalsIgnoreCase(actionInvariantUUID)) { - responseDTO = JsonUtil.json2Object(action.getData(), LinkedHashMap.class); - responseDTO.put(STATUS, action.getStatus().name()); - responseDTO.put(TIMESTAMP, getUtcDateStringFromTimestamp(action.getTimestamp())); - responseDTO.put(UPDATED_BY, action.getUser()); - } else { - throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); - } - } else { - checkAndThrowError(errorMap); + /** + * Get all actions with given action name + */ + private Response getActionsByName(String name, HttpServletRequest servletRequest) { + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(name); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_NAME, name); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - LOGGER.debug( - " exit getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " + - actionUUID); - return Response.ok(responseDTO).build(); - } - /** - * Get all actions with given Vendor Name - */ - private Response getActionsByVendor(String vendor, HttpServletRequest servletRequest) { - //Validate request syntax before passing to the manager - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(vendor); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = actionManager.getFilteredActions(FILTER_TYPE_VENDOR, vendor); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + /** + * Get an action with given ActionUUID + */ + private Response getActionsByUniqueID(String actionUUID, HttpServletRequest servletRequest, String actionInvariantUUID) { + LOGGER.debug(" entering getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " + actionUUID); + Map responseDTO = new LinkedHashMap<>(); + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(actionUUID); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + Action action = actionManager.getActionsByActionUuId(actionUUID); + if (action.getActionInvariantUuId() != null && action.getActionInvariantUuId().equalsIgnoreCase(actionInvariantUUID)) { + responseDTO = JsonUtil.json2Object(action.getData(), LinkedHashMap.class); + responseDTO.put(STATUS, action.getStatus().name()); + responseDTO.put(TIMESTAMP, getUtcDateStringFromTimestamp(action.getTimestamp())); + responseDTO.put(UPDATED_BY, action.getUser()); + } else { + throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); + } + } else { + checkAndThrowError(errorMap); + } + LOGGER.debug(" exit getActionByUUID with invariantID= " + actionInvariantUUID + " and actionUUID= " + actionUUID); + return Response.ok(responseDTO).build(); } - return Response.ok(responseList).build(); - } - /** - * Get all actions with given Category Name - */ - private Response getActionsByCategory(String category, HttpServletRequest servletRequest) { - //Validate request syntax before passing to the manager - ListResponseWrapper responseList = null; - Map errorMap = validateRequestHeaders(servletRequest); - Map queryParamErrors = validateQueryParam(category); - errorMap.putAll(queryParamErrors); - if (errorMap.isEmpty()) { - List actions = actionManager.getFilteredActions(FILTER_TYPE_CATEGORY, category); - responseList = createResponse(actions); - } else { - checkAndThrowError(errorMap); + /** + * Get all actions with given Vendor Name + */ + private Response getActionsByVendor(String vendor, HttpServletRequest servletRequest) { + //Validate request syntax before passing to the manager + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(vendor); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_VENDOR, vendor); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - return Response.ok(responseList).build(); - } - /** - * Validates mandatory headers in the request - * - * @param servletRequest Servlet Request object - * @return Map of error codes and description found in the request headers - */ - private Map validateRequestHeaders(HttpServletRequest servletRequest) { - Map errorMap = new LinkedHashMap<>(); - //Syntactic generic request parameter validations - String openEcompRequestId = servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM); - if (StringUtils.isEmpty(openEcompRequestId)) { - errorMap.put(ACTION_INVALID_REQUEST_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID); + /** + * Get all actions with given Category Name + */ + private Response getActionsByCategory(String category, HttpServletRequest servletRequest) { + //Validate request syntax before passing to the manager + ListResponseWrapper responseList = null; + Map errorMap = validateRequestHeaders(servletRequest); + Map queryParamErrors = validateQueryParam(category); + errorMap.putAll(queryParamErrors); + if (errorMap.isEmpty()) { + List actions = actionManager.getFilteredActions(FILTER_TYPE_CATEGORY, category); + responseList = createResponse(actions); + } else { + checkAndThrowError(errorMap); + } + return Response.ok(responseList).build(); } - String opemnEcompInstanceId = servletRequest.getHeader(X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM); - if (StringUtils.isEmpty(opemnEcompInstanceId)) { - errorMap.put(ACTION_INVALID_INSTANCE_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID); + /** + * Validates mandatory headers in the request + * + * @param servletRequest Servlet Request object + * @return Map of error codes and description found in the request headers + */ + private Map validateRequestHeaders(HttpServletRequest servletRequest) { + Map errorMap = new LinkedHashMap<>(); + //Syntactic generic request parameter validations + String openEcompRequestId = servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM); + if (StringUtils.isEmpty(openEcompRequestId)) { + errorMap.put(ACTION_INVALID_REQUEST_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID); + } + String opemnEcompInstanceId = servletRequest.getHeader(X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM); + if (StringUtils.isEmpty(opemnEcompInstanceId)) { + errorMap.put(ACTION_INVALID_INSTANCE_ID_CODE, ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID); + } + return errorMap; } - return errorMap; - } - /** - * Validates query parameter in the request - * - * @param queryParam Query Parameter to be validated - * @return Map of error codes and description found in the query parameter - */ - private Map validateQueryParam(String queryParam) { - Map queryParamErrors = new LinkedHashMap<>(); - if (StringUtils.isEmpty(queryParam)) { - queryParamErrors - .put(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + queryParam); + /** + * Validates query parameter in the request + * + * @param queryParam Query Parameter to be validated + * @return Map of error codes and description found in the query parameter + */ + private Map validateQueryParam(String queryParam) { + Map queryParamErrors = new LinkedHashMap<>(); + if (StringUtils.isEmpty(queryParam)) { + queryParamErrors.put(ACTION_INVALID_PARAM_CODE, ACTION_REQUEST_MISSING_MANDATORY_PARAM + queryParam); + } + return queryParamErrors; } - return queryParamErrors; - } - /** - * Validate request body based on request type - * - * @param requestJSON Raw request json body as string - * @return Map of error codes and description found in the request body - */ - private Map validateRequestBody(String requestType, String requestJSON) { - Map requestBodyErrorMap = new LinkedHashMap<>(); - if (StringUtils.isEmpty(requestJSON) || requestJSON.equals(REQUEST_EMPTY_BODY)) { - requestBodyErrorMap.put(ACTION_INVALID_REQUEST_BODY_CODE, ACTION_REQUEST_BODY_EMPTY); - } else { - if(requestType == ActionConstants.REQUEST_TYPE_CREATE_ACTION - || requestType == ActionConstants.REQUEST_TYPE_UPDATE_ACTION){ - //Semantic request specific validations - Action action = JsonUtil.json2Object(requestJSON, Action.class); - if(StringUtils.isEmpty(action.getName())){ - setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_NAME, - requestBodyErrorMap); + /** + * Validate request body based on request type + * + * @param requestJSON Raw request json body as string + * @return Map of error codes and description found in the request body + */ + private Map validateRequestBody(String requestType, String requestJSON) { + Map requestBodyErrorMap = new LinkedHashMap<>(); + if (StringUtils.isEmpty(requestJSON) || requestJSON.equals(REQUEST_EMPTY_BODY)) { + requestBodyErrorMap.put(ACTION_INVALID_REQUEST_BODY_CODE, ACTION_REQUEST_BODY_EMPTY); } else { - //Added check for action names not allowing whitespaces - if (action.getName().matches(whitespaceRegex)){ - requestBodyErrorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_REQUEST_INVALID_NAME); - } + if (requestType == ActionConstants.REQUEST_TYPE_CREATE_ACTION || requestType == ActionConstants.REQUEST_TYPE_UPDATE_ACTION) { + //Semantic request specific validations + Action action = JsonUtil.json2Object(requestJSON, Action.class); + if (StringUtils.isEmpty(action.getName())) { + setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_NAME, requestBodyErrorMap); + } else { + //Added check for action names not allowing whitespaces + if (action.getName().matches(whitespaceRegex)) { + requestBodyErrorMap.put(ACTION_ARTIFACT_INVALID_NAME_CODE, ACTION_REQUEST_INVALID_NAME); + } + } + if (action.getSupportedModels() != null && !isIDPresentInMap(action.getSupportedModels(), SUPPORTED_MODELS_VERSION_ID)) { + setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap); + } + if (action.getSupportedComponents() != null && !isIDPresentInMap(action.getSupportedComponents(), SUPPORTED_COMPONENTS_ID)) { + setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, ACTION_REQUEST_PARAM_SUPPORTED_COMPONENTS, requestBodyErrorMap); + } + if (action.getArtifacts() != null) { + setErrorValue(ACTION_UPDATE_NOT_ALLOWED_CODE, ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED, requestBodyErrorMap); + } + } } + return requestBodyErrorMap; + } - if(action.getSupportedModels() != null && !isIDPresentInMap(action.getSupportedModels(), - SUPPORTED_MODELS_VERSION_ID)){ - setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, - ACTION_REQUEST_PARAM_SUPPORTED_MODELS, requestBodyErrorMap); - } - if(action.getSupportedComponents() != null && !isIDPresentInMap(action - .getSupportedComponents(), SUPPORTED_COMPONENTS_ID)){ - setErrorValue(ACTION_REQUEST_INVALID_GENERIC_CODE, - ACTION_REQUEST_PARAM_SUPPORTED_COMPONENTS, requestBodyErrorMap); - } - if(action.getArtifacts() != null){ - setErrorValue(ACTION_UPDATE_NOT_ALLOWED_CODE, - ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED, requestBodyErrorMap); + /** + * Populates Given Error Map with Given Error Code and Error MEssage + */ + private void setErrorValue(String key, String message, Map errorMap) { + String errorMessage = errorMap.get(key); + if (errorMessage != null) { + message = errorMessage + ", " + message; + } else { + if (key == ACTION_REQUEST_INVALID_GENERIC_CODE) { + message = ACTION_REQUEST_MISSING_MANDATORY_PARAM + message; + } } - } - + errorMap.put(key, message); } - return requestBodyErrorMap; - } - /** - * Populates Given Error Map with Given Error Code and Error MEssage - */ - private void setErrorValue(String key, String message, Map errorMap) { - String errorMessage = errorMap.get(key); - if (errorMessage != null) { - message = errorMessage + ", " + message; - } else { - if(key == ACTION_REQUEST_INVALID_GENERIC_CODE) - message = ACTION_REQUEST_MISSING_MANDATORY_PARAM + message; + /** + * Returns true if given key exists in List of HashMap + */ + private boolean isIDPresentInMap(List> map, String idName) { + if (map != null && !map.isEmpty()) { + for (Map entry : map) { + if (StringUtils.isEmpty(entry.get(idName))) { + return false; + } + } + } + return true; } - errorMap.put(key, message); - } - /** - * Returns true if given key exists in List of HashMap - */ - private boolean isIDPresentInMap(List> map, String idName) { - if (map != null && !map.isEmpty()) { - for (Map entry : map) { - if (StringUtils.isEmpty(entry.get(idName))) { - return false; + /** + * @throws ActionException if given ErrorMap is not empty. All error messages at given time are thrown in one single exception + */ + private void checkAndThrowError(Map errorMap) { + if (errorMap.size() > 1) { + //Multiple errors detected .. Send the response with a common error code for multiple errors + throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE, StringUtils.join(errorMap.values(), ", ")); + } else if (errorMap.size() == 1) { + String svcPolicyExceptionCode = errorMap.entrySet().iterator().next().getKey(); + throw new ActionException(svcPolicyExceptionCode, errorMap.get(svcPolicyExceptionCode)); } - } } - return true; - } - /** - * @throws ActionException if given ErrorMap is not empty. All error messages at given time are - * thrown in one single exception - */ - private void checkAndThrowError(Map errorMap) { - if (errorMap.size() > 1) { - //Multiple errors detected .. Send the response with a common error code for multiple errors - throw new ActionException(ACTION_REQUEST_INVALID_GENERIC_CODE, - StringUtils.join(errorMap.values(), ", ")); - } else if (errorMap.size() == 1) { - String svcPolicyExceptionCode = errorMap.entrySet().iterator().next().getKey(); - throw new ActionException(svcPolicyExceptionCode, - errorMap.get(svcPolicyExceptionCode)); + /** + * Populates ActionResponseDto based on given Action + */ + private ActionResponseDto createResponseDTO(Action action) { + String data = action.getData(); + ActionResponseDto responseDTO = JsonUtil.json2Object(data, ActionResponseDto.class); + responseDTO.setStatus(action.getStatus().name()); + responseDTO.setTimestamp(getUtcDateStringFromTimestamp(action.getTimestamp())); + //if(!action.getUser().equals(DELETE_ACTION_USER)) + responseDTO.setUpdatedBy(action.getUser()); + return responseDTO; } - } - /** - * Populates ActionResponseDto based on given Action - */ - private ActionResponseDto createResponseDTO(Action action) { - String data = action.getData(); - ActionResponseDto responseDTO = JsonUtil.json2Object(data, ActionResponseDto.class); - responseDTO.setStatus(action.getStatus().name()); - responseDTO.setTimestamp(getUtcDateStringFromTimestamp(action.getTimestamp())); - //if(!action.getUser().equals(DELETE_ACTION_USER)) - responseDTO.setUpdatedBy(action.getUser()); - return responseDTO; - } - - /** - * Creates response based on given list of actions - */ - private ListResponseWrapper createResponse(List actions) { - ListResponseWrapper responseList = new ListResponseWrapper(); - for (Action action : actions) { - ActionResponseDto responseDTO = createResponseDTO(action); - responseList.add(responseDTO); + /** + * Creates response based on given list of actions + */ + private ListResponseWrapper createResponse(List actions) { + ListResponseWrapper responseList = new ListResponseWrapper(); + for (Action action : actions) { + ActionResponseDto responseDTO = createResponseDTO(action); + responseList.add(responseDTO); + } + return responseList; } - return responseList; - } - - private Response createArtifactDownloadResponse(ActionArtifact actionartifact) { - if (actionartifact != null && actionartifact.getArtifact() != null) { - byte[] artifactsBytes = actionartifact.getArtifact(); - File artifactFile = new File(actionartifact.getArtifactName()); - try (FileOutputStream fos = new FileOutputStream(artifactFile)) { - fos.write(artifactsBytes); - } catch (IOException exception) { - LOGGER.error(ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, exception); - throw new ActionException(ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE, - ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); - } - Response.ResponseBuilder responseBuilder = Response.ok(artifactFile); - responseBuilder.header("Content-Disposition", - "attachment; filename=" + actionartifact.getArtifactName()); - responseBuilder.header("Content-MD5", CalcMD5CheckSum(artifactsBytes)); - responseBuilder.header("Content-Length", artifactFile.length()); - return responseBuilder.build(); - } else { - throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, - ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); + private Response createArtifactDownloadResponse(ActionArtifact actionartifact) { + if (actionartifact != null && actionartifact.getArtifact() != null) { + byte[] artifactsBytes = actionartifact.getArtifact(); + File artifactFile = new File(actionartifact.getArtifactName()); + try (FileOutputStream fos = new FileOutputStream(artifactFile)) { + fos.write(artifactsBytes); + } catch (IOException exception) { + LOGGER.error(ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, exception); + throw new ActionException(ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE, + ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG); + } + Response.ResponseBuilder responseBuilder = Response.ok(artifactFile); + responseBuilder.header("Content-Disposition", "attachment; filename=" + actionartifact.getArtifactName()); + responseBuilder.header("Content-MD5", CalcMD5CheckSum(artifactsBytes)); + responseBuilder.header("Content-Length", artifactFile.length()); + return responseBuilder.build(); + } else { + throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, + ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); + } } - } - - /** - * Initialize MDC for logging the current request - * - * @param actionInvariantId Action Invariant Id if available (null otherwise) - * @param servletRequest Request Contecxt object - * @param requestType Current action request (CRUD of Action, Artifact, Version operations) - */ - private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId, - ActionRequest requestType) { - MDC.put(REQUEST_ID, servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM)); - MDC.put(PARTNER_NAME, servletRequest.getRemoteUser()); - MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID); - MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis())); - MDC.put(STATUS_CODE, COMPLETE.name()); - MDC.put(SERVICE_NAME, requestType.name()); - MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST)); - MDC.put(SERVICE_INSTANCE_ID, actionInvariantId); - MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress")); - MDC.put(BE_FQDN, MDC.get("ServerFQDN")); - if (LOGGER.isDebugEnabled()) { - MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name()); - } else if (LOGGER.isInfoEnabled()) { - MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name()); - } else if (LOGGER.isWarnEnabled()) { - MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name()); - } else if (LOGGER.isErrorEnabled()) { - MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name()); + /** + * Initialize MDC for logging the current request + * + * @param actionInvariantId Action Invariant Id if available (null otherwise) + * @param servletRequest Request Contecxt object + * @param requestType Current action request (CRUD of Action, Artifact, Version operations) + */ + private void initializeRequestMDC(HttpServletRequest servletRequest, String actionInvariantId, ActionRequest requestType) { + MDC.put(REQUEST_ID, servletRequest.getHeader(X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM)); + MDC.put(PARTNER_NAME, servletRequest.getRemoteUser()); + MDC.put(INSTANCE_UUID, MDC_ASDC_INSTANCE_UUID); + MDC.put(SERVICE_METRIC_BEGIN_TIMESTAMP, String.valueOf(System.currentTimeMillis())); + MDC.put(STATUS_CODE, COMPLETE.name()); + MDC.put(SERVICE_NAME, requestType.name()); + MDC.put(CLIENT_IP, MDC.get(REMOTE_HOST)); + MDC.put(SERVICE_INSTANCE_ID, actionInvariantId); + MDC.put(LOCAL_ADDR, MDC.get("ServerIPAddress")); + MDC.put(BE_FQDN, MDC.get("ServerFQDN")); + if (LOGGER.isDebugEnabled()) { + MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.DEBUG.name()); + } else if (LOGGER.isInfoEnabled()) { + MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.INFO.name()); + } else if (LOGGER.isWarnEnabled()) { + MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.WARN.name()); + } else if (LOGGER.isErrorEnabled()) { + MDC.put(CATEGORY_LOG_LEVEL, CategoryLogLevel.ERROR.name()); + } } - } - private String CalcMD5CheckSum(byte[] input) { - String checksum = null; - if (input != null) { - checksum = DigestUtils.md5Hex(input).toUpperCase(); - System.out.println("checksum : " + checksum); + private String CalcMD5CheckSum(byte[] input) { + String checksum = null; + if (input != null) { + checksum = DigestUtils.md5Hex(input).toUpperCase(); + System.out.println("checksum : " + checksum); + } + return checksum; } - return checksum; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionResponseDto.java index 804473b008..dc0f33b3ba 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionResponseDto.java @@ -17,13 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.types; - import java.util.HashMap; import java.util.List; -import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionVersionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionVersionDto.java index 2925fe106b..30b4ba825b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionVersionDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ActionVersionDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.types; import lombok.Getter; @@ -28,5 +27,4 @@ import lombok.Setter; public class ActionVersionDto { String status; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ListResponseWrapper.java b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ListResponseWrapper.java index f60a5cafa4..24c19bf485 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ListResponseWrapper.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/action-library-rest/action-library-rest-types/src/main/java/org/openecomp/sdcrests/action/types/ListResponseWrapper.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.action.types; import java.util.ArrayList; @@ -27,8 +26,7 @@ import lombok.Setter; import org.openecomp.sdc.action.types.OpenEcompComponent; /** - * Defines DTO used for creating Response with list of {@link ActionResponseDto } or list of {@link - * openEcompComponent }. + * Defines DTO used for creating Response with list of {@link ActionResponseDto } or list of {@link openEcompComponent }. */ @Getter @Setter diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/ApplicationConfiguration.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/ApplicationConfiguration.java index 1731688e06..5145b048aa 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/ApplicationConfiguration.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/ApplicationConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.applicationconfig.rest; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.InputStream; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.applicationconfiguration.types.ApplicationConfigDto; import org.openecomp.sdcrests.applicationconfiguration.types.ConfigurationDataDto; -import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.validation.annotation.Validated; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.InputStream; -import java.util.List; - @Path("/v1.0/application-configuration") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -47,23 +48,20 @@ import java.util.List; @Validated public interface ApplicationConfiguration { - @POST - @Path("/") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Insert JSON schema into application config table") - Response insertToTable(@QueryParam("namespace") String namespace, @QueryParam("key") String key, - @Multipart("description") InputStream fileContainingSchema); - - - @GET - @Path("/{namespace}/{key}") - @Operation(description = "Get JSON schema by namespace and key", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ConfigurationDataDto.class)))) - Response getFromTable(@PathParam("namespace") String namespace, @PathParam("key") String key); - + @POST + @Path("/") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Insert JSON schema into application config table") + Response insertToTable(@QueryParam("namespace") String namespace, @QueryParam("key") String key, + @Multipart("description") InputStream fileContainingSchema); - @GET - @Path("/{namespace}") - @Operation(description = "Get List of keys and descriptions by namespace", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ApplicationConfigDto.class))))) - Response getListOfConfigurationByNamespaceFromTable(@PathParam("namespace") String namespace); + @GET + @Path("/{namespace}/{key}") + @Operation(description = "Get JSON schema by namespace and key", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ConfigurationDataDto.class)))) + Response getFromTable(@PathParam("namespace") String namespace, @PathParam("key") String key); + @GET + @Path("/{namespace}") + @Operation(description = "Get List of keys and descriptions by namespace", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ApplicationConfigDto.class))))) + Response getListOfConfigurationByNamespaceFromTable(@PathParam("namespace") String namespace); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapApplicationConfigEntityToApplicationConfigDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapApplicationConfigEntityToApplicationConfigDto.java index 4ced6ba302..60fdecd714 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapApplicationConfigEntityToApplicationConfigDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapApplicationConfigEntityToApplicationConfigDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.applicationconfig.rest.mapping; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; @@ -27,11 +26,11 @@ import org.openecomp.sdcrests.mapping.MappingBase; /** * Created by Talio on 8/10/2016. */ -public class MapApplicationConfigEntityToApplicationConfigDto - extends MappingBase { - @Override - public void doMapping(ApplicationConfigEntity source, ApplicationConfigDto target) { - target.setKey(source.getKey()); - target.setValue(source.getValue()); - } +public class MapApplicationConfigEntityToApplicationConfigDto extends MappingBase { + + @Override + public void doMapping(ApplicationConfigEntity source, ApplicationConfigDto target) { + target.setKey(source.getKey()); + target.setValue(source.getValue()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapConfigurationDataToConfigurationDataDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapConfigurationDataToConfigurationDataDto.java index c86628d301..1730a21801 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapConfigurationDataToConfigurationDataDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/mapping/MapConfigurationDataToConfigurationDataDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.applicationconfig.rest.mapping; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; @@ -27,11 +26,11 @@ import org.openecomp.sdcrests.mapping.MappingBase; /** * Created by Talio on 8/9/2016. */ -public class MapConfigurationDataToConfigurationDataDto - extends MappingBase { - @Override - public void doMapping(ConfigurationData source, ConfigurationDataDto target) { - target.setValue(source.getValue()); - target.setTimeStamp(source.getTimeStamp()); - } +public class MapConfigurationDataToConfigurationDataDto extends MappingBase { + + @Override + public void doMapping(ConfigurationData source, ConfigurationDataDto target) { + target.setValue(source.getValue()); + target.setTimeStamp(source.getTimeStamp()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/services/ApplicationConfigurationImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/services/ApplicationConfigurationImpl.java index 349ec87276..2f6c8a8be6 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/services/ApplicationConfigurationImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-services/src/main/java/org/openecomp/sdcrests/applicationconfig/rest/services/ApplicationConfigurationImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,9 +19,12 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdcrests.applicationconfig.rest.services; +import java.io.InputStream; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; import org.openecomp.core.utilities.file.FileUtils; @@ -36,55 +39,43 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.io.InputStream; -import java.util.Collection; - /** * Created by Talio on 8/8/2016. */ - @Named @Service("applicationConfiguration") @Scope(value = "prototype") public class ApplicationConfigurationImpl implements ApplicationConfiguration { - private final ApplicationConfigManager applicationConfigManager; - - @Autowired - public ApplicationConfigurationImpl(ApplicationConfigManager applicationConfigManager) { - this.applicationConfigManager = applicationConfigManager; - } + private final ApplicationConfigManager applicationConfigManager; - @Override - public Response insertToTable(String namespace, String key, InputStream fileContainingSchema) { - String value = new String(FileUtils.toByteArray(fileContainingSchema)); - applicationConfigManager.insertIntoTable(namespace, key, value); - return Response.ok().build(); - } + @Autowired + public ApplicationConfigurationImpl(ApplicationConfigManager applicationConfigManager) { + this.applicationConfigManager = applicationConfigManager; + } - @Override - public Response getFromTable(String namespace, String key) { - ConfigurationData value = applicationConfigManager.getFromTable(namespace, key); - ConfigurationDataDto valueDto = new MapConfigurationDataToConfigurationDataDto() - .applyMapping(value, ConfigurationDataDto.class); - return Response.ok(valueDto).build(); - } + @Override + public Response insertToTable(String namespace, String key, InputStream fileContainingSchema) { + String value = new String(FileUtils.toByteArray(fileContainingSchema)); + applicationConfigManager.insertIntoTable(namespace, key, value); + return Response.ok().build(); + } - @Override - public Response getListOfConfigurationByNamespaceFromTable(String namespace) { - Collection applicationConfigEntities = - applicationConfigManager.getListOfConfigurationByNamespace(namespace); - GenericCollectionWrapper applicationConfigWrapper = - new GenericCollectionWrapper<>(); - MapApplicationConfigEntityToApplicationConfigDto mapper = - new MapApplicationConfigEntityToApplicationConfigDto(); + @Override + public Response getFromTable(String namespace, String key) { + ConfigurationData value = applicationConfigManager.getFromTable(namespace, key); + ConfigurationDataDto valueDto = new MapConfigurationDataToConfigurationDataDto().applyMapping(value, ConfigurationDataDto.class); + return Response.ok(valueDto).build(); + } - for (ApplicationConfigEntity applicationConfigEntity : applicationConfigEntities) { - applicationConfigWrapper - .add(mapper.applyMapping(applicationConfigEntity, ApplicationConfigDto.class)); + @Override + public Response getListOfConfigurationByNamespaceFromTable(String namespace) { + Collection applicationConfigEntities = applicationConfigManager.getListOfConfigurationByNamespace(namespace); + GenericCollectionWrapper applicationConfigWrapper = new GenericCollectionWrapper<>(); + MapApplicationConfigEntityToApplicationConfigDto mapper = new MapApplicationConfigEntityToApplicationConfigDto(); + for (ApplicationConfigEntity applicationConfigEntity : applicationConfigEntities) { + applicationConfigWrapper.add(mapper.applyMapping(applicationConfigEntity, ApplicationConfigDto.class)); + } + return Response.ok(applicationConfigWrapper).build(); } - return Response.ok(applicationConfigWrapper).build(); - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ApplicationConfigDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ApplicationConfigDto.java index 63834a3983..d705d556aa 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ApplicationConfigDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ApplicationConfigDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.applicationconfiguration.types; import lombok.Getter; @@ -32,5 +31,4 @@ public class ApplicationConfigDto { private String key; private String value; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ConfigurationDataDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ConfigurationDataDto.java index 75aaf756d5..c6638680c4 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ConfigurationDataDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/application-config-rest/application-config-rest-types/src/main/java/org/openecomp/sdcrests/applicationconfiguration/types/ConfigurationDataDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.applicationconfiguration.types; import lombok.AllArgsConstructor; @@ -33,6 +32,7 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor public class ConfigurationDataDto { - private String value; - private long timeStamp; + + private String value; + private long timeStamp; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java index a6acfdba9c..0762325882 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/Conflicts.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.common.RestConstants; import org.openecomp.sdcrests.conflict.types.ConflictDto; import org.openecomp.sdcrests.conflict.types.ConflictResolutionDto; import org.openecomp.sdcrests.conflict.types.ItemVersionConflictDto; import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - @Path("/v1.0/items/{itemId}/versions/{versionId}/conflicts") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -46,35 +49,26 @@ import javax.ws.rs.core.Response; @Validated public interface Conflicts { - @GET - @Path("/") - @Operation(description = "item version conflicts", - summary = "Item version private copy conflicts against its public copy", - responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ItemVersionConflictDto.class)))) - Response getConflict(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "item version conflicts", summary = "Item version private copy conflicts against its public copy", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ItemVersionConflictDto.class)))) + Response getConflict(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{conflictId}") - @Operation(description = "Gets item version conflict", - summary = "Gets an item version private copy conflict against its public copy", - responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ConflictDto.class)))) - Response getConflict(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Version Id") @PathParam("conflictId") String conflictId, - @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{conflictId}") + @Operation(description = "Gets item version conflict", summary = "Gets an item version private copy conflict against its public copy", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ConflictDto.class)))) + Response getConflict(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Version Id") @PathParam("conflictId") String conflictId, + @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{conflictId}") - @Operation(description = "Resolves item version conflict", - summary = "Resolves an item version private copy conflict against its public copy") - Response resolveConflict(ConflictResolutionDto conflictResolution, - @Parameter(description = "Item Id") @PathParam("itemId") String itemId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Version Id") @PathParam("conflictId") String conflictId, - @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{conflictId}") + @Operation(description = "Resolves item version conflict", summary = "Resolves an item version private copy conflict against its public copy") + Response resolveConflict(ConflictResolutionDto conflictResolution, @Parameter(description = "Item Id") @PathParam("itemId") String itemId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Version Id") @PathParam("conflictId") String conflictId, + @NotNull(message = RestConstants.USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java index 274a0cc674..7213fafa0b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictInfoToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest.mapping; import org.openecomp.conflicts.types.ConflictInfo; @@ -25,10 +24,11 @@ import org.openecomp.sdcrests.conflict.types.ConflictInfoDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapConflictInfoToDto extends MappingBase { - @Override - public void doMapping(ConflictInfo source, ConflictInfoDto target) { - target.setId(source.getId()); - target.setType(source.getType()); - target.setName(source.getName()); - } + + @Override + public void doMapping(ConflictInfo source, ConflictInfoDto target) { + target.setId(source.getId()); + target.setType(source.getType()); + target.setName(source.getName()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java index 1a1f3296fa..a1615bfccf 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapConflictToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,108 +17,119 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest.mapping; +import java.util.AbstractMap; +import java.util.HashMap; +import java.util.Map; import org.openecomp.conflicts.types.Conflict; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdcrests.conflict.types.ConflictDto; import org.openecomp.sdcrests.mapping.EchoMapMapping; import org.openecomp.sdcrests.mapping.MappingBase; -import org.openecomp.sdcrests.vendorlicense.rest.mapping.*; -import org.openecomp.sdcrests.vendorlicense.types.*; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; -import org.openecomp.sdcrests.vsp.rest.mapping.*; - -import java.util.AbstractMap; -import java.util.HashMap; -import java.util.Map; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapEntitlementPoolEntityToEntitlementPoolEntityDto; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapFeatureGroupEntityToFeatureGroupDescriptorDto; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapLicenseAgreementEntityToLicenseAgreementDescriptorDto; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapLimitEntityToLimitDto; +import org.openecomp.sdcrests.vendorlicense.rest.mapping.MapVendorLicenseModelEntityToDto; +import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupDescriptorDto; +import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementDescriptorDto; +import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelEntityDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyModel; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessEntityDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentDependencyModelEntityToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentEntityToComponentDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToVspComputeDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapDeploymentFlavorEntityToDeploymentFlavorDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapImageEntityToImageDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNetworkEntityToNetworkDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNicEntityToNicDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapProcessEntityToProcessEntityDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireToQuestionnaireDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapVspDetailsToDto; public class MapConflictToDto extends MappingBase { - @Override - public void doMapping(Conflict source, ConflictDto target) { - target.setId(source.getId()); - target.setType(source.getType()); - target.setName(source.getName()); - - Map.Entry mapperToTargetClass = getMapper(source.getType()); - target.setTheirs(map(mapperToTargetClass, source.getTheirs())); - target.setYours(map(mapperToTargetClass, source.getYours())); - } + @Override + public void doMapping(Conflict source, ConflictDto target) { + target.setId(source.getId()); + target.setType(source.getType()); + target.setName(source.getName()); + Map.Entry mapperToTargetClass = getMapper(source.getType()); + target.setTheirs(map(mapperToTargetClass, source.getTheirs())); + target.setYours(map(mapperToTargetClass, source.getYours())); + } - private Map map(Map.Entry mapperToTargetClass, Object object) { - return JsonUtil - .json2Object(JsonUtil.object2Json( - mapperToTargetClass.getKey().applyMapping(object, mapperToTargetClass.getValue())), - Map.class); - } + private Map map(Map.Entry mapperToTargetClass, Object object) { + return JsonUtil + .json2Object(JsonUtil.object2Json(mapperToTargetClass.getKey().applyMapping(object, mapperToTargetClass.getValue())), Map.class); + } - private Map.Entry getMapper(ElementType type) { - switch (type) { - case VendorLicenseModel: - return new AbstractMap.SimpleEntry<>(new MapVendorLicenseModelEntityToDto(), - VendorLicenseModelEntityDto.class); - case LicenseAgreement: - return new AbstractMap.SimpleEntry<>( - new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto(), - LicenseAgreementDescriptorDto.class); - case FeatureGroup: - return new AbstractMap.SimpleEntry<>(new MapFeatureGroupEntityToFeatureGroupDescriptorDto(), - FeatureGroupDescriptorDto.class); - case LicenseKeyGroup: - return new AbstractMap.SimpleEntry<>( - new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(), LicenseKeyGroupEntityDto - .class); - case EntitlementPool: - return new AbstractMap.SimpleEntry<>( - new MapEntitlementPoolEntityToEntitlementPoolEntityDto(), EntitlementPoolEntityDto - .class); - case Limit: - return new AbstractMap.SimpleEntry<>(new MapLimitEntityToLimitDto(), LimitEntityDto.class); - case VendorSoftwareProduct: - return new AbstractMap.SimpleEntry<>(new MapVspDetailsToDto(), VspDetailsDto.class); - case Network: - return new AbstractMap.SimpleEntry<>(new MapNetworkEntityToNetworkDto(), NetworkDto.class); - case Component: - return new AbstractMap.SimpleEntry<>(new MapComponentEntityToComponentDto(), - ComponentDto.class); - case ComponentDependencies: - return new AbstractMap.SimpleEntry<>(new MapComponentDependencyModelEntityToDto(), - ComponentDependencyModel.class); - case Nic: - return new AbstractMap.SimpleEntry<>(new MapNicEntityToNicDto(), NicDto.class); - case Process: - return new AbstractMap.SimpleEntry<>(new MapProcessEntityToProcessEntityDto(), - ProcessEntityDto.class); - case DeploymentFlavor: - return new AbstractMap.SimpleEntry<>(new MapDeploymentFlavorEntityToDeploymentFlavorDto(), - DeploymentFlavorDto.class); - case Compute: - return new AbstractMap.SimpleEntry<>(new MapComputeEntityToVspComputeDto(), - VspComputeDto.class); - case Image: - return new AbstractMap.SimpleEntry<>(new MapImageEntityToImageDto(), ImageDto.class); - case VSPQuestionnaire: - case NicQuestionnaire: - case ComponentQuestionnaire: - case ImageQuestionnaire: - case ComputeQuestionnaire: - return new AbstractMap.SimpleEntry<>(new MapQuestionnaireToQuestionnaireDto(), - QuestionnaireDto.class); - case SNMP_POLL: - case SNMP_TRAP: - case VES_EVENTS: - case OrchestrationTemplateCandidate: - return new AbstractMap.SimpleEntry<>(new MapFilesDataStructureToDto(), - FileDataStructureDto.class); - case ServiceModel: - case NetworkPackage: - return new AbstractMap.SimpleEntry<>(new EchoMapMapping(), HashMap.class); - case itemVersion: - return new AbstractMap.SimpleEntry<>(new EchoMapMapping(), HashMap.class); + private Map.Entry getMapper(ElementType type) { + switch (type) { + case VendorLicenseModel: + return new AbstractMap.SimpleEntry<>(new MapVendorLicenseModelEntityToDto(), VendorLicenseModelEntityDto.class); + case LicenseAgreement: + return new AbstractMap.SimpleEntry<>(new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto(), + LicenseAgreementDescriptorDto.class); + case FeatureGroup: + return new AbstractMap.SimpleEntry<>(new MapFeatureGroupEntityToFeatureGroupDescriptorDto(), FeatureGroupDescriptorDto.class); + case LicenseKeyGroup: + return new AbstractMap.SimpleEntry<>(new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(), LicenseKeyGroupEntityDto.class); + case EntitlementPool: + return new AbstractMap.SimpleEntry<>(new MapEntitlementPoolEntityToEntitlementPoolEntityDto(), EntitlementPoolEntityDto.class); + case Limit: + return new AbstractMap.SimpleEntry<>(new MapLimitEntityToLimitDto(), LimitEntityDto.class); + case VendorSoftwareProduct: + return new AbstractMap.SimpleEntry<>(new MapVspDetailsToDto(), VspDetailsDto.class); + case Network: + return new AbstractMap.SimpleEntry<>(new MapNetworkEntityToNetworkDto(), NetworkDto.class); + case Component: + return new AbstractMap.SimpleEntry<>(new MapComponentEntityToComponentDto(), ComponentDto.class); + case ComponentDependencies: + return new AbstractMap.SimpleEntry<>(new MapComponentDependencyModelEntityToDto(), ComponentDependencyModel.class); + case Nic: + return new AbstractMap.SimpleEntry<>(new MapNicEntityToNicDto(), NicDto.class); + case Process: + return new AbstractMap.SimpleEntry<>(new MapProcessEntityToProcessEntityDto(), ProcessEntityDto.class); + case DeploymentFlavor: + return new AbstractMap.SimpleEntry<>(new MapDeploymentFlavorEntityToDeploymentFlavorDto(), DeploymentFlavorDto.class); + case Compute: + return new AbstractMap.SimpleEntry<>(new MapComputeEntityToVspComputeDto(), VspComputeDto.class); + case Image: + return new AbstractMap.SimpleEntry<>(new MapImageEntityToImageDto(), ImageDto.class); + case VSPQuestionnaire: + case NicQuestionnaire: + case ComponentQuestionnaire: + case ImageQuestionnaire: + case ComputeQuestionnaire: + return new AbstractMap.SimpleEntry<>(new MapQuestionnaireToQuestionnaireDto(), QuestionnaireDto.class); + case SNMP_POLL: + case SNMP_TRAP: + case VES_EVENTS: + case OrchestrationTemplateCandidate: + return new AbstractMap.SimpleEntry<>(new MapFilesDataStructureToDto(), FileDataStructureDto.class); + case ServiceModel: + case NetworkPackage: + return new AbstractMap.SimpleEntry<>(new EchoMapMapping(), HashMap.class); + case itemVersion: + return new AbstractMap.SimpleEntry<>(new EchoMapMapping(), HashMap.class); + } + throw new RuntimeException("Get conflict does not support element type: " + type.name()); } - throw new RuntimeException("Get conflict does not support element type: " + type.name()); - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java index a2b70834c6..c439d5e7ba 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapDtoToConflictResolution.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest.mapping; import org.openecomp.conflicts.types.ConflictResolution; import org.openecomp.sdcrests.conflict.types.ConflictResolutionDto; import org.openecomp.sdcrests.mapping.MappingBase; -public class MapDtoToConflictResolution - extends MappingBase { +public class MapDtoToConflictResolution extends MappingBase { - @Override - public void doMapping(ConflictResolutionDto source, ConflictResolution target) { - target.setResolution(source.getResolution()); - target.setOtherResolution(source.getOtherResolution()); - } + @Override + public void doMapping(ConflictResolutionDto source, ConflictResolution target) { + target.setResolution(source.getResolution()); + target.setOtherResolution(source.getOtherResolution()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java index 51201a884b..a3ae77fc79 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/mapping/MapItemVersionConflictToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest.mapping; - import org.openecomp.conflicts.types.ItemVersionConflict; import org.openecomp.sdcrests.conflict.types.ConflictDto; import org.openecomp.sdcrests.conflict.types.ConflictInfoDto; import org.openecomp.sdcrests.conflict.types.ItemVersionConflictDto; import org.openecomp.sdcrests.mapping.MappingBase; -public class MapItemVersionConflictToDto - extends MappingBase { - - @Override - public void doMapping(ItemVersionConflict source, ItemVersionConflictDto target) { - target - .setConflict(new MapConflictToDto().applyMapping(source.getVersionConflict(), ConflictDto.class)); +public class MapItemVersionConflictToDto extends MappingBase { - MapConflictInfoToDto conflictInfoMapper = new MapConflictInfoToDto(); - source.getElementConflicts().forEach(conflictInfo -> target - .addConflictInfo(conflictInfoMapper.applyMapping(conflictInfo, ConflictInfoDto.class))); - } + @Override + public void doMapping(ItemVersionConflict source, ItemVersionConflictDto target) { + target.setConflict(new MapConflictToDto().applyMapping(source.getVersionConflict(), ConflictDto.class)); + MapConflictInfoToDto conflictInfoMapper = new MapConflictInfoToDto(); + source.getElementConflicts() + .forEach(conflictInfo -> target.addConflictInfo(conflictInfoMapper.applyMapping(conflictInfo, ConflictInfoDto.class))); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java index 994c29afb1..61225b5d6f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-services/src/main/java/org/openecomp/sdcrests/conflict/rest/services/ConflictsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.rest.services; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.conflicts.types.Conflict; import org.openecomp.conflicts.types.ConflictResolution; import org.openecomp.conflicts.types.ItemVersionConflict; @@ -36,47 +37,34 @@ import org.openecomp.sdcrests.conflict.types.ItemVersionConflictDto; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; - @Named @Service("conflicts") @Scope(value = "prototype") public class ConflictsImpl implements Conflicts { - @Override - public Response getConflict(String itemId, String versionId, String user) { - - ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); - ItemVersionConflict itemVersionConflict = conflictsManager.getConflict - (itemId, new Version(versionId)); - ItemVersionConflictDto result = (new MapItemVersionConflictToDto()).applyMapping - (itemVersionConflict, ItemVersionConflictDto.class); - return Response.ok(result).build(); - } - - @Override - public Response getConflict(String itemId, String versionId, String conflictId, String user) { - ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); - Conflict conflict = conflictsManager.getConflict(itemId, new Version(versionId), conflictId); - - ConflictDto result = new MapConflictToDto().applyMapping(conflict, ConflictDto.class); - - return Response.ok(result).build(); - - } - - @Override - public Response resolveConflict(ConflictResolutionDto conflictResolution, String itemId, - String versionId, String conflictId, String user) { - ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); + @Override + public Response getConflict(String itemId, String versionId, String user) { + ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); + ItemVersionConflict itemVersionConflict = conflictsManager.getConflict(itemId, new Version(versionId)); + ItemVersionConflictDto result = (new MapItemVersionConflictToDto()).applyMapping(itemVersionConflict, ItemVersionConflictDto.class); + return Response.ok(result).build(); + } - Version version = new Version(versionId); - conflictsManager.resolveConflict(itemId, version, conflictId, - new MapDtoToConflictResolution() - .applyMapping(conflictResolution, ConflictResolution.class)); - conflictsManager.finalizeMerge(itemId, version); + @Override + public Response getConflict(String itemId, String versionId, String conflictId, String user) { + ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); + Conflict conflict = conflictsManager.getConflict(itemId, new Version(versionId), conflictId); + ConflictDto result = new MapConflictToDto().applyMapping(conflict, ConflictDto.class); + return Response.ok(result).build(); + } - return Response.ok().build(); - } + @Override + public Response resolveConflict(ConflictResolutionDto conflictResolution, String itemId, String versionId, String conflictId, String user) { + ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); + Version version = new Version(versionId); + conflictsManager.resolveConflict(itemId, version, conflictId, + new MapDtoToConflictResolution().applyMapping(conflictResolution, ConflictResolution.class)); + conflictsManager.finalizeMerge(itemId, version); + return Response.ok().build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java index 004517434e..e7179fd6a3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.types; import java.util.Map; public class ConflictDto extends ConflictInfoDto { - private Map yours; - private Map theirs; - public Map getYours() { - return yours; - } + private Map yours; + private Map theirs; + + public Map getYours() { + return yours; + } - public void setYours(Map yours) { - this.yours = yours; - } + public void setYours(Map yours) { + this.yours = yours; + } - public Map getTheirs() { - return theirs; - } + public Map getTheirs() { + return theirs; + } - public void setTheirs(Map theirs) { - this.theirs = theirs; - } + public void setTheirs(Map theirs) { + this.theirs = theirs; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java index 659ca46c8f..320fc3de61 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictInfoDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,37 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.types; import org.openecomp.sdc.datatypes.model.ElementType; public class ConflictInfoDto { - private String id; - private ElementType type; - private String name; - public String getId() { - return id; - } + private String id; + private ElementType type; + private String name; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public ElementType getType() { - return type; - } + public ElementType getType() { + return type; + } - public void setType(ElementType type) { - this.type = type; - } + public void setType(ElementType type) { + this.type = type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java index 8983c91924..6d3ca38a03 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ConflictResolutionDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.types; -import org.openecomp.conflicts.types.Resolution; - import java.util.Map; +import org.openecomp.conflicts.types.Resolution; public class ConflictResolutionDto { - private Resolution resolution; - // sits in lower level... - private Map otherResolution; - public Resolution getResolution() { - return resolution; - } + private Resolution resolution; + // sits in lower level... + private Map otherResolution; + + public Resolution getResolution() { + return resolution; + } - public void setResolution(Resolution resolution) { - this.resolution = resolution; - } + public void setResolution(Resolution resolution) { + this.resolution = resolution; + } - public Map getOtherResolution() { - return otherResolution; - } + public Map getOtherResolution() { + return otherResolution; + } - public void setOtherResolution(Map otherResolution) { - this.otherResolution = otherResolution; - } + public void setOtherResolution(Map otherResolution) { + this.otherResolution = otherResolution; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java index 005689450a..2eea6edc7a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/conflict-rest/conflict-rest-types/src/main/java/org/openecomp/sdcrests/conflict/types/ItemVersionConflictDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.conflict.types; import java.util.ArrayList; import java.util.Collection; -public class ItemVersionConflictDto{ - private ConflictDto conflict; - private Collection conflictInfoList = new ArrayList<>(); +public class ItemVersionConflictDto { + + private ConflictDto conflict; + private Collection conflictInfoList = new ArrayList<>(); - public ConflictDto getConflict() { - return conflict; - } + public ConflictDto getConflict() { + return conflict; + } - public void setConflict(ConflictDto conflict) { - this.conflict = conflict; - } + public void setConflict(ConflictDto conflict) { + this.conflict = conflict; + } - public Collection getConflictInfoList() { - return conflictInfoList; - } + public Collection getConflictInfoList() { + return conflictInfoList; + } - public void setConflictInfoList(Collection conflictInfoList) { - this.conflictInfoList = conflictInfoList; - } + public void setConflictInfoList(Collection conflictInfoList) { + this.conflictInfoList = conflictInfoList; + } - public void addConflictInfo(ConflictInfoDto conflictInfo){ - conflictInfoList.add(conflictInfo); - } + public void addConflictInfo(ConflictInfoDto conflictInfo) { + conflictInfoList.add(conflictInfo); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/HealthCheck.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/HealthCheck.java index 2a9e0a24de..31cfabdba4 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/HealthCheck.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/HealthCheck.java @@ -17,25 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.rest; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.health.types.HealthInfoDtos; -import org.springframework.validation.annotation.Validated; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.openecomp.sdcrests.health.types.HealthInfoDtos; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/healthcheck") @Produces(MediaType.APPLICATION_JSON) @@ -44,8 +41,7 @@ import javax.ws.rs.core.Response; @Validated public interface HealthCheck { - @GET - @Operation(description = "Perform health check", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = HealthInfoDtos.class)))) - Response checkHealth(); - + @GET + @Operation(description = "Perform health check", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = HealthInfoDtos.class)))) + Response checkHealth(); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/mapping/MapHealthCheckInfoToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/mapping/MapHealthCheckInfoToDto.java index 8d560027e5..1b5c690d3b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/mapping/MapHealthCheckInfoToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/mapping/MapHealthCheckInfoToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.rest.mapping; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; import org.openecomp.sdc.health.data.HealthInfo; import org.openecomp.sdcrests.health.types.HealthCheckStatus; import org.openecomp.sdcrests.health.types.HealthInfoDto; @@ -27,23 +29,17 @@ import org.openecomp.sdcrests.health.types.HealthInfoDtos; import org.openecomp.sdcrests.health.types.MonitoredModules; import org.openecomp.sdcrests.mapping.MappingBase; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - /** * Created by Talio on 8/10/2016. */ -public class MapHealthCheckInfoToDto - extends MappingBase, HealthInfoDtos> { +public class MapHealthCheckInfoToDto extends MappingBase, HealthInfoDtos> { + @Override public void doMapping(Collection source, HealthInfoDtos target) { - - List healthInfos = source.stream() - .map(healthInfo -> new HealthInfoDto( - MonitoredModules.toValue(healthInfo.getHealthCheckComponent().toString()), - HealthCheckStatus.valueOf(healthInfo.getHealthCheckStatus().toString()), - healthInfo.getVersion(), healthInfo.getDescription())).collect(Collectors.toList()); + List healthInfos = source.stream().map( + healthInfo -> new HealthInfoDto(MonitoredModules.toValue(healthInfo.getHealthCheckComponent().toString()), + HealthCheckStatus.valueOf(healthInfo.getHealthCheckStatus().toString()), healthInfo.getVersion(), healthInfo.getDescription())) + .collect(Collectors.toList()); target.setHealthInfos(healthInfos); } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/services/HealthCheckImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/services/HealthCheckImpl.java index 57ebb1f3f7..aa1cb5711c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/services/HealthCheckImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-services/src/main/java/org/openecomp/sdcrests/health/rest/services/HealthCheckImpl.java @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.rest.services; +import java.util.Arrays; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.impl.ResponseBuilderImpl; import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.health.HealthCheckManager; @@ -32,60 +35,45 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Arrays; -import java.util.Collection; - @Named @Service("healthCheck") @Scope(value = "prototype") public class HealthCheckImpl implements org.openecomp.sdcrests.health.rest.HealthCheck { - private HealthCheckManager healthCheckManager; - private static final Logger logger = LoggerFactory.getLogger(HealthCheckImpl.class); + private static final Logger logger = LoggerFactory.getLogger(HealthCheckImpl.class); + private HealthCheckManager healthCheckManager; - public HealthCheckImpl() { - try { - healthCheckManager = HealthCheckManagerFactory.getInstance().createInterface(); - } catch (Exception e) { - logger.error(e.getMessage(), e); + public HealthCheckImpl() { + try { + healthCheckManager = HealthCheckManagerFactory.getInstance().createInterface(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } } - } - - @Override - public Response checkHealth() { - HealthCheckResult healthCheckResult = new HealthCheckResult(); - - SessionContextProviderFactory.getInstance().createInterface().create("public", "dox"); - try { - Collection healthInfos = healthCheckManager.checkHealth(); - healthCheckResult.setComponentsInfo(healthInfos); - boolean someIsDown = healthInfos.stream() - .anyMatch(healthInfo -> healthInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)); - healthInfos.stream() - .filter(healthInfo -> healthInfo.getHealthCheckComponent() - .equals(org.openecomp.sdc.health.data.MonitoredModules.BE)) - .findFirst() - .ifPresent(healthInfo -> healthCheckResult.setSdcVersion(healthInfo.getVersion())); - if (someIsDown) { - Response.ResponseBuilder responseBuilder = new ResponseBuilderImpl(); - return responseBuilder.entity(healthCheckResult).status(500).build(); - } - return Response.ok(healthCheckResult).build(); - } catch (Exception ex) { - logger.error("Health check failed", ex); - Response.ResponseBuilder responseBuilder = new ResponseBuilderImpl(); - HealthInfo healthInfo = new HealthInfo(org.openecomp.sdc.health.data.MonitoredModules.BE, - HealthCheckStatus.DOWN, - "", "Failed to perform Health Check"); - Collection healthInfos = Arrays.asList(healthInfo); - healthCheckResult.setComponentsInfo(healthInfos); - return responseBuilder.entity(healthCheckResult).status(500).build(); + @Override + public Response checkHealth() { + HealthCheckResult healthCheckResult = new HealthCheckResult(); + SessionContextProviderFactory.getInstance().createInterface().create("public", "dox"); + try { + Collection healthInfos = healthCheckManager.checkHealth(); + healthCheckResult.setComponentsInfo(healthInfos); + boolean someIsDown = healthInfos.stream().anyMatch(healthInfo -> healthInfo.getHealthCheckStatus().equals(HealthCheckStatus.DOWN)); + healthInfos.stream().filter(healthInfo -> healthInfo.getHealthCheckComponent().equals(org.openecomp.sdc.health.data.MonitoredModules.BE)) + .findFirst().ifPresent(healthInfo -> healthCheckResult.setSdcVersion(healthInfo.getVersion())); + if (someIsDown) { + Response.ResponseBuilder responseBuilder = new ResponseBuilderImpl(); + return responseBuilder.entity(healthCheckResult).status(500).build(); + } + return Response.ok(healthCheckResult).build(); + } catch (Exception ex) { + logger.error("Health check failed", ex); + Response.ResponseBuilder responseBuilder = new ResponseBuilderImpl(); + HealthInfo healthInfo = new HealthInfo(org.openecomp.sdc.health.data.MonitoredModules.BE, HealthCheckStatus.DOWN, "", + "Failed to perform Health Check"); + Collection healthInfos = Arrays.asList(healthInfo); + healthCheckResult.setComponentsInfo(healthInfos); + return responseBuilder.entity(healthCheckResult).status(500).build(); + } } - } - - } - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthCheckStatus.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthCheckStatus.java index ff19640ee8..de333d269d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthCheckStatus.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthCheckStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.types; - public enum HealthCheckStatus { - UP("UP"), - DOWN("DOWN"); - + UP("UP"), DOWN("DOWN"); private String name; HealthCheckStatus(String name) { this.name = name; } - - @Override - public String toString() { - return name; - } - - public static final HealthCheckStatus toValue(String inVal){ - for (HealthCheckStatus val : values()){ - if (val.toString().equals(inVal)){ + public static final HealthCheckStatus toValue(String inVal) { + for (HealthCheckStatus val : values()) { + if (val.toString().equals(inVal)) { return val; } } return null; } + + @Override + public String toString() { + return name; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDto.java index 012a9f329b..16453ff12d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.types; - public class HealthInfoDto { + private MonitoredModules healthCheckComponent; private HealthCheckStatus healthStatus; private String version; @@ -71,11 +70,7 @@ public class HealthInfoDto { @Override public String toString() { - return "HealthInfo{" + - "healthCheckComponent='" + healthCheckComponent + '\'' + - ", healthStatus=" + healthStatus + - ", version='" + version + '\'' + - ", description='" + description + '\'' + - '}'; + return "HealthInfo{" + "healthCheckComponent='" + healthCheckComponent + '\'' + ", healthStatus=" + healthStatus + ", version='" + version + + '\'' + ", description='" + description + '\'' + '}'; } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDtos.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDtos.java index 709320df57..99a861f1f7 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDtos.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/HealthInfoDtos.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.types; - import java.util.List; import java.util.stream.Collectors; public class HealthInfoDtos { + private List healthInfos; public HealthInfoDtos() { @@ -44,8 +43,6 @@ public class HealthInfoDtos { @Override public String toString() { - return healthInfos.stream().map(healthInfoDto -> healthInfoDto.toString()) - .collect(Collectors.joining(", ")); - + return healthInfos.stream().map(healthInfoDto -> healthInfoDto.toString()).collect(Collectors.joining(", ")); } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/MonitoredModules.java b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/MonitoredModules.java index b2519d5854..74b4a439e3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/MonitoredModules.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/healthcheck-rest/healthcheck-rest-types/src/main/java/org/openecomp/sdcrests/health/types/MonitoredModules.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.health.types; - public enum MonitoredModules { - BE("BE"), - CAS("Cassandra"), - ZU("Zusammen"); - + BE("BE"), CAS("Cassandra"), ZU("Zusammen"); private String name; MonitoredModules(String name) { this.name = name; } - - @Override - public String toString() { - return name; - } - - public static final MonitoredModules toValue(String inVal){ - for (MonitoredModules val : values()){ - if (val.toString().equals(inVal)){ + public static final MonitoredModules toValue(String inVal) { + for (MonitoredModules val : values()) { + if (val.toString().equals(inVal)) { return val; } } return null; } + + @Override + public String toString() { + return name; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/ItemPermissions.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/ItemPermissions.java index c3ebc31b08..4343c1a000 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/ItemPermissions.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/ItemPermissions.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,30 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.itempermissions.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsDto; -import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsDto; +import org.openecomp.sdcrests.itempermissions.types.ItemPermissionsRequestDto; +import org.springframework.validation.annotation.Validated; /** * Created by ayalaben on 6/18/2017. @@ -52,19 +54,15 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface ItemPermissions { - @GET - @Path("/") - @Operation(description = "List users permissions assigned on item",responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ItemPermissionsDto.class))))) - Response list(@PathParam("itemId") String itemId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @PUT - @Path("/{permission}") - @Operation(description = "Update useres permission on item") - Response updatePermissions(@Valid ItemPermissionsRequestDto request, - @PathParam("itemId") String itemId, - @PathParam("permission") String permission, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List users permissions assigned on item", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ItemPermissionsDto.class))))) + Response list(@PathParam("itemId") String itemId, @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{permission}") + @Operation(description = "Update useres permission on item") + Response updatePermissions(@Valid ItemPermissionsRequestDto request, @PathParam("itemId") String itemId, + @PathParam("permission") String permission, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/mapping/MapItemPermissionsToItemPermissionsDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/mapping/MapItemPermissionsToItemPermissionsDto.java index c578cbe699..97011ef4c9 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/mapping/MapItemPermissionsToItemPermissionsDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/mapping/MapItemPermissionsToItemPermissionsDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.itempermissions.rest.mapping; import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; @@ -27,14 +26,11 @@ import org.openecomp.sdcrests.mapping.MappingBase; /** * Created by ayalaben on 6/18/2017. */ +public class MapItemPermissionsToItemPermissionsDto extends MappingBase { -public class MapItemPermissionsToItemPermissionsDto extends - MappingBase { - - - @Override - public void doMapping(ItemPermissionsEntity source, ItemPermissionsDto target) { - target.setUserId(source.getUserId()); - target.setPermission(source.getPermission()); - } + @Override + public void doMapping(ItemPermissionsEntity source, ItemPermissionsDto target) { + target.setUserId(source.getUserId()); + target.setPermission(source.getPermission()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/services/ItemPermissionsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/services/ItemPermissionsImpl.java index 213af650f7..ece235a29a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/services/ItemPermissionsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-services/src/main/java/org/openecomp/sdcrests/itempermissions/rest/services/ItemPermissionsImpl.java @@ -15,7 +15,8 @@ */ package org.openecomp.sdcrests.itempermissions.rest.services; - +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.itempermissions.PermissionsManager; import org.openecomp.sdc.itempermissions.PermissionsManagerFactory; import org.openecomp.sdcrests.itempermissions.rest.ItemPermissions; @@ -26,41 +27,28 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; - /** * Created by ayalaben on 6/18/2017. */ - @Named @Service("itemPermissions") @Scope(value = "prototype") public class ItemPermissionsImpl implements ItemPermissions { - private PermissionsManager permissionsManager = - PermissionsManagerFactory.getInstance().createInterface(); - - @Override - public Response list(String itemId, String user) { - - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - MapItemPermissionsToItemPermissionsDto mapper = new MapItemPermissionsToItemPermissionsDto(); - - permissionsManager.listItemPermissions(itemId) - .forEach(itemPermission -> results.add(mapper.applyMapping - (itemPermission, ItemPermissionsDto.class))); - - return Response.ok(results).build(); - } - - @Override - public Response updatePermissions(ItemPermissionsRequestDto request, String itemId, - String permission, String user) { - - permissionsManager.updateItemPermissions(itemId,permission,request.getAddedUsersIds(), - request.getRemovedUsersIds()); - - return Response.ok().build(); - } + private PermissionsManager permissionsManager = PermissionsManagerFactory.getInstance().createInterface(); + + @Override + public Response list(String itemId, String user) { + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + MapItemPermissionsToItemPermissionsDto mapper = new MapItemPermissionsToItemPermissionsDto(); + permissionsManager.listItemPermissions(itemId) + .forEach(itemPermission -> results.add(mapper.applyMapping(itemPermission, ItemPermissionsDto.class))); + return Response.ok(results).build(); + } + + @Override + public Response updatePermissions(ItemPermissionsRequestDto request, String itemId, String permission, String user) { + permissionsManager.updateItemPermissions(itemId, permission, request.getAddedUsersIds(), request.getRemovedUsersIds()); + return Response.ok().build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsDto.java index ef56619ff6..be3790b6e0 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.itempermissions.types; /** @@ -25,23 +24,22 @@ package org.openecomp.sdcrests.itempermissions.types; */ public class ItemPermissionsDto { - private String userId; - private String permission; - - public String getUserId() { - return userId; - } + private String userId; + private String permission; - public void setUserId(String id) { - this.userId = id; - } + public String getUserId() { + return userId; + } - public String getPermission() { - return permission; - } + public void setUserId(String id) { + this.userId = id; + } - public void setPermission(String permission) { - this.permission = permission; - } + public String getPermission() { + return permission; + } + public void setPermission(String permission) { + this.permission = permission; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsRequestDto.java index 873ff5d49e..1353b58d70 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-permissions-rest/item-permissions-rest-types/src/main/java/org/openecomp/sdcrests/itempermissions/types/ItemPermissionsRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.itempermissions.types; - - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; /** * Created by ayalaben on 6/20/2017. */ - @Schema(description = "ItemPermissionsRequest") public class ItemPermissionsRequestDto { - private Set addedUsersIds; - private Set removedUsersIds; + private Set addedUsersIds; + private Set removedUsersIds; - public Set getAddedUsersIds() { - return addedUsersIds; - } + public Set getAddedUsersIds() { + return addedUsersIds; + } - public void setAddedUsersIds(Set addedUsersIds) { - this.addedUsersIds = addedUsersIds; - } + public void setAddedUsersIds(Set addedUsersIds) { + this.addedUsersIds = addedUsersIds; + } - public Set getRemovedUsersIds() { - return removedUsersIds; - } + public Set getRemovedUsersIds() { + return removedUsersIds; + } - public void setRemovedUsersIds(Set removedUsersIds) { - this.removedUsersIds = removedUsersIds; - } + public void setRemovedUsersIds(Set removedUsersIds) { + this.removedUsersIds = removedUsersIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Items.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Items.java index ae8e095acb..066acb9370 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Items.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Items.java @@ -15,27 +15,31 @@ */ package org.openecomp.sdcrests.item.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdc.versioning.types.Item; -import org.openecomp.sdcrests.item.types.ItemActionRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdc.versioning.types.Item; +import org.openecomp.sdcrests.item.types.ItemActionRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/items") @Produces(MediaType.APPLICATION_JSON) @@ -57,23 +61,16 @@ public interface Items { @QueryParam("permission") String permissionFilter, @Parameter(description = "Filter by onboarding method", schema = @Schema(type = "string", allowableValues = {"NetworkPackage", "manual"})) @QueryParam("onboardingMethod") String onboardingMethodFilter, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); @GET @Path("/{itemId}") @Operation(description = "Get details of a item") - Response getItem(@PathParam("itemId") String itemId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + Response getItem(@PathParam("itemId") String itemId, @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); @PUT @Path("/{itemId}/actions") @Operation(description = "Acts on item version") - Response actOn(ItemActionRequestDto request, - @PathParam("itemId") String itemId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - + Response actOn(ItemActionRequestDto request, @PathParam("itemId") String itemId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java index edc0596282..0335f894b8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/Versions.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.item.types.*; -import org.springframework.validation.annotation.Validated; - import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.item.types.ActivityLogDto; +import org.openecomp.sdcrests.item.types.VersionActionRequestDto; +import org.openecomp.sdcrests.item.types.VersionDto; +import org.openecomp.sdcrests.item.types.VersionRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/items/{itemId}/versions") @Produces(MediaType.APPLICATION_JSON) @@ -47,52 +54,39 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface Versions { - @GET - @Path("/") - @Operation(description = "Lists item versions", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = VersionDto.class))))) - Response list(@PathParam("itemId") String itemId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "Lists item versions", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = VersionDto.class))))) + Response list(@PathParam("itemId") String itemId, @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/{versionId}") - @Operation(description = "Creates a new item version") - Response create(VersionRequestDto request, - @PathParam("itemId") String itemId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/{versionId}") + @Operation(description = "Creates a new item version") + Response create(VersionRequestDto request, @PathParam("itemId") String itemId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{versionId}") - @Operation(description = "Gets item version", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = VersionDto.class)))) - Response get(@PathParam("itemId") String itemId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{versionId}") + @Operation(description = "Gets item version", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = VersionDto.class)))) + Response get(@PathParam("itemId") String itemId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{versionId}/activity-logs") - @Operation(description = "Gets item version activity log", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = ActivityLogDto.class))))) - Response getActivityLog(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, - @Parameter( description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{versionId}/activity-logs") + @Operation(description = "Gets item version activity log", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ActivityLogDto.class))))) + Response getActivityLog(@Parameter(description = "Item Id") @PathParam("itemId") String itemId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{versionId}/revisions") - @Operation(description = "Gets item version revisions", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = ActivityLogDto.class))))) - Response listRevisions(@PathParam("itemId") String itemId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{versionId}/revisions") + @Operation(description = "Gets item version revisions", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ActivityLogDto.class))))) + Response listRevisions(@PathParam("itemId") String itemId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{versionId}/actions") - @Operation(description = "Acts on item version") - Response actOn(VersionActionRequestDto request, - @PathParam("itemId") String itemId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{versionId}/actions") + @Operation(description = "Acts on item version") + Response actOn(VersionActionRequestDto request, @PathParam("itemId") String itemId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java index 307b555720..633da0a92a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapActivityLogEntityToDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.rest.mapping; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; @@ -25,17 +24,15 @@ import org.openecomp.sdcrests.item.types.ActivityLogDto; import org.openecomp.sdcrests.item.types.ActivityStatus; import org.openecomp.sdcrests.mapping.MappingBase; -public class MapActivityLogEntityToDto - extends MappingBase { - +public class MapActivityLogEntityToDto extends MappingBase { - @Override - public void doMapping(ActivityLogEntity source, ActivityLogDto target) { - target.setId(source.getId()); - target.setTimestamp(source.getTimestamp()); - target.setType(source.getType().name()); - target.setComment(source.getComment()); - target.setUser(source.getUser()); - target.setStatus(new ActivityStatus(source.isSuccess(), source.getMessage())); - } + @Override + public void doMapping(ActivityLogEntity source, ActivityLogDto target) { + target.setId(source.getId()); + target.setTimestamp(source.getTimestamp()); + target.setType(source.getType().name()); + target.setComment(source.getComment()); + target.setUser(source.getUser()); + target.setStatus(new ActivityStatus(source.isSuccess(), source.getMessage())); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java index 68bd9a51fb..3bd8a7fe9f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapItemToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.rest.mapping; import org.openecomp.sdc.versioning.types.Item; @@ -25,14 +24,15 @@ import org.openecomp.sdcrests.item.types.ItemDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapItemToDto extends MappingBase { - @Override - public void doMapping(Item source, ItemDto target) { - target.setId(source.getId()); - target.setType(source.getType()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setOwner(source.getOwner()); - target.setStatus(source.getStatus().name()); - target.setProperties(source.getProperties()); - } + + @Override + public void doMapping(Item source, ItemDto target) { + target.setId(source.getId()); + target.setType(source.getType()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setOwner(source.getOwner()); + target.setStatus(source.getStatus().name()); + target.setProperties(source.getProperties()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java index b66b289ce9..13838f794b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapRevisionToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.rest.mapping; import org.openecomp.sdc.versioning.dao.types.Revision; @@ -25,11 +24,12 @@ import org.openecomp.sdcrests.item.types.RevisionDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapRevisionToDto extends MappingBase { - @Override - public void doMapping(Revision source, RevisionDto target) { - target.setId(source.getId()); - target.setMessage(source.getMessage()); - target.setUser(source.getUser()); - target.setTime(source.getTime()); - } + + @Override + public void doMapping(Revision source, RevisionDto target) { + target.setId(source.getId()); + target.setMessage(source.getMessage()); + target.setUser(source.getUser()); + target.setTime(source.getTime()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java index a29ac8acf6..382b85a761 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/mapping/MapVersionToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.rest.mapping; import org.openecomp.sdc.versioning.dao.types.Version; @@ -25,16 +24,17 @@ import org.openecomp.sdcrests.item.types.VersionDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapVersionToDto extends MappingBase { - @Override - public void doMapping(Version source, VersionDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setBaseId(source.getBaseId()); - target.setStatus(source.getStatus()); - target.setState(source.getState()); - target.setCreationTime(source.getCreationTime()); - target.setModificationTime(source.getModificationTime()); - target.setAdditionalInfo(source.getAdditionalInfo()); - } + + @Override + public void doMapping(Version source, VersionDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setBaseId(source.getBaseId()); + target.setStatus(source.getStatus()); + target.setState(source.getState()); + target.setCreationTime(source.getCreationTime()); + target.setModificationTime(source.getModificationTime()); + target.setAdditionalInfo(source.getAdditionalInfo()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/models/SyncEvent.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/models/SyncEvent.java index c057ecf7e0..716ae8dcf3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/models/SyncEvent.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/models/SyncEvent.java @@ -55,5 +55,4 @@ public class SyncEvent implements Event { public String getEntityId() { return entityId; } - -} \ No newline at end of file +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ItemsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ItemsImpl.java index 4c1a0fb659..f18de66863 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ItemsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ItemsImpl.java @@ -13,10 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID; +import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME; + import com.google.common.annotations.VisibleForTesting; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.activitylog.dao.type.ActivityType; import org.openecomp.sdc.datatypes.model.ItemType; @@ -42,17 +59,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; -import javax.annotation.PostConstruct; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; -import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_ID; -import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.ITEM_NAME; - @Named @Service("items") @Scope(value = "prototype") @@ -61,26 +67,21 @@ public class ItemsImpl implements Items { private static final String ONBOARDING_METHOD = "onboardingMethod"; private static final Logger LOGGER = LoggerFactory.getLogger(ItemsImpl.class); - private Map actionSideAffectsMap = new EnumMap<>(ItemAction.class); private ManagersProvider managersProvider; @PostConstruct public void initActionSideAffectsMap() { - actionSideAffectsMap - .put(ItemAction.ARCHIVE, new ActionSideAffects(ActivityType.Archive, NotificationEventTypes.ARCHIVE)); - actionSideAffectsMap - .put(ItemAction.RESTORE, new ActionSideAffects(ActivityType.Restore, NotificationEventTypes.RESTORE)); + actionSideAffectsMap.put(ItemAction.ARCHIVE, new ActionSideAffects(ActivityType.Archive, NotificationEventTypes.ARCHIVE)); + actionSideAffectsMap.put(ItemAction.RESTORE, new ActionSideAffects(ActivityType.Restore, NotificationEventTypes.RESTORE)); } @Override public Response actOn(ItemActionRequestDto request, String itemId, String user) { - Item item = getManagersProvider().getItemManager().get(itemId); if (item == null) { return Response.status(Response.Status.NOT_FOUND).entity(new Exception("Item does not exist.")).build(); } - switch (request.getAction()) { case ARCHIVE: getManagersProvider().getItemManager().archive(item); @@ -90,7 +91,6 @@ public class ItemsImpl implements Items { break; default: } - actionSideAffectsMap.get(request.getAction()).execute(item, user); try { Notifier catalogNotifier = NotifierFactory.getInstance(); @@ -98,81 +98,32 @@ public class ItemsImpl implements Items { } catch (Exception e) { LOGGER.error("Failed to send catalog notification on item {}", itemId, e); } - return Response.ok().build(); } @Override - public Response list(String itemStatusFilter, String versionStatusFilter, String itemTypeFilter, - String permissionFilter, String onboardingMethodFilter, String user) { - - Predicate itemPredicate = - createItemPredicate(itemStatusFilter, versionStatusFilter, itemTypeFilter, onboardingMethodFilter, - permissionFilter, user); - + public Response list(String itemStatusFilter, String versionStatusFilter, String itemTypeFilter, String permissionFilter, + String onboardingMethodFilter, String user) { + Predicate itemPredicate = createItemPredicate(itemStatusFilter, versionStatusFilter, itemTypeFilter, onboardingMethodFilter, + permissionFilter, user); GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapItemToDto mapper = new MapItemToDto(); getManagersProvider().getItemManager().list(itemPredicate).stream() - .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) - .forEach(item -> results.add(mapper.applyMapping(item, ItemDto.class))); - + .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) + .forEach(item -> results.add(mapper.applyMapping(item, ItemDto.class))); return Response.ok(results).build(); - } @Override public Response getItem(String itemId, String user) { Item item = getManagersProvider().getItemManager().get(itemId); ItemDto itemDto = new MapItemToDto().applyMapping(item, ItemDto.class); - return Response.ok(itemDto).build(); } - private class ActionSideAffects { - - private ActivityType activityType; - private NotificationEventTypes notificationType; - - private ActionSideAffects(ActivityType activityType, NotificationEventTypes notificationType) { - this.activityType = activityType; - this.notificationType = notificationType; - - } - - private Version getLatestVersion(String itemId) { - List list = getManagersProvider().getVersioningManager().list(itemId); - Optional max = list.stream().max(Version::compareTo); - - return max.orElse(null); - } - - private void execute(Item item, String user) { - notifyUsers(item.getId(), item.getName(), user, this.notificationType); - getManagersProvider().getActivityLogManager().logActivity( - new ActivityLogEntity(item.getId(), getLatestVersion(item.getId()), this.activityType, user, true, - "", "")); - } - - private void notifyUsers(String itemId, String itemName, String userName, NotificationEventTypes eventType) { - Map eventProperties = new HashMap<>(); - eventProperties.put(ITEM_NAME, itemName == null ? getManagersProvider().getItemManager().get(itemId).getName() : itemName); - eventProperties.put(ITEM_ID, itemId); - - eventProperties.put(PERMISSION_USER, userName); - - Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); - try { - getManagersProvider().getNotificationPropagationManager().notifySubscribers(syncEvent, userName); - } catch (Exception e) { - LOGGER.error("Failed to send sync notification to users subscribed to item '{}'", itemId, e); - } - } - } - - private Predicate createItemPredicate(String itemStatusFilter, String versionStatusFilter, - String itemTypeFilter, String onboardingMethodFilter, String permissionsFilter, String user) { + private Predicate createItemPredicate(String itemStatusFilter, String versionStatusFilter, String itemTypeFilter, + String onboardingMethodFilter, String permissionsFilter, String user) { Predicate itemPredicate = item -> true; - if (itemStatusFilter != null) { validateItemStatusValue(itemStatusFilter); itemPredicate = itemPredicate.and(createItemStatusPredicate(itemStatusFilter)); @@ -205,8 +156,7 @@ public class ItemsImpl implements Items { } private Predicate createVersionStatusPredicate(String filterValue) { - Set versionStatuses = - Arrays.stream(filterValue.split(",")).map(VersionStatus::valueOf).collect(Collectors.toSet()); + Set versionStatuses = Arrays.stream(filterValue.split(",")).map(VersionStatus::valueOf).collect(Collectors.toSet()); return item -> item.getVersionStatusCounters().keySet().stream().anyMatch(versionStatuses::contains); } @@ -215,9 +165,8 @@ public class ItemsImpl implements Items { } private Predicate createOnboardingMethodPredicate(String filterValue) { - return item -> !ItemType.vsp.name().equals(item.getType()) || ((String) item.getProperties() - .get(ONBOARDING_METHOD)) - .matches(formatFilter(filterValue)); + return item -> !ItemType.vsp.name().equals(item.getType()) || ((String) item.getProperties().get(ONBOARDING_METHOD)) + .matches(formatFilter(filterValue)); } private Predicate createPermissionsPredicate(String user, String filterValue) { @@ -241,7 +190,6 @@ public class ItemsImpl implements Items { for (String value : values) { VersionStatus.valueOf(value); } - } private void validateItemTypeValue(String itemTypeFilter) { @@ -265,26 +213,59 @@ public class ItemsImpl implements Items { } } - //Do not delete - is in use, duplicates code to prevent dependency on openecomp-sdc-vendor-software-product-api - private enum OnboardingMethod { - NetworkPackage, Manual - } - - @VisibleForTesting - void setManagersProvider(ManagersProvider managersProvider) { - this.managersProvider = managersProvider; - } - @VisibleForTesting Map getActionSideAffectsMap() { return actionSideAffectsMap; } private ManagersProvider getManagersProvider() { - if (managersProvider == null){ + if (managersProvider == null) { managersProvider = new ManagersProvider(); } return managersProvider; } + @VisibleForTesting + void setManagersProvider(ManagersProvider managersProvider) { + this.managersProvider = managersProvider; + } + + //Do not delete - is in use, duplicates code to prevent dependency on openecomp-sdc-vendor-software-product-api + private enum OnboardingMethod {NetworkPackage, Manual} + + private class ActionSideAffects { + + private ActivityType activityType; + private NotificationEventTypes notificationType; + + private ActionSideAffects(ActivityType activityType, NotificationEventTypes notificationType) { + this.activityType = activityType; + this.notificationType = notificationType; + } + + private Version getLatestVersion(String itemId) { + List list = getManagersProvider().getVersioningManager().list(itemId); + Optional max = list.stream().max(Version::compareTo); + return max.orElse(null); + } + + private void execute(Item item, String user) { + notifyUsers(item.getId(), item.getName(), user, this.notificationType); + getManagersProvider().getActivityLogManager() + .logActivity(new ActivityLogEntity(item.getId(), getLatestVersion(item.getId()), this.activityType, user, true, "", "")); + } + + private void notifyUsers(String itemId, String itemName, String userName, NotificationEventTypes eventType) { + Map eventProperties = new HashMap<>(); + eventProperties.put(ITEM_NAME, itemName == null ? getManagersProvider().getItemManager().get(itemId).getName() : itemName); + eventProperties.put(ITEM_ID, itemId); + eventProperties.put(PERMISSION_USER, userName); + Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); + try { + getManagersProvider().getNotificationPropagationManager().notifySubscribers(syncEvent, userName); + } catch (Exception e) { + LOGGER.error("Failed to send sync notification to users subscribed to item '{}'", itemId, e); + } + } + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ManagersProvider.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ManagersProvider.java index 9d2ca6ef57..8db02f777f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ManagersProvider.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/ManagersProvider.java @@ -37,12 +37,12 @@ import org.openecomp.sdc.versioning.VersioningManagerFactory; @Getter class ManagersProvider { + private PermissionsManager permissionsManager = PermissionsManagerFactory.getInstance().createInterface(); private AsdcItemManager asdcItemManager = AsdcItemManagerFactory.getInstance().createInterface(); private VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); private ConflictsManager conflictsManager = ConflictsManagerFactory.getInstance().createInterface(); private ActivityLogManager activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); - private NotificationPropagationManager notificationPropagationManager = NotificationPropagationManagerFactory - .getInstance().createInterface(); + private NotificationPropagationManager notificationPropagationManager = NotificationPropagationManagerFactory.getInstance().createInterface(); private ItemManager itemManager = ItemManagerFactory.getInstance().createInterface(); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java index 114a97a039..6e7703cda3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/VersionsImpl.java @@ -13,29 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; +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; + import com.google.common.annotations.VisibleForTesting; -import org.openecomp.sdc.activitylog.ActivityLogManager; -import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.inject.Named; +import javax.ws.rs.core.Response; 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.Messages; -import org.openecomp.sdc.conflicts.ConflictsManager; -import org.openecomp.sdc.conflicts.ConflictsManagerFactory; -import org.openecomp.sdc.itempermissions.PermissionsManager; -import org.openecomp.sdc.itempermissions.PermissionsManagerFactory; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; 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.versioning.AsdcItemManager; -import org.openecomp.sdc.versioning.AsdcItemManagerFactory; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.SynchronizationState; import org.openecomp.sdc.versioning.dao.types.Version; @@ -47,20 +46,17 @@ import org.openecomp.sdcrests.item.rest.mapping.MapActivityLogEntityToDto; import org.openecomp.sdcrests.item.rest.mapping.MapRevisionToDto; import org.openecomp.sdcrests.item.rest.mapping.MapVersionToDto; import org.openecomp.sdcrests.item.rest.models.SyncEvent; -import org.openecomp.sdcrests.item.types.*; +import org.openecomp.sdcrests.item.types.ActivityLogDto; +import org.openecomp.sdcrests.item.types.CommitRequestDto; +import org.openecomp.sdcrests.item.types.RevisionDto; +import org.openecomp.sdcrests.item.types.RevisionRequestDto; +import org.openecomp.sdcrests.item.types.VersionActionRequestDto; +import org.openecomp.sdcrests.item.types.VersionDto; +import org.openecomp.sdcrests.item.types.VersionRequestDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; -import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.*; - @Named @Service("versions") @Scope(value = "prototype") @@ -68,16 +64,13 @@ public class VersionsImpl implements Versions { private static final String COMMIT_ITEM_ACTION = "Commit_Item"; private static final Logger LOGGER = LoggerFactory.getLogger(VersionsImpl.class); - private ManagersProvider managersProvider; @Override public Response list(String itemId, String user) { GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapVersionToDto mapper = new MapVersionToDto(); - - getManagersProvider().getVersioningManager().list(itemId) - .forEach(version -> results.add(mapper.applyMapping(version, VersionDto.class))); + getManagersProvider().getVersioningManager().list(itemId).forEach(version -> results.add(mapper.applyMapping(version, VersionDto.class))); return Response.ok(results).build(); } @@ -86,15 +79,11 @@ public class VersionsImpl implements Versions { Version version = new Version(); version.setBaseId(baseVersionId); version.setDescription(request.getDescription()); - version = getManagersProvider().getVersioningManager() .create(itemId, version, VersionCreationMethod.valueOf(request.getCreationMethod().name())); - VersionDto versionDto = new MapVersionToDto().applyMapping(version, VersionDto.class); - - getManagersProvider().getActivityLogManager().logActivity( - new ActivityLogEntity(itemId, version, ActivityType.Create_Version, user, true, "", "")); - + getManagersProvider().getActivityLogManager() + .logActivity(new ActivityLogEntity(itemId, version, ActivityType.Create_Version, user, true, "", "")); return Response.ok(versionDto).build(); } @@ -109,10 +98,8 @@ public class VersionsImpl implements Versions { public Response getActivityLog(String itemId, String versionId, String user) { GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapActivityLogEntityToDto mapper = new MapActivityLogEntityToDto(); - getManagersProvider().getActivityLogManager().listLoggedActivities(itemId, new Version(versionId)) - .forEach(loggedActivity -> results.add(mapper.applyMapping(loggedActivity, ActivityLogDto.class))); - + .forEach(loggedActivity -> results.add(mapper.applyMapping(loggedActivity, ActivityLogDto.class))); return Response.ok(results).build(); } @@ -120,7 +107,6 @@ public class VersionsImpl implements Versions { public Response listRevisions(String itemId, String versionId, String user) { List revisions = getManagersProvider().getVersioningManager().listRevisions(itemId, new Version(versionId)); filterRevisions(revisions); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapRevisionToDto mapper = new MapRevisionToDto(); revisions.forEach(revision -> results.add(mapper.applyMapping(revision, RevisionDto.class))); @@ -136,8 +122,7 @@ public class VersionsImpl implements Versions { break; case Commit: if (!getManagersProvider().getPermissionsManager().isAllowed(itemId, user, COMMIT_ITEM_ACTION)) { - return Response.status(Response.Status.FORBIDDEN) - .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); + return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); } commit(request.getCommitRequest(), itemId, version, user); break; @@ -155,10 +140,9 @@ public class VersionsImpl implements Versions { private Version getVersion(String itemId, Version version) { Version retrievedVersion = getManagersProvider().getVersioningManager().get(itemId, version); - if (retrievedVersion.getState().getSynchronizationState() != SynchronizationState.Merging && - // looks for sdc applicative conflicts - getManagersProvider().getConflictsManager().isConflicted(itemId, retrievedVersion)) { + // looks for sdc applicative conflicts + getManagersProvider().getConflictsManager().isConflicted(itemId, retrievedVersion)) { retrievedVersion.getState().setSynchronizationState(SynchronizationState.Merging); } return retrievedVersion; @@ -170,20 +154,17 @@ public class VersionsImpl implements Versions { } private void commit(CommitRequestDto request, String itemId, Version version, String user) { - String message = request == null ? "" : request.getMessage(); - getManagersProvider().getVersioningManager().publish(itemId, version, message); notifyUsers(itemId, version, message, user, NotificationEventTypes.COMMIT); - getManagersProvider().getActivityLogManager().logActivity( - new ActivityLogEntity(itemId, version, ActivityType.Commit, user, true, "", message)); + getManagersProvider().getActivityLogManager() + .logActivity(new ActivityLogEntity(itemId, version, ActivityType.Commit, user, true, "", message)); } private void revert(RevisionRequestDto request, String itemId, String versionId) { if (request.getRevisionId() == null) { throw new CoreException(new RevisionIdNotFoundErrorBuilder().build()); } - getManagersProvider().getVersioningManager().revert(itemId, new Version(versionId), request.getRevisionId()); } @@ -195,26 +176,20 @@ public class VersionsImpl implements Versions { 3- the second revision is in format "Initial : " 4- only if a revision in this format exists we remove the first revision. */ int numOfRevisions = revisions.size(); - if (numOfRevisions > 1 && - - revisions.get(numOfRevisions - 2).getMessage().matches("Initial .*:.*")) { + if (numOfRevisions > 1 && revisions.get(numOfRevisions - 2).getMessage().matches("Initial .*:.*")) { revisions.remove(numOfRevisions - 1); } } - private void notifyUsers(String itemId, Version version, String message, String userName, - NotificationEventTypes eventType) { + private void notifyUsers(String itemId, Version version, String message, String userName, NotificationEventTypes eventType) { Map eventProperties = new HashMap<>(); eventProperties.put(ITEM_NAME, getManagersProvider().getAsdcItemManager().get(itemId).getName()); eventProperties.put(ITEM_ID, itemId); - Version ver = getManagersProvider().getVersioningManager().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); - Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); try { getManagersProvider().getNotificationPropagationManager().notifySubscribers(syncEvent, userName); @@ -223,16 +198,15 @@ public class VersionsImpl implements Versions { } } - @VisibleForTesting - void setManagersProvider(ManagersProvider managersProvider) { - this.managersProvider = managersProvider; - } - private ManagersProvider getManagersProvider() { - if (managersProvider == null){ + if (managersProvider == null) { managersProvider = new ManagersProvider(); } return managersProvider; } + @VisibleForTesting + void setManagersProvider(ManagersProvider managersProvider) { + this.managersProvider = managersProvider; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/AsyncNotifier.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/AsyncNotifier.java index 872c61e480..acdd1ae5aa 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/AsyncNotifier.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/AsyncNotifier.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification; import java.util.Collection; @@ -38,21 +37,17 @@ import org.openecomp.sdcrests.item.types.ItemAction; public class AsyncNotifier implements Notifier { private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(1); - private static final int DEFAULT_NUM_OF_RETRIES = 2; private static final long DEFAULT_INTERVAL = 5000; - private final BiFunction, ItemAction, Callable> taskProducer; private final int numberOfRetries; private final long retryInterval; - AsyncNotifier(BiFunction, ItemAction, Callable> taskProducer) { this(taskProducer, DEFAULT_NUM_OF_RETRIES, DEFAULT_INTERVAL); } - AsyncNotifier(BiFunction, ItemAction, Callable> taskProducer, int numOfRetries, - long retryInterval) { + AsyncNotifier(BiFunction, ItemAction, Callable> taskProducer, int numOfRetries, long retryInterval) { this.taskProducer = taskProducer; this.numberOfRetries = numOfRetries; this.retryInterval = retryInterval; @@ -60,30 +55,22 @@ public class AsyncNotifier implements Notifier { @Override public void execute(Collection itemIds, ItemAction action) { - Callable worker = taskProducer.apply(itemIds, action); - RetryingTask retryingTask = new RetryingTask(worker, numberOfRetries, retryInterval, EXECUTOR_SERVICE); - EXECUTOR_SERVICE.submit(LoggingContext.copyToCallable(retryingTask)); } - public enum NextAction { - RETRY, DONE - } + public enum NextAction {RETRY, DONE} static class RetryingTask implements Callable { private static final Logger LOGGER = LoggerFactory.getLogger(RetryingTask.class); - private final Callable worker; private final long delay; private final ScheduledExecutorService scheduler; private final AtomicInteger retries; - RetryingTask(Callable worker, int numOfRetries, long delay, - ScheduledExecutorService scheduler) { - + RetryingTask(Callable worker, int numOfRetries, long delay, ScheduledExecutorService scheduler) { this.worker = Objects.requireNonNull(worker); this.retries = new AtomicInteger(requirePositiveRetries(numOfRetries)); this.delay = requirePositiveDelay(delay); @@ -91,38 +78,31 @@ public class AsyncNotifier implements Notifier { } private int requirePositiveRetries(int number) { - if (number < 1) { throw new IllegalArgumentException("Number of retries must be positive"); } - return number; } private long requirePositiveDelay(long number) { - if (number < 1) { throw new IllegalArgumentException("Delay must be positive"); } - return number; } @Override public Void call() throws Exception { - NextAction next = worker.call(); if (next == NextAction.DONE) { LOGGER.debug("Task successful: {}. Not going to retry", worker); return null; } - int attempts = retries.decrementAndGet(); if (attempts < 1) { LOGGER.warn("Exhausted number of retries for task {}, exiting", worker); return null; } - scheduler.schedule(this, delay, TimeUnit.MILLISECONDS); return null; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/EntryNotConfiguredException.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/EntryNotConfiguredException.java index 070164afe6..53ccac7503 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/EntryNotConfiguredException.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/EntryNotConfiguredException.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification; /** diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/Notifier.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/Notifier.java index 9143de4212..dae07ebc05 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/Notifier.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/Notifier.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification; import java.util.Collection; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/NotifierFactory.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/NotifierFactory.java index 462ffdf00c..f0bb1648dc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/NotifierFactory.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/NotifierFactory.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification; import com.fasterxml.jackson.databind.ObjectMapper; @@ -31,29 +30,27 @@ import org.openecomp.sdcrests.item.rest.services.catalog.notification.http.HttpT import org.openecomp.sdcrests.item.types.ItemAction; /** - * Creates an instance of {@link Notifier}, initialized according to current configuration. - * The configuration must be passed via the {@link #CONFIG_FILE_PROPERTY} JVM argument. + * Creates an instance of {@link Notifier}, initialized according to current configuration. The configuration must be passed via the {@link + * #CONFIG_FILE_PROPERTY} JVM argument. */ public class NotifierFactory { private static final Logger LOGGER = LoggerFactory.getLogger(NotifierFactory.class); - private static final String CONFIG_FILE_PROPERTY = "configuration.yaml"; private static final String CONFIG_SECTION = "catalogNotificationsConfig"; - private static final Notifier INSTANCE; - private NotifierFactory() { - // prevent instantiation - } - static { INSTANCE = createInstance(); } + private NotifierFactory() { + // prevent instantiation + } + /** - * Returns a {@link Notifier} instance according to the provided configuration. If no configuration was not - * provided, or the given configuration is incorrect, then an instance with reduced functionality will be returned. + * Returns a {@link Notifier} instance according to the provided configuration. If no configuration was not provided, or the given configuration + * is incorrect, then an instance with reduced functionality will be returned. * * @return available instance of {@link Notifier} */ @@ -62,18 +59,13 @@ public class NotifierFactory { } static Notifier createInstance() { - try { - String file = Objects.requireNonNull(System.getProperty(CONFIG_FILE_PROPERTY), - "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); - + "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); Object config = getNotificationConfiguration(file); ObjectMapper mapper = new ObjectMapper(); HttpConfiguration httpConfig = mapper.convertValue(config, HttpConfiguration.class); - return new AsyncNotifier(new HttpTaskProducer(httpConfig)); - } catch (Exception e) { LOGGER.warn("Failed to initialize notifier. Notifications will not be sent", e); return new UnsupportedConfigurationNotifier(); @@ -81,18 +73,15 @@ public class NotifierFactory { } private static Object getNotificationConfiguration(String file) throws IOException { - Map configuration = Objects.requireNonNull(readConfigurationFile(file), "Configuration cannot be empty"); Object notificationConfig = configuration.get(CONFIG_SECTION); if (notificationConfig == null) { throw new EntryNotConfiguredException(CONFIG_SECTION + " section"); } - return notificationConfig; } private static Map readConfigurationFile(String file) throws IOException { - try (InputStream fileInput = new FileInputStream(file)) { YamlUtil yamlUtil = new YamlUtil(); return yamlUtil.yamlToMap(fileInput); diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpConfiguration.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpConfiguration.java index 4403bd840b..e10cd5d8c3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpConfiguration.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpConfiguration.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification.http; import lombok.AllArgsConstructor; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpNotificationTask.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpNotificationTask.java index c88ac4ecce..1904bb5072 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpNotificationTask.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpNotificationTask.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification.http; import static org.openecomp.sdcrests.item.rest.services.catalog.notification.AsyncNotifier.NextAction.DONE; @@ -42,8 +41,8 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdcrests.item.rest.services.catalog.notification.AsyncNotifier; /** - * HTTP client for notifying the Catalog of an action on items. The items are referenced by their IDs. The client can - * run multiple times, in which case only failed IDs will be re-attempted. + * HTTP client for notifying the Catalog of an action on items. The items are referenced by their IDs. The client can run multiple times, in which + * case only failed IDs will be re-attempted. * * @author evitaliy * @since 21 Nov 2018 @@ -52,10 +51,8 @@ import org.openecomp.sdcrests.item.rest.services.catalog.notification.AsyncNotif class HttpNotificationTask implements Callable { private static final Logger LOGGER = LoggerFactory.getLogger(HttpNotificationTask.class); - private static final String APPLICATION_JSON = ContentType.APPLICATION_JSON.getMimeType(); private static final String USER_ID_HEADER_PARAM = "USER_ID"; - private final String endpoint; private final String userId; private volatile Collection itemIds; @@ -68,59 +65,41 @@ class HttpNotificationTask implements Callable { @Override public synchronized AsyncNotifier.NextAction call() { - try (CloseableHttpClient client = HttpClients.createDefault()) { - HttpPost request = createPostRequest(endpoint, itemIds, userId); - try (CloseableHttpResponse response = client.execute(request)) { - StatusLine status = response.getStatusLine(); - - LOGGER.debug("Catalog notification on VSP IDs: {}, endpoint: {}, response: {}", - itemIds, endpoint, status); - + LOGGER.debug("Catalog notification on VSP IDs: {}, endpoint: {}, response: {}", itemIds, endpoint, status); itemIds = getFailedIds(itemIds, response.getEntity()); - - if ((status.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) - && (itemIds != null) && !itemIds.isEmpty()) { - + if ((status.getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) && (itemIds != null) && !itemIds.isEmpty()) { LOGGER.debug("Catalog notification on VSP IDs {} failed. Endpoint: {}. Retry", itemIds, endpoint); return RETRY; } - return DONE; } - } catch (Exception e) { LOGGER.error("Catalog notification on VSP IDs {} failed. Endpoint: {}", itemIds, endpoint, e); return DONE; } } - private HttpPost createPostRequest(String postUrl, Collection itemIds, String userId) - throws UnsupportedEncodingException { - + private HttpPost createPostRequest(String postUrl, Collection itemIds, String userId) throws UnsupportedEncodingException { HttpPost request = new HttpPost(postUrl); - request.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON); request.addHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); request.addHeader(USER_ID_HEADER_PARAM, userId); - HttpEntity entity = new StringEntity(JsonUtil.object2Json(itemIds)); request.setEntity(entity); return request; } private Collection getFailedIds(Collection itemIds, HttpEntity responseBody) { - try { NotificationResponse response = JsonUtil.json2Object(responseBody.getContent(), NotificationResponse.class); return response != null ? response.failedIds : null; } catch (Exception e) { LOGGER.error("Error getting failed IDs from response", e); } - return itemIds; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpTaskProducer.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpTaskProducer.java index d210dc21af..694aa9241c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpTaskProducer.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/src/main/java/org/openecomp/sdcrests/item/rest/services/catalog/notification/http/HttpTaskProducer.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.item.rest.services.catalog.notification.http; import java.util.Collection; @@ -35,11 +34,9 @@ import org.openecomp.sdcrests.item.types.ItemAction; * @author evitaliy * @since 21 Nov 2018 */ -public class HttpTaskProducer - implements BiFunction, ItemAction, Callable>, Notifier { +public class HttpTaskProducer implements BiFunction, ItemAction, Callable>, Notifier { private static final Logger LOGGER = LoggerFactory.getLogger(HttpTaskProducer.class); - private static final String CATALOG_HTTP_PROTOCOL = "HTTP"; private static final String CATALOG_HTTPS_PROTOCOL = "HTTPS"; private static final Map ACTION_PATHS; @@ -66,16 +63,13 @@ public class HttpTaskProducer } private static String ensureEntryConfigured(String value, String entryName) { - if (value == null) { throw new EntryNotConfiguredException(entryName); } - return value; } private static String getPortConfiguration(String protocol, HttpConfiguration config) { - if (CATALOG_HTTP_PROTOCOL.equalsIgnoreCase(protocol)) { return ensureEntryConfigured(config.getCatalogBeHttpPort(), "HTTP port"); } else if (CATALOG_HTTPS_PROTOCOL.equalsIgnoreCase(protocol)) { @@ -85,6 +79,14 @@ public class HttpTaskProducer } } + static String getApiPath(ItemAction action) { + String path = ACTION_PATHS.get(action); + if (path == null) { + throw new IllegalArgumentException("Unsupported action: " + action.name()); + } + return path; + } + @Override public Callable apply(Collection itemIds, ItemAction action) { return createNotificationTask(itemIds, action); @@ -97,20 +99,9 @@ public class HttpTaskProducer return new HttpNotificationTask(notificationEndpoint, userId, itemIds); } - static String getApiPath(ItemAction action) { - - String path = ACTION_PATHS.get(action); - if (path == null) { - throw new IllegalArgumentException("Unsupported action: " + action.name()); - } - - return path; - } - @Override public void execute(Collection itemIds, ItemAction action) { HttpNotificationTask task = createNotificationTask(itemIds, action); task.call(); } - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java index 40fb91867e..a4b688085c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ActivityLogDto.java @@ -17,69 +17,67 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; - import java.util.Date; public class ActivityLogDto { - private String id; - private Date timestamp; - private String type; - private String comment; - private String user; - private ActivityStatus status; + private String id; + private Date timestamp; + private String type; + private String comment; + private String user; + private ActivityStatus status; - public ActivityLogDto() { - } + public ActivityLogDto() { + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Date getTimestamp() { - return timestamp; - } + public Date getTimestamp() { + return timestamp; + } - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } - public String getUser() { - return user; - } + public String getUser() { + return user; + } - public void setUser(String user) { - this.user = user; - } + public void setUser(String user) { + this.user = user; + } - public ActivityStatus getStatus() { - return status; - } + public ActivityStatus getStatus() { + return status; + } - public void setStatus(ActivityStatus status) { - this.status = status; - } + public void setStatus(ActivityStatus status) { + this.status = status; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java index 1c9a53de62..821b7713eb 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/CommitRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; public class CommitRequestDto { - private String message; - public String getMessage() { - return message; - } + private String message; + + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemAction.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemAction.java index e82bc56100..2329302694 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemAction.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemAction.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; -public enum ItemAction { - ARCHIVE, - RESTORE -} +public enum ItemAction {ARCHIVE, RESTORE} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemActionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemActionRequestDto.java index 00032b62ab..d3e2041b8a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemActionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemActionRequestDto.java @@ -16,14 +16,14 @@ package org.openecomp.sdcrests.item.types; public class ItemActionRequestDto { - private ItemAction action; - public ItemAction getAction() { - return action; - } + private ItemAction action; - public void setAction(ItemAction action) { - this.action = action; - } + public ItemAction getAction() { + return action; + } + public void setAction(ItemAction action) { + this.action = action; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java index 8eff678a2c..dec7c97674 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; public class ItemCreationDto { - private String itemId; - private VersionDto version; - public String getItemId() { - return itemId; - } + private String itemId; + private VersionDto version; + + public String getItemId() { + return itemId; + } - public void setItemId(String itemId) { - this.itemId = itemId; - } + public void setItemId(String itemId) { + this.itemId = itemId; + } - public VersionDto getVersion() { - return version; - } + public VersionDto getVersion() { + return version; + } - public void setVersion(VersionDto version) { - this.version = version; - } + public void setVersion(VersionDto version) { + this.version = version; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java index 64b68eb1cf..38633fb6f7 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/ItemDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,74 +17,73 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; import java.util.Map; public class ItemDto { - private String id; - private String type; - private String name; - private String description; - private String owner; - private String status; - private Map properties; - - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getOwner() { - return owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getStatus() { - return status; - } - - public void setStatus(String status) { - this.status = status; - } - - public Map getProperties() { - return properties; - } - - public void setProperties(Map properties) { - this.properties = properties; - } + + private String id; + private String type; + private String name; + private String description; + private String owner; + private String status; + private Map properties; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java index d3a7f95b86..d7bd88f4be 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,47 +17,46 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; import java.util.Date; public class RevisionDto { - private String id; - private String message; - private Date time; - private String user; - public String getId() { - return id; - } + private String id; + private String message; + private Date time; + private String user; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public void setMessage(String message) { - this.message = message; - } + public void setId(String id) { + this.id = id; + } - public void setTime(Date time) { - this.time = time; - } + public String getMessage() { + return message; + } - public String getMessage() { - return message; - } + public void setMessage(String message) { + this.message = message; + } - public Date getTime() { - return time; - } + public Date getTime() { + return time; + } - public String getUser() { - return user; - } + public void setTime(Date time) { + this.time = time; + } - public void setUser(String user) { - this.user = user; - } + public String getUser() { + return user; + } + public void setUser(String user) { + this.user = user; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java index 516f0ea8e7..89631014ea 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/RevisionRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; public class RevisionRequestDto { - private String revisionId; + private String revisionId; - public String getRevisionId() { - return revisionId; - } + public String getRevisionId() { + return revisionId; + } - public void setRevisionId(String revisionId) { - this.revisionId = revisionId; - } + public void setRevisionId(String revisionId) { + this.revisionId = revisionId; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java index 76500ca326..3f4b4a94da 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/SubmitRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; public class SubmitRequestDto { - private String message; - public String getMessage() { - return message; - } + private String message; + + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java index 1dba03cedc..335eb15bf8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionAction.java @@ -17,13 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; -public enum VersionAction { - Sync, - Commit, - Revert, - Reset, - Clean -} +public enum VersionAction {Sync, Commit, Revert, Reset, Clean} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java index 98a5bb94ee..a664318cd3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionActionRequestDto.java @@ -17,36 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; public class VersionActionRequestDto { - private VersionAction action; - private CommitRequestDto commitRequest; - private RevisionRequestDto revisionRequest; + private VersionAction action; + private CommitRequestDto commitRequest; + private RevisionRequestDto revisionRequest; - public VersionAction getAction() { - return action; - } + public VersionAction getAction() { + return action; + } - public void setAction(VersionAction action) { - this.action = action; - } + public void setAction(VersionAction action) { + this.action = action; + } - public CommitRequestDto getCommitRequest() { - return commitRequest; - } + public CommitRequestDto getCommitRequest() { + return commitRequest; + } - public void setCommitRequest(CommitRequestDto commitRequest) { - this.commitRequest = commitRequest; - } + public void setCommitRequest(CommitRequestDto commitRequest) { + this.commitRequest = commitRequest; + } - public RevisionRequestDto getRevisionRequest() { - return revisionRequest; - } + public RevisionRequestDto getRevisionRequest() { + return revisionRequest; + } - public void setRevisionRequest(RevisionRequestDto revisionRequest) { - this.revisionRequest = revisionRequest; - } + public void setRevisionRequest(RevisionRequestDto revisionRequest) { + this.revisionRequest = revisionRequest; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java index 8f3ce5dcad..83884d3a1d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,98 +17,97 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; -import org.openecomp.sdc.versioning.dao.types.VersionState; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; - import java.util.Date; import java.util.Map; +import org.openecomp.sdc.versioning.dao.types.VersionState; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; public class VersionDto { - private String id; - private String name; - private String description; - private String baseId; - private VersionStatus status; - private VersionState state; - private Date creationTime; - private Date modificationTime; - private Map additionalInfo; - public VersionDto() { - - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getBaseId() { - return baseId; - } - - public void setBaseId(String baseId) { - this.baseId = baseId; - } - - public VersionStatus getStatus() { - return status; - } - - public void setStatus(VersionStatus status) { - this.status = status; - } - - public VersionState getState() { - return state; - } - - public void setState(VersionState state) { - this.state = state; - } - - public Date getCreationTime() { - return creationTime; - } - - public void setCreationTime(Date creationTime) { - this.creationTime = creationTime; - } - - public Date getModificationTime() { - return modificationTime; - } - - public void setModificationTime(Date modificationTime) { - this.modificationTime = modificationTime; - } - - public Map getAdditionalInfo() { - return additionalInfo; - } - - public void setAdditionalInfo(Map additionalInfo) { - this.additionalInfo = additionalInfo; - } + + private String id; + private String name; + private String description; + private String baseId; + private VersionStatus status; + private VersionState state; + private Date creationTime; + private Date modificationTime; + private Map additionalInfo; + + public VersionDto() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getBaseId() { + return baseId; + } + + public void setBaseId(String baseId) { + this.baseId = baseId; + } + + public VersionStatus getStatus() { + return status; + } + + public void setStatus(VersionStatus status) { + this.status = status; + } + + public VersionState getState() { + return state; + } + + public void setState(VersionState state) { + this.state = state; + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getModificationTime() { + return modificationTime; + } + + public void setModificationTime(Date modificationTime) { + this.modificationTime = modificationTime; + } + + public Map getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(Map additionalInfo) { + this.additionalInfo = additionalInfo; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java index 5c6e4848a0..81747d4612 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-types/src/main/java/org/openecomp/sdcrests/item/types/VersionRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.item.types; import org.openecomp.sdc.versioning.types.VersionCreationMethod; public class VersionRequestDto { - private String description; - private VersionCreationMethod creationMethod; - public String getDescription() { - return description; - } + private String description; + private VersionCreationMethod creationMethod; + + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public VersionCreationMethod getCreationMethod() { - return creationMethod; - } + public VersionCreationMethod getCreationMethod() { + return creationMethod; + } - public void setCreationMethod(VersionCreationMethod creationMethod) { - this.creationMethod = creationMethod; - } + public void setCreationMethod(VersionCreationMethod creationMethod) { + this.creationMethod = creationMethod; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java index 96300b5cbb..5007246ae1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-fe/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java @@ -17,27 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.listeners; - -import org.springframework.web.context.ContextLoaderListener; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; +import org.springframework.web.context.ContextLoaderListener; public class OnboardingAppStartupListener implements ServletContextListener { - ContextLoaderListener springListener; + ContextLoaderListener springListener; - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - springListener = new ContextLoaderListener(); - springListener.initWebApplicationContext(servletContextEvent.getServletContext()); - } + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + springListener = new ContextLoaderListener(); + springListener.initWebApplicationContext(servletContextEvent.getServletContext()); + } - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - springListener.closeWebApplicationContext(servletContextEvent.getServletContext()); - } + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + springListener.closeWebApplicationContext(servletContextEvent.getServletContext()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java index 41376b040f..be98d809de 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsStatusToDto.java @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.rest.mapping; import com.datastax.driver.core.utils.UUIDs; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.notification.dao.types.NotificationEntity; import org.openecomp.sdc.notification.dtos.NotificationsStatus; @@ -28,37 +31,24 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.notifications.types.NotificationEntityDto; import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +public class MapNotificationsStatusToDto extends MappingBase { -public class MapNotificationsStatusToDto - extends MappingBase { - - private static final DateFormat formatter = - DateFormat.getDateTimeInstance(DateFormat.LONG, - DateFormat.SHORT); + private static final DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); @Override public void doMapping(NotificationsStatus source, NotificationsStatusDto target) { - target.setLastScanned(source.getLastScanned()); target.setNewEntries(source.getNewEntries()); target.setEndOfPage(source.getEndOfPage()); target.setNumOfNotSeenNotifications(source.getNumOfNotSeenNotifications()); List entityDtos = new ArrayList<>(); - source.getNotifications() - .forEach(notification -> entityDtos.add(new NotificationEntityDto(notification.isRead(), - notification.getEventId(), notification.getEventType(), - JsonUtil.json2Object(notification.getEventAttributes(), Map.class), - extractDate(notification)))); + source.getNotifications().forEach(notification -> entityDtos.add( + new NotificationEntityDto(notification.isRead(), notification.getEventId(), notification.getEventType(), + JsonUtil.json2Object(notification.getEventAttributes(), Map.class), extractDate(notification)))); target.setNotifications(entityDtos); } private String extractDate(NotificationEntity notification) { - return formatter.format(UUIDs.unixTimestamp - (notification - .getEventId())); + return formatter.format(UUIDs.unixTimestamp(notification.getEventId())); } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java index 558453b7b6..a42f5f98da 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/mapping/MapNotificationsToDto.java @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.rest.mapping; import com.datastax.driver.core.utils.UUIDs; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.notification.dao.types.NotificationEntity; @@ -28,30 +31,23 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.notifications.types.NotificationEntityDto; import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; -import java.text.DateFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public class MapNotificationsToDto extends MappingBase, NotificationsStatusDto> { - private static final DateFormat formatter = - DateFormat.getDateTimeInstance(DateFormat.LONG, - DateFormat.SHORT); + + private static final DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); + @Override public void doMapping(List source, NotificationsStatusDto target) { List entityDtos = new ArrayList<>(); - if(CollectionUtils.isNotEmpty(source)) { - source.forEach(notification -> entityDtos.add(new NotificationEntityDto(notification.isRead(), - notification.getEventId(), notification.getEventType(), JsonUtil.json2Object(notification.getEventAttributes(), Map.class), - extractDate(notification)))); + if (CollectionUtils.isNotEmpty(source)) { + source.forEach(notification -> entityDtos.add( + new NotificationEntityDto(notification.isRead(), notification.getEventId(), notification.getEventType(), + JsonUtil.json2Object(notification.getEventAttributes(), Map.class), extractDate(notification)))); target.setNotifications(entityDtos); target.setLastScanned(source.get(0).getEventId()); } } private String extractDate(NotificationEntity notification) { - return formatter.format(UUIDs.unixTimestamp - (notification - .getEventId())); + return formatter.format(UUIDs.unixTimestamp(notification.getEventId())); } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java index b2e262e9ba..9a8d00c521 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/Notifications.java @@ -17,30 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.rest.services; +import static org.openecomp.sdcrests.common.RestConstants.LAST_DELIVERED_QUERY_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; -import org.openecomp.sdcrests.notifications.types.UpdateNotificationResponseStatus; -import org.springframework.validation.annotation.Validated; - +import java.lang.reflect.InvocationTargetException; +import java.util.UUID; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.lang.reflect.InvocationTargetException; -import java.util.UUID; - -import static org.openecomp.sdcrests.common.RestConstants.*; +import org.openecomp.sdcrests.notifications.types.NotificationsStatusDto; +import org.openecomp.sdcrests.notifications.types.UpdateNotificationResponseStatus; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/notifications") @Produces(MediaType.APPLICATION_JSON) @@ -48,38 +54,32 @@ import static org.openecomp.sdcrests.common.RestConstants.*; @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Notifications")}) @Validated public interface Notifications { - String LIMIT_QUERY_PARAM = "NOTIFICATION_ROWS_LIMIT"; - String END_OF_PAGE_QUERY_PARAM = "END_OF_PAGE_EVENT_ID"; - @GET - @Operation(description = "Retrieve all user notifications", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = NotificationsStatusDto.class))))) - Response getNotifications( - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user, - @QueryParam(LAST_DELIVERED_QUERY_PARAM) UUID lastDelvered, - @QueryParam(END_OF_PAGE_QUERY_PARAM) UUID endOfPage); + String LIMIT_QUERY_PARAM = "NOTIFICATION_ROWS_LIMIT"; + String END_OF_PAGE_QUERY_PARAM = "END_OF_PAGE_EVENT_ID"; - @PUT - @Path("/{notificationId}") - @Operation(description = "Mark notification as read", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UpdateNotificationResponseStatus.class)))) - Response markAsRead( - @Parameter(description = "Notification Id") @PathParam("notificationId") String notificationId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws InvocationTargetException, IllegalAccessException; + @GET + @Operation(description = "Retrieve all user notifications", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NotificationsStatusDto.class))))) + Response getNotifications(@NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user, + @QueryParam(LAST_DELIVERED_QUERY_PARAM) UUID lastDelvered, @QueryParam(END_OF_PAGE_QUERY_PARAM) UUID endOfPage); - @PUT - @Path("/last-seen/{notificationId}") - @Operation(description = "Update Last Seen Notification", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UpdateNotificationResponseStatus.class)))) - Response updateLastSeenNotification( - @Parameter(description = "Notification Id") @PathParam("notificationId") String notificationId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws InvocationTargetException, IllegalAccessException; + @PUT + @Path("/{notificationId}") + @Operation(description = "Mark notification as read", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UpdateNotificationResponseStatus.class)))) + Response markAsRead(@Parameter(description = "Notification Id") @PathParam("notificationId") String notificationId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) + throws InvocationTargetException, IllegalAccessException; - @GET - @Path("/worker") - @Operation(description = "Retrive user not delivered notifications",responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = NotificationsStatusDto.class))))) - Response getNewNotificationsByOwnerId( - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user, - @QueryParam(LAST_DELIVERED_QUERY_PARAM) String eventId, - @QueryParam(LIMIT_QUERY_PARAM) String limit); + @PUT + @Path("/last-seen/{notificationId}") + @Operation(description = "Update Last Seen Notification", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UpdateNotificationResponseStatus.class)))) + Response updateLastSeenNotification(@Parameter(description = "Notification Id") @PathParam("notificationId") String notificationId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) + throws InvocationTargetException, IllegalAccessException; + @GET + @Path("/worker") + @Operation(description = "Retrive user not delivered notifications", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NotificationsStatusDto.class))))) + Response getNewNotificationsByOwnerId(@NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user, + @QueryParam(LAST_DELIVERED_QUERY_PARAM) String eventId, @QueryParam(LIMIT_QUERY_PARAM) String limit); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/impl/NotificationsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/impl/NotificationsImpl.java index bc33784bc8..4463717910 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/impl/NotificationsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-services/src/main/java/org/openecomp/sdcrests/notifications/rest/services/impl/NotificationsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.rest.services.impl; +import java.lang.reflect.InvocationTargetException; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -38,13 +43,6 @@ import org.openecomp.sdcrests.notifications.types.UpdateNotificationResponseStat import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.lang.reflect.InvocationTargetException; -import java.util.List; -import java.util.Objects; -import java.util.UUID; - /** * @author Avrahamg * @since June 22, 2017 @@ -54,54 +52,41 @@ import java.util.UUID; @Scope(value = "prototype") public class NotificationsImpl implements Notifications { - private static int selectionLimit = 10; - - private static final Logger LOGGER = LoggerFactory.getLogger(NotificationsImpl.class); - private NotificationsService notificationsService = NotificationsServiceFactory.getInstance().createInterface(); + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationsImpl.class); + private static int selectionLimit = 10; + private NotificationsService notificationsService = NotificationsServiceFactory.getInstance().createInterface(); @Override public Response getNotifications(String user, UUID lastDelivered, UUID endOfPage) { - NotificationsStatus notificationsStatus = notificationsService - .getNotificationsStatus(user, lastDelivered, selectionLimit, endOfPage); + NotificationsStatus notificationsStatus = notificationsService.getNotificationsStatus(user, lastDelivered, selectionLimit, endOfPage); MapNotificationsStatusToDto converter = new MapNotificationsStatusToDto(); NotificationsStatusDto notificationsStatusDto = new NotificationsStatusDto(); converter.doMapping(notificationsStatus, notificationsStatusDto); - return Response.ok(notificationsStatusDto).build(); } @Override - public Response updateLastSeenNotification(String notificationId, String user) - throws InvocationTargetException, IllegalAccessException { - UpdateNotificationResponseStatus - updateNotificationResponseStatus = new UpdateNotificationResponseStatus(); + public Response updateLastSeenNotification(String notificationId, String user) throws InvocationTargetException, IllegalAccessException { + UpdateNotificationResponseStatus updateNotificationResponseStatus = new UpdateNotificationResponseStatus(); try { notificationsService.updateLastSeenNotification(user, UUID.fromString(notificationId)); } catch (Exception ex) { - LOGGER.error( - String.format(Messages.FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION.getErrorMessage(), - user), ex); + LOGGER.error(String.format(Messages.FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION.getErrorMessage(), user), ex); updateNotificationResponseStatus.addStructureError(notificationId, - new ErrorMessage(ErrorLevel.ERROR, - Messages.FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION.getErrorMessage())); + new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION.getErrorMessage())); } return Response.ok(updateNotificationResponseStatus).build(); } @Override - public Response markAsRead(String notificationId, String user) - throws InvocationTargetException, IllegalAccessException { - - UpdateNotificationResponseStatus - updateNotificationResponseStatus = new UpdateNotificationResponseStatus(); + public Response markAsRead(String notificationId, String user) throws InvocationTargetException, IllegalAccessException { + UpdateNotificationResponseStatus updateNotificationResponseStatus = new UpdateNotificationResponseStatus(); try { notificationsService.markAsRead(user, notificationId); } catch (NotificationNotExistException ex) { LOGGER.error(Messages.FAILED_TO_MARK_NOTIFICATION_AS_READ.getErrorMessage(), ex); - updateNotificationResponseStatus.addStructureError( - notificationId, new ErrorMessage(ErrorLevel.ERROR, Messages - .FAILED_TO_MARK_NOTIFICATION_AS_READ - .getErrorMessage())); + updateNotificationResponseStatus.addStructureError(notificationId, + new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_MARK_NOTIFICATION_AS_READ.getErrorMessage())); } return Response.ok(updateNotificationResponseStatus).build(); } @@ -109,24 +94,18 @@ public class NotificationsImpl implements Notifications { @Override public Response getNewNotificationsByOwnerId(String user, String eventId, String limitStr) { int limit = selectionLimit; - if (Objects.nonNull(limitStr)) { try { limit = Integer.parseInt(limitStr); - } - catch (NumberFormatException f) { + } catch (NumberFormatException f) { LOGGER.error("Non numeric selection list size value specified: " + limitStr); } } - - List notifications = Objects.isNull(eventId) - ? notificationsService.getNotificationsByOwnerId(user, limit) + List notifications = Objects.isNull(eventId) ? notificationsService.getNotificationsByOwnerId(user, limit) : notificationsService.getNewNotificationsByOwnerId(user, UUID.fromString(eventId), limit); - MapNotificationsToDto converter = new MapNotificationsToDto(); NotificationsStatusDto notificationsStatusDto = new NotificationsStatusDto(); converter.doMapping(notifications, notificationsStatusDto); - return Response.ok(notificationsStatusDto).build(); } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java index d41deb3a4d..f76c9566ec 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationEntityDto.java @@ -17,75 +17,74 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.types; import java.util.Map; import java.util.UUID; public class NotificationEntityDto { - private boolean read; - private UUID eventId; - private String dateTime; - private String eventType; - private Map eventAttributes; - - public NotificationEntityDto() { - } - public NotificationEntityDto(boolean read, UUID eventId, String eventType, - Map eventAttributes) { - this.read = read; - this.eventId = eventId; - this.eventType = eventType; - this.eventAttributes = eventAttributes; - } - - public NotificationEntityDto(boolean read, UUID eventId,String eventType, - Map eventAttributes, String dateTime) { - this.read = read; - this.eventId = eventId; - this.dateTime = dateTime; - this.eventType = eventType; - this.eventAttributes = eventAttributes; - } - - public boolean isRead() { - return read; - } - - public void setRead(boolean read) { - this.read = read; - } - - public UUID getEventId() { - return eventId; - } - - public void setEventId(UUID eventId) { - this.eventId = eventId; - } - - public String getEventType() { - return eventType; - } - - public void setEventType(String eventType) { - this.eventType = eventType; - } - - public Map getEventAttributes() { - return eventAttributes; - } - - public void setEventAttributes(Map eventAttributes) { - this.eventAttributes = eventAttributes; - } - - public String getDateTime() { - return dateTime; - } - - public void setDateTime(String dateTime) { - this.dateTime = dateTime; - } + + private boolean read; + private UUID eventId; + private String dateTime; + private String eventType; + private Map eventAttributes; + + public NotificationEntityDto() { + } + + public NotificationEntityDto(boolean read, UUID eventId, String eventType, Map eventAttributes) { + this.read = read; + this.eventId = eventId; + this.eventType = eventType; + this.eventAttributes = eventAttributes; + } + + public NotificationEntityDto(boolean read, UUID eventId, String eventType, Map eventAttributes, String dateTime) { + this.read = read; + this.eventId = eventId; + this.dateTime = dateTime; + this.eventType = eventType; + this.eventAttributes = eventAttributes; + } + + public boolean isRead() { + return read; + } + + public void setRead(boolean read) { + this.read = read; + } + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Map getEventAttributes() { + return eventAttributes; + } + + public void setEventAttributes(Map eventAttributes) { + this.eventAttributes = eventAttributes; + } + + public String getDateTime() { + return dateTime; + } + + public void setDateTime(String dateTime) { + this.dateTime = dateTime; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java index a0273d51e0..fb4ed722b5 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationResponseStatus.java @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.types; -public enum NotificationResponseStatus { - Success, - Failure -} +public enum NotificationResponseStatus {Success, Failure} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java index 7067fab509..bda548ae8f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/NotificationsStatusDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.types; import java.util.ArrayList; @@ -29,6 +28,7 @@ import java.util.UUID; * @since June 29, 2017 */ public class NotificationsStatusDto { + private List notifications; private List newEntries = new ArrayList<>(); private UUID lastScanned; @@ -42,8 +42,7 @@ public class NotificationsStatusDto { return notifications; } - public void setNotifications( - List notifications) { + public void setNotifications(List notifications) { this.notifications = notifications; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java index 9e985726dc..2a81555f9b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/notifications-rest/notifications-rest-types/src/main/java/org/openecomp/sdcrests/notifications/types/UpdateNotificationResponseStatus.java @@ -17,24 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.notifications.types; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; +import static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Failure; +import static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Success; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Failure; -import static org.openecomp.sdcrests.notifications.types.NotificationResponseStatus.Success; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; /** * Created by TALIO on 4/27/2016. */ public class UpdateNotificationResponseStatus { + private Map> errors = new HashMap<>(); private NotificationResponseStatus status = Success; @@ -55,8 +54,7 @@ public class UpdateNotificationResponseStatus { } public void addStructureError(String notificationId, ErrorMessage errorMessage) { - List errorList = - errors.computeIfAbsent(notificationId, k -> new ArrayList<>()); + List errorList = errors.computeIfAbsent(notificationId, k -> new ArrayList<>()); errorList.add(errorMessage); if (ErrorLevel.ERROR.equals(errorMessage.getLevel())) { status = Failure; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/configuration/CookieConfig.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/configuration/CookieConfig.java index c299805d0c..aeea6de894 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/configuration/CookieConfig.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/configuration/CookieConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.configuration; import java.util.List; @@ -25,8 +24,8 @@ import java.util.List; public class CookieConfig { String securityKey = ""; - long maxSessionTimeOut = 600L*1000L; - long sessionIdleTimeOut = 30L*1000L; + long maxSessionTimeOut = 600L * 1000L; + long sessionIdleTimeOut = 30L * 1000L; String cookieName = "AuthenticationCookie"; String redirectURL = "portal_url"; List excludedUrls; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthenticationFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthenticationFilter.java index 272e1e0e86..89d5346907 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthenticationFilter.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthenticationFilter.java @@ -12,98 +12,92 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.server.filters; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.Principal; import java.util.Base64; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; public class ActionAuthenticationFilter implements Filter { - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - private boolean runningOnLocal = true; - - @Override - public void destroy() { - // TODO Auto-generated method stub + private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); + private boolean runningOnLocal = true; - } - - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) - throws IOException, ServletException { - if (runningOnLocal) { - - HttpServletRequest httpRequest = (HttpServletRequest) arg0; - String authorizationHeader = httpRequest.getHeader("Authorization"); - if (authorizationHeader != null && !authorizationHeader.isEmpty()) { - String username; - try { - String base64Credentials = - httpRequest.getHeader("Authorization").replace("Basic", "").trim(); - String decodedCredentials = new String(Base64.getDecoder().decode(base64Credentials)); - username = decodedCredentials.substring(0, decodedCredentials.indexOf(":")); - } catch (Exception exception) { - log.error("Failed to decode credentials", exception); - setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_FORBIDDEN); - return; - } - if (username.startsWith("AUTH")) { - HttpServletRequestWrapper servletRequest = new HttpServletRequestWrapper(httpRequest) { - @Override - public java.lang.String getRemoteUser() { - return getUserPrincipal().getName(); - } - - @Override - public Principal getUserPrincipal() { - return () -> username.substring(0, username.indexOf("-")); - } + @Override + public void destroy() { + // TODO Auto-generated method stub + } - @Override - public boolean isUserInRole(String role) { - try { - ActionLibraryPrivilege requiredPrivilege = - ActionLibraryPrivilege.getPrivilege(httpRequest.getMethod()); - ActionLibraryPrivilege userPrivilege = ActionLibraryPrivilege - .valueOf(username.substring(username.indexOf("-") + 1).toUpperCase()); - return userPrivilege.ordinal() >= requiredPrivilege.ordinal(); - } catch (Exception exception) { - log.error("Failed to validate UserInRole", exception); - return false; - } + @Override + public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { + if (runningOnLocal) { + HttpServletRequest httpRequest = (HttpServletRequest) arg0; + String authorizationHeader = httpRequest.getHeader("Authorization"); + if (authorizationHeader != null && !authorizationHeader.isEmpty()) { + String username; + try { + String base64Credentials = httpRequest.getHeader("Authorization").replace("Basic", "").trim(); + String decodedCredentials = new String(Base64.getDecoder().decode(base64Credentials)); + username = decodedCredentials.substring(0, decodedCredentials.indexOf(":")); + } catch (Exception exception) { + log.error("Failed to decode credentials", exception); + setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_FORBIDDEN); + return; + } + if (username.startsWith("AUTH")) { + HttpServletRequestWrapper servletRequest = new HttpServletRequestWrapper(httpRequest) { + @Override + public java.lang.String getRemoteUser() { + return getUserPrincipal().getName(); + } + + @Override + public Principal getUserPrincipal() { + return () -> username.substring(0, username.indexOf("-")); + } + + @Override + public boolean isUserInRole(String role) { + try { + ActionLibraryPrivilege requiredPrivilege = ActionLibraryPrivilege.getPrivilege(httpRequest.getMethod()); + ActionLibraryPrivilege userPrivilege = ActionLibraryPrivilege + .valueOf(username.substring(username.indexOf("-") + 1).toUpperCase()); + return userPrivilege.ordinal() >= requiredPrivilege.ordinal(); + } catch (Exception exception) { + log.error("Failed to validate UserInRole", exception); + return false; + } + } + }; + arg2.doFilter(servletRequest, arg1); + } else { + setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_FORBIDDEN); + } + } else { + setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_UNAUTHORIZED); } - }; - arg2.doFilter(servletRequest, arg1); } else { - setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_FORBIDDEN); + //call super doFilter of cadi authentication filter } - } else { - setResponseStatus((HttpServletResponse) arg1, HttpServletResponse.SC_UNAUTHORIZED); - } - } else { - //call super doFilter of cadi authentication filter } + private void setResponseStatus(HttpServletResponse response, int status) { + response.setStatus(status); + } - } - - private void setResponseStatus(HttpServletResponse response, int status) { - response.setStatus(status); - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - - } - + @Override + public void init(FilterConfig arg0) throws ServletException { + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthorizationFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthorizationFilter.java index 10fd7d23f5..c394c3cf46 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthorizationFilter.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionAuthorizationFilter.java @@ -13,43 +13,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.server.filters; -import javax.servlet.*; +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; public class ActionAuthorizationFilter implements Filter { - - @Override - public void destroy() { - //destroy() is not implemented for ActionAuthorizationFilter - - } - - @Override - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, - FilterChain filterChain) - throws IOException, ServletException { - - HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; - if (httpRequest.isUserInRole(httpRequest.getMethod().toUpperCase())) { - filterChain.doFilter(servletRequest, servletResponse); - } else { - setResponseStatus((HttpServletResponse) servletResponse, HttpServletResponse.SC_FORBIDDEN); + @Override + public void destroy() { + //destroy() is not implemented for ActionAuthorizationFilter } - } - private void setResponseStatus(HttpServletResponse response, int status) { - response.setStatus(status); - } + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; + if (httpRequest.isUserInRole(httpRequest.getMethod().toUpperCase())) { + filterChain.doFilter(servletRequest, servletResponse); + } else { + setResponseStatus((HttpServletResponse) servletResponse, HttpServletResponse.SC_FORBIDDEN); + } + } - @Override - public void init(FilterConfig arg0) throws ServletException { - //init() is not implemented for ActionAuthorizationFilter - } + private void setResponseStatus(HttpServletResponse response, int status) { + response.setStatus(status); + } + @Override + public void init(FilterConfig arg0) throws ServletException { + //init() is not implemented for ActionAuthorizationFilter + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionLibraryPrivilege.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionLibraryPrivilege.java index 6c8b1e8ca5..bd0f219f22 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionLibraryPrivilege.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/ActionLibraryPrivilege.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,59 +17,54 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.filters; /** * The enum Action library privilege. */ public enum ActionLibraryPrivilege { + /** + * Retrieve action library privilege. + */ + RETRIEVE, + /** + * Create action library privilege. + */ + CREATE, + /** + * Update action library privilege. + */ + UPDATE, + /** + * Delete action library privilege. + */ + DELETE; - /** - * Retrieve action library privilege. - */ - RETRIEVE, /** - * Create action library privilege. - */ - CREATE, /** - * Update action library privilege. - */ - UPDATE, /** - * Delete action library privilege. - */ - DELETE; - - /** - * Gets privilege. - * - * @param operation the operation - * @return the privilege - */ - public static ActionLibraryPrivilege getPrivilege(String operation) { - - ActionLibraryPrivilege toReturn; - - switch (operation) { - - case "GET": - toReturn = RETRIEVE; - break; - case "POST": - toReturn = CREATE; - break; - case "PUT": - toReturn = UPDATE; - break; - case "DELETE": - toReturn = DELETE; - break; - default: - toReturn = null; - break; - + /** + * Gets privilege. + * + * @param operation the operation + * @return the privilege + */ + public static ActionLibraryPrivilege getPrivilege(String operation) { + ActionLibraryPrivilege toReturn; + switch (operation) { + case "GET": + toReturn = RETRIEVE; + break; + case "POST": + toReturn = CREATE; + break; + case "PUT": + toReturn = UPDATE; + break; + case "DELETE": + toReturn = DELETE; + break; + default: + toReturn = null; + break; + } + return toReturn; } - - return toReturn; - - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/BasicAuthenticationFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/BasicAuthenticationFilter.java index 0cda5f8a27..2c2b36717a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/BasicAuthenticationFilter.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/BasicAuthenticationFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.filters; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.FileInputStream; +import java.io.IOException; import java.io.InputStream; import java.util.Arrays; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Objects; @@ -33,101 +34,89 @@ import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.be.config.Configuration.BasicAuthConfig; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Base64; import org.openecomp.sdcrests.item.rest.services.catalog.notification.EntryNotConfiguredException; public class BasicAuthenticationFilter implements Filter { - private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class); - private static final String CONFIG_FILE_PROPERTY = "configuration.yaml"; - private static final String CONFIG_SECTION = "basicAuth"; - - @Override - public void destroy() { - // TODO Auto-generated method stub - - } - - @Override - public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) - throws IOException, ServletException { - String file = Objects.requireNonNull(System.getProperty(CONFIG_FILE_PROPERTY), - "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); - Object config = getAuthenticationConfiguration(file); - ObjectMapper mapper = new ObjectMapper(); - BasicAuthConfig basicAuthConfig = mapper.convertValue(config, BasicAuthConfig.class); - HttpServletRequest httpRequest = (HttpServletRequest) arg0; - HttpServletRequestWrapper servletRequest = new HttpServletRequestWrapper(httpRequest); - - // BasicAuth is disabled - if (!basicAuthConfig.isEnabled()) { - arg2.doFilter(servletRequest, arg1); - return; - } - - List excludedUrls = Arrays.asList(basicAuthConfig.getExcludedUrls().split(",")); - if (excludedUrls.contains(httpRequest.getServletPath() + httpRequest.getPathInfo())) { - // this url is included in the excludeUrls list, no need for authentication - arg2.doFilter(servletRequest, arg1); - return; - } - - - // Get the basicAuth info from the header - String authorizationHeader = httpRequest.getHeader("Authorization"); - if (authorizationHeader == null || authorizationHeader.isEmpty()) { - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - return; - } - - String base64Credentials = - httpRequest.getHeader("Authorization").replace("Basic", "").trim(); - if (verifyCredentials(basicAuthConfig, base64Credentials)) { - arg2.doFilter(servletRequest, arg1); - } else { - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } + private static final Logger log = LoggerFactory.getLogger(BasicAuthenticationFilter.class); + private static final String CONFIG_FILE_PROPERTY = "configuration.yaml"; + private static final String CONFIG_SECTION = "basicAuth"; + + private static Object getAuthenticationConfiguration(String file) throws IOException { + InputStream fileInput = new FileInputStream(file); + YamlUtil yamlUtil = new YamlUtil(); + Map configuration = Objects.requireNonNull(yamlUtil.yamlToMap(fileInput), "Configuration cannot be empty"); + Object authenticationConfig = configuration.get(CONFIG_SECTION); + if (authenticationConfig == null) { + throw new EntryNotConfiguredException(CONFIG_SECTION + " section"); + } + return authenticationConfig; + } - @Override - public void init(FilterConfig config) throws ServletException { - } + @Override + public void destroy() { + // TODO Auto-generated method stub + } - private static Object getAuthenticationConfiguration(String file) throws IOException { - InputStream fileInput = new FileInputStream(file); - YamlUtil yamlUtil = new YamlUtil(); + @Override + public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { + String file = Objects.requireNonNull(System.getProperty(CONFIG_FILE_PROPERTY), + "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); + Object config = getAuthenticationConfiguration(file); + ObjectMapper mapper = new ObjectMapper(); + BasicAuthConfig basicAuthConfig = mapper.convertValue(config, BasicAuthConfig.class); + HttpServletRequest httpRequest = (HttpServletRequest) arg0; + HttpServletRequestWrapper servletRequest = new HttpServletRequestWrapper(httpRequest); + // BasicAuth is disabled + if (!basicAuthConfig.isEnabled()) { + arg2.doFilter(servletRequest, arg1); + return; + } + List excludedUrls = Arrays.asList(basicAuthConfig.getExcludedUrls().split(",")); + if (excludedUrls.contains(httpRequest.getServletPath() + httpRequest.getPathInfo())) { + // this url is included in the excludeUrls list, no need for authentication + arg2.doFilter(servletRequest, arg1); + return; + } + // Get the basicAuth info from the header + String authorizationHeader = httpRequest.getHeader("Authorization"); + if (authorizationHeader == null || authorizationHeader.isEmpty()) { + ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return; + } + String base64Credentials = httpRequest.getHeader("Authorization").replace("Basic", "").trim(); + if (verifyCredentials(basicAuthConfig, base64Credentials)) { + arg2.doFilter(servletRequest, arg1); + } else { + ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } - Map configuration = Objects.requireNonNull(yamlUtil.yamlToMap(fileInput), "Configuration cannot be empty"); - Object authenticationConfig = configuration.get(CONFIG_SECTION); - if (authenticationConfig == null) { - throw new EntryNotConfiguredException(CONFIG_SECTION + " section"); + @Override + public void init(FilterConfig config) throws ServletException { } - return authenticationConfig; - } - private boolean verifyCredentials (BasicAuthConfig basicAuthConfig, String credential) { - String decodedCredentials = new String(Base64.getDecoder().decode(credential)); - int p = decodedCredentials.indexOf(':'); - if (p != -1) { - String userName = decodedCredentials.substring(0, p).trim(); - String password = decodedCredentials.substring(p + 1).trim(); - if (!userName.equals(basicAuthConfig.getUserName()) || !password.equals(basicAuthConfig.getUserPass())) { - log.error("Authentication failed. Invalid user name or password"); - return false; - } - return true; - } else { - log.error("Failed to decode credentials"); - return false; + private boolean verifyCredentials(BasicAuthConfig basicAuthConfig, String credential) { + String decodedCredentials = new String(Base64.getDecoder().decode(credential)); + int p = decodedCredentials.indexOf(':'); + if (p != -1) { + String userName = decodedCredentials.substring(0, p).trim(); + String password = decodedCredentials.substring(p + 1).trim(); + if (!userName.equals(basicAuthConfig.getUserName()) || !password.equals(basicAuthConfig.getUserPass())) { + log.error("Authentication failed. Invalid user name or password"); + return false; + } + return true; + } else { + log.error("Failed to decode credentials"); + return false; + } } - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/OnboardingSessionContextFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/OnboardingSessionContextFilter.java index 5465677b5a..d8c8eb6cc4 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/OnboardingSessionContextFilter.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/OnboardingSessionContextFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.filters; -import org.openecomp.sdcrests.filters.SessionContextFilter; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import org.openecomp.sdcrests.filters.SessionContextFilter; public class OnboardingSessionContextFilter extends SessionContextFilter { - @Override - public String getUser(ServletRequest servletRequest) { - return ((HttpServletRequest) servletRequest).getHeader(USER_ID_HEADER_PARAM); - } + @Override + public String getUser(ServletRequest servletRequest) { + return ((HttpServletRequest) servletRequest).getHeader(USER_ID_HEADER_PARAM); + } - @Override - public String getTenant(ServletRequest servletRequest) { - return "dox"; - } + @Override + public String getTenant(ServletRequest servletRequest) { + return "dox"; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/RestrictionAccessFilter.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/RestrictionAccessFilter.java index 61a74500ca..19b5e52cf8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/RestrictionAccessFilter.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/filters/RestrictionAccessFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.filters; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; -import org.openecomp.sdc.securityutil.filters.SessionValidationFilter; -import org.openecomp.server.configuration.CookieConfig; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdcrests.item.rest.services.catalog.notification.EntryNotConfiguredException; - -import javax.servlet.http.Cookie; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.Objects; +import javax.servlet.http.Cookie; +import org.onap.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; +import org.openecomp.sdc.securityutil.filters.SessionValidationFilter; +import org.openecomp.sdcrests.item.rest.services.catalog.notification.EntryNotConfiguredException; +import org.openecomp.server.configuration.CookieConfig; public class RestrictionAccessFilter extends SessionValidationFilter { @@ -43,7 +41,23 @@ public class RestrictionAccessFilter extends SessionValidationFilter { private static final String CONFIG_FILE_PROPERTY = "configuration.yaml"; private static final String CONFIG_SECTION = "authCookie"; + @Override + public ISessionValidationFilterConfiguration getFilterConfiguration() { + return Configuration.getInstance(); + } + + @Override + protected Cookie addRoleToCookie(Cookie cookie) { + return cookie; + } + + @Override + protected boolean isRoleValid(Cookie cookie) { + return true; + } + private static class Configuration implements ISessionValidationFilterConfiguration { + private static Configuration instance; private String securityKey; private long maxSessionTimeOut; @@ -55,13 +69,10 @@ public class RestrictionAccessFilter extends SessionValidationFilter { private String cookiePath; private boolean isCookieHttpOnly; - private Configuration() { try { - String file = Objects.requireNonNull(System.getProperty(CONFIG_FILE_PROPERTY), - "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); - + "Config file location must be specified via system property " + CONFIG_FILE_PROPERTY); Object config = getAuthenticationConfiguration(file); ObjectMapper mapper = new ObjectMapper(); CookieConfig cookieConfig = mapper.convertValue(config, CookieConfig.class); @@ -74,11 +85,9 @@ public class RestrictionAccessFilter extends SessionValidationFilter { this.cookieDomain = cookieConfig.getDomain(); this.cookiePath = cookieConfig.getPath(); this.isCookieHttpOnly = cookieConfig.isHttpOnly(); - } catch (Exception e) { LOGGER.warn("Failed to load configuration. ", e); } - } public static Configuration getInstance() { @@ -89,18 +98,15 @@ public class RestrictionAccessFilter extends SessionValidationFilter { } private static Object getAuthenticationConfiguration(String file) throws IOException { - Map configuration = Objects.requireNonNull(readConfigurationFile(file), "Configuration cannot be empty"); Object authenticationConfig = configuration.get(CONFIG_SECTION); if (authenticationConfig == null) { throw new EntryNotConfiguredException(CONFIG_SECTION + " section"); } - return authenticationConfig; } private static Map readConfigurationFile(String file) throws IOException { - try (InputStream fileInput = new FileInputStream(file)) { YamlUtil yamlUtil = new YamlUtil(); return yamlUtil.yamlToMap(fileInput); @@ -152,19 +158,4 @@ public class RestrictionAccessFilter extends SessionValidationFilter { return excludedUrls; } } - - @Override - public ISessionValidationFilterConfiguration getFilterConfiguration() { - return Configuration.getInstance(); - } - - @Override - protected Cookie addRoleToCookie(Cookie cookie) { - return cookie; - } - - @Override - protected boolean isRoleValid(Cookie cookie) { - return true; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/DefaultOutput.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/DefaultOutput.java index 16110816b2..076582f5d5 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/DefaultOutput.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/DefaultOutput.java @@ -15,159 +15,165 @@ */ package org.openecomp.server.interceptors; - -import javax.ws.rs.core.*; import java.lang.annotation.Annotation; import java.net.URI; -import java.util.*; +import java.util.Collections; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.core.EntityTag; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Link; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.NewCookie; +import javax.ws.rs.core.Response; public class DefaultOutput extends Response { - private static final long serialVersionUID = 8061802931931401706L; - - private final int status; - private final Object entity; - private MultivaluedMap metadata; - - public DefaultOutput(int s0, Object e0) { - this.status = s0; - this.entity = e0; - } - - @Override - public Object getEntity() { - return entity; - } - - @Override - public T readEntity(Class asClass) { - return null; - } - - @Override - public T readEntity(GenericType genericType) { - return null; - } - - @Override - public T readEntity(Class asClass, Annotation[] annotations) { - return null; - } - - @Override - public T readEntity(GenericType var1, Annotation[] var2) { - return null; - } - - @Override - public boolean hasEntity() { - return false; - } - - @Override - public boolean bufferEntity() { - return false; - } - - @Override - public void close() { - //close() is not implemented for DefaultOutput - } - - @Override - public MediaType getMediaType() { - return null; - } - - @Override - public Locale getLanguage() { - return null; - } - - @Override - public int getLength() { - return 0; - } - - @Override - public Set getAllowedMethods() { - return Collections.emptySet(); - } - - @Override - public Map getCookies() { - return null; - } - - @Override - public EntityTag getEntityTag() { - return null; - } - - @Override - public Date getDate() { - return null; - } - - @Override - public Date getLastModified() { - return null; - } - - @Override - public URI getLocation() { - return null; - } - - @Override - public Set getLinks() { - return Collections.emptySet(); - } - - @Override - public boolean hasLink(String s0) { - return false; - } - - - @Override - public Link getLink(String s0) { - return null; - } - - @Override - public Link.Builder getLinkBuilder(String s0) { - return null; - } - - @Override - public int getStatus() { - return status; - } - - @Override - public StatusType getStatusInfo() { - return null; - } - - void addMetadata(MultivaluedMap meta) { - this.metadata = meta; - } - - @Override - public MultivaluedMap getMetadata() { - // don't worry about cloning for now - return metadata; - } - - @Override - public MultivaluedMap getStringHeaders() { - return null; - } - - @Override - public String getHeaderString(String s0) { - return null; - } - + private static final long serialVersionUID = 8061802931931401706L; + private final int status; + private final Object entity; + private MultivaluedMap metadata; + + public DefaultOutput(int s0, Object e0) { + this.status = s0; + this.entity = e0; + } + + @Override + public Object getEntity() { + return entity; + } + + @Override + public T readEntity(Class asClass) { + return null; + } + + @Override + public T readEntity(GenericType genericType) { + return null; + } + + @Override + public T readEntity(Class asClass, Annotation[] annotations) { + return null; + } + + @Override + public T readEntity(GenericType var1, Annotation[] var2) { + return null; + } + + @Override + public boolean hasEntity() { + return false; + } + + @Override + public boolean bufferEntity() { + return false; + } + + @Override + public void close() { + //close() is not implemented for DefaultOutput + } + + @Override + public MediaType getMediaType() { + return null; + } + + @Override + public Locale getLanguage() { + return null; + } + + @Override + public int getLength() { + return 0; + } + + @Override + public Set getAllowedMethods() { + return Collections.emptySet(); + } + + @Override + public Map getCookies() { + return null; + } + + @Override + public EntityTag getEntityTag() { + return null; + } + + @Override + public Date getDate() { + return null; + } + + @Override + public Date getLastModified() { + return null; + } + + @Override + public URI getLocation() { + return null; + } + + @Override + public Set getLinks() { + return Collections.emptySet(); + } + + @Override + public boolean hasLink(String s0) { + return false; + } + + @Override + public Link getLink(String s0) { + return null; + } + + @Override + public Link.Builder getLinkBuilder(String s0) { + return null; + } + + @Override + public int getStatus() { + return status; + } + + @Override + public StatusType getStatusInfo() { + return null; + } + + void addMetadata(MultivaluedMap meta) { + this.metadata = meta; + } + + @Override + public MultivaluedMap getMetadata() { + // don't worry about cloning for now + return metadata; + } + + @Override + public MultivaluedMap getStringHeaders() { + return null; + } + + @Override + public String getHeaderString(String s0) { + return null; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/EmptyOutputOutInterceptor.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/EmptyOutputOutInterceptor.java index 440354318d..b8548806fe 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/EmptyOutputOutInterceptor.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/EmptyOutputOutInterceptor.java @@ -15,48 +15,44 @@ */ package org.openecomp.server.interceptors; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageContentsList; import org.apache.cxf.phase.Phase; -import javax.inject.Named; -import javax.ws.rs.core.Response; - - /** * The type Empty output out interceptor. */ @Named public class EmptyOutputOutInterceptor extends AbstractOutDatabindingInterceptor { - public EmptyOutputOutInterceptor() { - // To be executed in post logical phase before marshal phase - super(Phase.POST_LOGICAL); - } + public EmptyOutputOutInterceptor() { + // To be executed in post logical phase before marshal phase + super(Phase.POST_LOGICAL); + } - /** - * Intercepts a message. - * Interceptors should NOT invoke handleMessage or handleFault - * on the next interceptor - the interceptor chain will - * take care of this. - * - * @param message input message. - */ - @Override - public void handleMessage(Message message) { - //get the message - MessageContentsList objs = MessageContentsList.getContentsList(message); - if (objs.get(0) instanceof Response) { - //check if response is present but entity inside it is null the set a default entity - int status = ((Response) objs.get(0)).getStatus(); - Object entity = ((Response) objs.get(0)).getEntity(); - // in case of staus 200 and entity is null send InternalEmptyObject in output. - if (entity == null && status == 200) { - DefaultOutput defaultOutput = new DefaultOutput(status, new InternalEmptyObject()); - defaultOutput.addMetadata(((Response) objs.get(0)).getMetadata()); - objs.set(0, defaultOutput); - } + /** + * Intercepts a message. Interceptors should NOT invoke handleMessage or handleFault on the next interceptor - the interceptor chain will take + * care of this. + * + * @param message input message. + */ + @Override + public void handleMessage(Message message) { + //get the message + MessageContentsList objs = MessageContentsList.getContentsList(message); + if (objs.get(0) instanceof Response) { + //check if response is present but entity inside it is null the set a default entity + int status = ((Response) objs.get(0)).getStatus(); + Object entity = ((Response) objs.get(0)).getEntity(); + // in case of staus 200 and entity is null send InternalEmptyObject in output. + if (entity == null && status == 200) { + DefaultOutput defaultOutput = new DefaultOutput(status, new InternalEmptyObject()); + defaultOutput.addMetadata(((Response) objs.get(0)).getMetadata()); + objs.set(0, defaultOutput); + } + } } - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/InternalEmptyObject.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/InternalEmptyObject.java index b052c57d10..e65be6d38f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/InternalEmptyObject.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/interceptors/InternalEmptyObject.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.interceptors; import com.fasterxml.jackson.annotation.JsonAutoDetect; - import java.io.Serializable; /** diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java index b1c818cabb..606a0f7f7c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/onboarding-rest-war/src/main/java/org/openecomp/server/listeners/OnboardingAppStartupListener.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,30 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.server.listeners; - -import org.openecomp.sdc.common.session.SessionContextProviderFactory; -import org.springframework.web.context.ContextLoaderListener; - import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.springframework.web.context.ContextLoaderListener; public class OnboardingAppStartupListener implements ServletContextListener { - ContextLoaderListener springListener; + ContextLoaderListener springListener; - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - SessionContextProviderFactory.getInstance().createInterface().create("onboarding", - "dox"); - springListener = new ContextLoaderListener(); - springListener.initWebApplicationContext(servletContextEvent.getServletContext()); - } + @Override + public void contextInitialized(ServletContextEvent servletContextEvent) { + SessionContextProviderFactory.getInstance().createInterface().create("onboarding", "dox"); + springListener = new ContextLoaderListener(); + springListener.initWebApplicationContext(servletContextEvent.getServletContext()); + } - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - springListener.closeWebApplicationContext(servletContextEvent.getServletContext()); - } + @Override + public void contextDestroyed(ServletContextEvent servletContextEvent) { + springListener.closeWebApplicationContext(servletContextEvent.getServletContext()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/RestConstants.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/RestConstants.java index 230d1610eb..3f7dd523f9 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/RestConstants.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/RestConstants.java @@ -13,20 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.common; public class RestConstants { - // value Should be equal to com.tlv.sdc.common.api.Constants#USER_ID_HEADER - public static final String USER_ID_HEADER_PARAM = "USER_ID"; - public static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; - public static final String USER_MISSING_ERROR_MSG = - "Field does not conform to predefined criteria : user : may not be null"; - - public static final String INVALID_JSON_ERROR_MESSAGE = - "Field does not conform to predefined criteria : body :must be in JSON format"; - private RestConstants() { + // value Should be equal to com.tlv.sdc.common.api.Constants#USER_ID_HEADER + public static final String USER_ID_HEADER_PARAM = "USER_ID"; + public static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; + public static final String USER_MISSING_ERROR_MSG = "Field does not conform to predefined criteria : user : may not be null"; + public static final String INVALID_JSON_ERROR_MESSAGE = "Field does not conform to predefined criteria : body :must be in JSON format"; - } + private RestConstants() { + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorCodeToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorCodeToDto.java index cad5c69899..558d2e7c22 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorCodeToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorCodeToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.common.mapping; import org.openecomp.sdc.common.errors.ErrorCode; @@ -25,10 +24,11 @@ import org.openecomp.sdcrests.common.types.ErrorCodeDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapErrorCodeToDto extends MappingBase { - @Override - public void doMapping(ErrorCode source, ErrorCodeDto target) { - target.setId(source.id()); - target.setCategory(source.category()); - target.setMessage(source.message()); - } + + @Override + public void doMapping(ErrorCode source, ErrorCodeDto target) { + target.setId(source.id()); + target.setCategory(source.category()); + target.setMessage(source.message()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorMessageToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorMessageToDto.java index 83c7b15980..78262b8c30 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorMessageToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/mapping/MapErrorMessageToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.common.mapping; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -25,9 +24,10 @@ import org.openecomp.sdcrests.common.types.ErrorMessageDto; import org.openecomp.sdcrests.mapping.MappingBase; public class MapErrorMessageToDto extends MappingBase { - @Override - public void doMapping(ErrorMessage source, ErrorMessageDto target) { - target.setMessage(source.getMessage()); - target.setLevel(source.getLevel()); - } + + @Override + public void doMapping(ErrorMessage source, ErrorMessageDto target) { + target.setMessage(source.getMessage()); + target.setLevel(source.getLevel()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorCodeDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorCodeDto.java index 3615f89afc..f70d863653 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorCodeDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorCodeDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,37 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.common.types; import org.openecomp.sdc.common.errors.ErrorCategory; public class ErrorCodeDto { - private String id; - private String message; - private ErrorCategory category; - public String getId() { - return id; - } + private String id; + private String message; + private ErrorCategory category; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public ErrorCategory getCategory() { - return category; - } + public ErrorCategory getCategory() { + return category; + } - public void setCategory(ErrorCategory category) { - this.category = category; - } + public void setCategory(ErrorCategory category) { + this.category = category; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorMessageDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorMessageDto.java index f63a9b0ced..9bac491ed1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorMessageDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/common/types/ErrorMessageDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.common.types; import org.openecomp.sdc.datatypes.error.ErrorLevel; public class ErrorMessageDto { - private ErrorLevel level; - private String message; - public ErrorLevel getLevel() { - return level; - } + private ErrorLevel level; + private String message; + + public ErrorLevel getLevel() { + return level; + } - public void setLevel(ErrorLevel level) { - this.level = level; - } + public void setLevel(ErrorLevel level) { + this.level = level; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/DefaultExceptionMapper.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/DefaultExceptionMapper.java index 9fe70fc5e5..0546180575 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/DefaultExceptionMapper.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/DefaultExceptionMapper.java @@ -13,23 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.errors; +import com.fasterxml.jackson.databind.JsonMappingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; - import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; - import org.apache.commons.collections4.CollectionUtils; -import com.fasterxml.jackson.databind.JsonMappingException; import org.hibernate.validator.internal.engine.path.PathImpl; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; @@ -47,9 +44,8 @@ public class DefaultExceptionMapper implements ExceptionMapper { private static final String ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE = "errorCodesToResponseStatusMapping.json"; @SuppressWarnings("unchecked") - private static final Map ERROR_CODE_TO_RESPONSE_STATUS = FileUtils.readViaInputStream( - ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class)); - + private static final Map ERROR_CODE_TO_RESPONSE_STATUS = FileUtils + .readViaInputStream(ERROR_CODES_TO_RESPONSE_STATUS_MAPPING_FILE, stream -> JsonUtil.json2Object(stream, Map.class)); private static final Logger LOGGER = LoggerFactory.getLogger(DefaultExceptionMapper.class); @Override @@ -59,14 +55,11 @@ public class DefaultExceptionMapper implements ExceptionMapper { response = transform(CoreException.class.cast(exception)); } else if (exception instanceof ConstraintViolationException) { response = transform(ConstraintViolationException.class.cast(exception)); - } else if (exception instanceof JsonMappingException) { response = transform(JsonMappingException.class.cast(exception)); - } else { response = transform(exception); } - List contentTypes = new ArrayList<>(); contentTypes.add(MediaType.APPLICATION_JSON); response.getMetadata().put("Content-Type", contentTypes); @@ -77,32 +70,23 @@ public class DefaultExceptionMapper implements ExceptionMapper { Response response; ErrorCode code = coreException.code(); LOGGER.error(code.message(), coreException); - if (coreException.code().category().equals(ErrorCategory.APPLICATION)) { if (Response.Status.NOT_FOUND.name().equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) { - response = Response.status(Response.Status.NOT_FOUND).entity(toEntity(Response.Status.NOT_FOUND, code)) - .build(); + response = Response.status(Response.Status.NOT_FOUND).entity(toEntity(Response.Status.NOT_FOUND, code)).build(); } else if (Response.Status.BAD_REQUEST.name().equals(ERROR_CODE_TO_RESPONSE_STATUS.get(code.id()))) { - response = - Response.status(Response.Status.BAD_REQUEST).entity(toEntity(Response.Status.BAD_REQUEST, code)) - .build(); + response = Response.status(Response.Status.BAD_REQUEST).entity(toEntity(Response.Status.BAD_REQUEST, code)).build(); } else { - response = Response.status(Response.Status.EXPECTATION_FAILED) - .entity(toEntity(Response.Status.EXPECTATION_FAILED, code)).build(); + response = Response.status(Response.Status.EXPECTATION_FAILED).entity(toEntity(Response.Status.EXPECTATION_FAILED, code)).build(); } } else { - response = Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code)).build(); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, code)).build(); } - - return response; } private Response transform(ConstraintViolationException validationException) { Set> constraintViolationSet = validationException.getConstraintViolations(); String message; - String fieldName = null; if (CollectionUtils.isEmpty(constraintViolationSet)) { message = validationException.getMessage(); @@ -111,28 +95,24 @@ public class DefaultExceptionMapper implements ExceptionMapper { ConstraintViolation constraintViolation = constraintViolationSet.iterator().next(); message = constraintViolation.getMessage(); fieldName = getFieldName(constraintViolation.getPropertyPath()); - } - ErrorCode validationErrorCode = new ValidationErrorBuilder(message, fieldName).build(); - LOGGER.error(validationErrorCode.message(), validationException); return Response.status(Response.Status.EXPECTATION_FAILED) //error 417 - .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode)).build(); + .entity(toEntity(Response.Status.EXPECTATION_FAILED, validationErrorCode)).build(); } private Response transform(JsonMappingException jsonMappingException) { ErrorCode jsonMappingErrorCode = new JsonMappingErrorBuilder().build(); LOGGER.error(jsonMappingErrorCode.message(), jsonMappingException); return Response.status(Response.Status.EXPECTATION_FAILED) //error 417 - .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode)).build(); + .entity(toEntity(Response.Status.EXPECTATION_FAILED, jsonMappingErrorCode)).build(); } private Response transform(Exception exception) { ErrorCode errorCode = new GeneralErrorBuilder().build(); LOGGER.error(errorCode.message(), exception); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR) - .entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, errorCode)).build(); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(toEntity(Response.Status.INTERNAL_SERVER_ERROR, errorCode)).build(); } private String getFieldName(Path propertyPath) { diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/ZusammenExceptionMapper.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/ZusammenExceptionMapper.java index abf6024701..497d3cfeb7 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/ZusammenExceptionMapper.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/errors/ZusammenExceptionMapper.java @@ -13,16 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.errors; import com.amdocs.zusammen.datatypes.response.Module; - import java.util.stream.Stream; - import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; - import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.common.errors.ErrorCodeAndMessage; import org.openecomp.sdc.common.errors.GeneralErrorBuilder; @@ -32,19 +28,16 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; public class ZusammenExceptionMapper implements ExceptionMapper { + private static final String ZUSAMMEN_DB_PREFIX = Module.ZDB + "-"; static final String VLM_VSP_VERSION_ID_DOES_NOT_EXISTS = - ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_VERSION_NOT_EXIST; + ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_VERSION_NOT_EXIST; static final String VLM_VSP_ITEM_ID_DOES_NOT_EXISTS = - ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_DOES_NOT_EXIST; - static final String SUB_ENTITY_ID_DOES_NOT_EXISTS = - ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ELEMENT_GET_INFO; - static final String FAILED_TO_SYNC = - ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_VERSION_SYNC; + ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_DOES_NOT_EXIST; + static final String SUB_ENTITY_ID_DOES_NOT_EXISTS = ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ELEMENT_GET_INFO; + static final String FAILED_TO_SYNC = ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_VERSION_SYNC; static final String FAILED_TO_PUBLISH_OUT_OF_SYNC = - ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode - .ZU_ITEM_VERSION_PUBLISH_NOT_ALLOWED; - + ZUSAMMEN_DB_PREFIX + com.amdocs.zusammen.datatypes.response.ErrorCode.ZU_ITEM_VERSION_PUBLISH_NOT_ALLOWED; private static final Logger LOGGER = LoggerFactory.getLogger(ZusammenExceptionMapper.class); @Override @@ -53,29 +46,24 @@ public class ZusammenExceptionMapper implements ExceptionMapper, Map> { - @Override - public void doMapping(Map source, Map target) { - target.putAll(source); - } + @Override + public void doMapping(Map source, Map target) { + target.putAll(source); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/MappingBase.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/MappingBase.java index 8b6fca5ae1..68a16e854c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/MappingBase.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/mapping/MappingBase.java @@ -13,86 +13,71 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.mapping; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; /** - * Base class for all mapping classes. Mapping classes will perform data mapping from source object - * to target object Base class provides following
  1. provides life cycle of - * mapping class , first mapSimpleProperties is called and then mapComplexProperties is - * called.
  2. methods mapSimpleProperties and mapComplexProperties with default - * implementation, these should be overridden by concrete mapping classes for writing mapping - * logic.
- * - * + * Base class for all mapping classes. Mapping classes will perform data mapping from source object to target object Base class provides + * following
+ *
  1. provides life cycle of mapping class , first mapSimpleProperties is called and then mapComplexProperties is called.
  2. methods + * mapSimpleProperties and mapComplexProperties with default implementation, these should be overridden by concrete mapping classes for writing + * mapping logic.
*/ - public abstract class MappingBase { - /** - * Method is called for starting mapping from source object to target object method sets context - * in the thread locale and than calls mapSimpleProperties and mapComplexProperties - * respectively. - * - * @param source : source object for mapping - * @param clazz : target Class for mapping - * @return T - instance of type T - */ - - public final T applyMapping(final S source, Class clazz) { - T target = (T) instantiateTarget(clazz); - if (source != null && target != null) { - preMapping(source, target); - doMapping(source, target); - postMapping(source, target); - + /** + * Method is called for starting mapping from source object to target object method sets context in the thread locale and than calls + * mapSimpleProperties and mapComplexProperties respectively. + * + * @param source : source object for mapping + * @param clazz : target Class for mapping + * @return T - instance of type T + */ + public final T applyMapping(final S source, Class clazz) { + T target = (T) instantiateTarget(clazz); + if (source != null && target != null) { + preMapping(source, target); + doMapping(source, target); + postMapping(source, target); + } + return target; } - return target; - - } - /** - * This method is called before the doMapping method. - */ - public void preMapping(final S source, T target) { - // extension point - } - - /** - * The actual method that does the mapping between the source to target - * objects. This method is being called automatically as part of the mapper class. This - * method must be override (it is abstract) by the mapper class. - * - * @param source - the source object. - * @param target - the target object. - */ - - public abstract void doMapping(final S source, T target); - - /** - * This method is called after the doMapping method. - */ - public void postMapping(final S source, T target) { - // extension point - } - - /** - * Creates the instance of the input class. - * - * @return Object - */ + /** + * This method is called before the doMapping method. + */ + public void preMapping(final S source, T target) { + // extension point + } - private Object instantiateTarget(final Class clazz) { + /** + * The actual method that does the mapping between the source to target objects. This method is being called + * automatically as part of the mapper class. This method must be override (it is abstract) by the mapper class. + * + * @param source - the source object. + * @param target - the target object. + */ + public abstract void doMapping(final S source, T target); + + /** + * This method is called after the doMapping method. + */ + public void postMapping(final S source, T target) { + // extension point + } - try { - return clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException exception ) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(exception.getMessage()).build(), exception); + /** + * Creates the instance of the input class. + * + * @return Object + */ + private Object instantiateTarget(final Class clazz) { + try { + return clazz.newInstance(); + } catch (InstantiationException | IllegalAccessException exception) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(exception.getMessage()).build(), exception); + } } - } } - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/GenericCollectionWrapper.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/GenericCollectionWrapper.java index b73d2d93c5..7bff3d5b77 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/GenericCollectionWrapper.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/GenericCollectionWrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.wrappers; import java.io.Serializable; @@ -25,57 +24,56 @@ import java.util.ArrayList; import java.util.List; public class GenericCollectionWrapper implements Serializable { - private static final long serialVersionUID = 1L; - - private transient List results; - private int listCount; - public GenericCollectionWrapper() { - this.results = new ArrayList<>(); - } + private static final long serialVersionUID = 1L; + private transient List results; + private int listCount; - /** - * Instantiates a new Generic collection wrapper. - * - * @param list the list - */ - public GenericCollectionWrapper(List list) { - if (!list.isEmpty()) { - this.results = list; - this.listCount = list.size(); + public GenericCollectionWrapper() { + this.results = new ArrayList<>(); } - else { - this.results = new ArrayList<>(); + + /** + * Instantiates a new Generic collection wrapper. + * + * @param list the list + */ + public GenericCollectionWrapper(List list) { + if (!list.isEmpty()) { + this.results = list; + this.listCount = list.size(); + } else { + this.results = new ArrayList<>(); + } } - } - public List getResults() { - return results; - } + public List getResults() { + return results; + } - public void setResults(List results) { - this.results = results; - } + public void setResults(List results) { + this.results = results; + } - public int getListCount() { - return listCount; - } + public int getListCount() { + return listCount; + } - public void setListCount(int listCount) { - this.listCount = listCount; - } + public void setListCount(int listCount) { + this.listCount = listCount; + } - /** - * Add boolean. - * - * @param item the list item - * @return the boolean - */ - public boolean add(T item) { - if (this.getResults().add(item)) { - this.setListCount(this.getResults().size()); - return true; + /** + * Add boolean. + * + * @param item the list item + * @return the boolean + */ + public boolean add(T item) { + if (this.getResults().add(item)) { + this.setListCount(this.getResults().size()); + return true; + } + return false; } - return false; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/StringWrapperResponse.java b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/StringWrapperResponse.java index aad4e606de..0cfd5838f4 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/StringWrapperResponse.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/openecomp-sdc-common-rest/src/main/java/org/openecomp/sdcrests/wrappers/StringWrapperResponse.java @@ -13,28 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.wrappers; public class StringWrapperResponse { - private String value; - public StringWrapperResponse() { - // defualt ctor is used by reflection, for instance JSON mapping - super(); - } + private String value; - public StringWrapperResponse(String value) { - super(); - this.value = value; - } + public StringWrapperResponse() { + // defualt ctor is used by reflection, for instance JSON mapping + super(); + } - public String getValue() { - return value; - } + public StringWrapperResponse(String value) { + super(); + this.value = value; + } - public void setValue(String value) { - this.value = value; - } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/TogglzFeatures.java b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/TogglzFeatures.java index bdeefa46f2..ab010c288b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/TogglzFeatures.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/TogglzFeatures.java @@ -13,26 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.togglz.rest; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.togglz.types.FeatureDto; import org.openecomp.sdcrests.togglz.types.FeatureSetDto; import org.springframework.validation.annotation.Validated; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - - @Path("/v1.0/togglz") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -40,24 +41,22 @@ import javax.ws.rs.core.Response; @Validated public interface TogglzFeatures { - @GET - @Operation(description = "Get TOGGLZ Features", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = FeatureSetDto.class))))) - Response getFeatures(); - - - @PUT - @Path("/state/{state}") - @Operation(description = "Update feature toggle state for all features") - Response setAllFeatures(@PathParam("state") boolean state); + @GET + @Operation(description = "Get TOGGLZ Features", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = FeatureSetDto.class))))) + Response getFeatures(); + @PUT + @Path("/state/{state}") + @Operation(description = "Update feature toggle state for all features") + Response setAllFeatures(@PathParam("state") boolean state); - @PUT - @Path("/{featureName}/state/{state}") - @Operation(description = "Update feature toggle state") - Response setFeatureState(@PathParam("featureName") String featureName, @PathParam("state") boolean state); + @PUT + @Path("/{featureName}/state/{state}") + @Operation(description = "Update feature toggle state") + Response setFeatureState(@PathParam("featureName") String featureName, @PathParam("state") boolean state); - @GET - @Path("/{featureName}/state") - @Operation(description = "Get feature toggle state", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = FeatureDto.class)))) - Response getFeatureState(@PathParam("featureName") String featureName); + @GET + @Path("/{featureName}/state") + @Operation(description = "Get feature toggle state", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = FeatureDto.class)))) + Response getFeatureState(@PathParam("featureName") String featureName); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/mapping/MapToggleableFeatureToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/mapping/MapToggleableFeatureToDto.java index c6fbed672e..47cd79bdf0 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/mapping/MapToggleableFeatureToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/mapping/MapToggleableFeatureToDto.java @@ -28,9 +28,8 @@ public class MapToggleableFeatureToDto extends MappingBase source, FeatureSetDto target) { - if (source != null && !source.isEmpty()){ - Set fDtos = source.stream().map(f -> new FeatureDto(f.name(), f.isActive())) - .collect(Collectors.toSet()); + if (source != null && !source.isEmpty()) { + Set fDtos = source.stream().map(f -> new FeatureDto(f.name(), f.isActive())).collect(Collectors.toSet()); target.setFeatures(fDtos); } else { target.setFeatures(Collections.emptySet()); diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/services/TogglzFeaturesImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/services/TogglzFeaturesImpl.java index 4777d0a656..b4e9db695a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/services/TogglzFeaturesImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-services/src/main/java/org/openecomp/sdcrests/togglz/rest/services/TogglzFeaturesImpl.java @@ -13,13 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.togglz.rest.services; + +import java.util.Arrays; +import javax.inject.Named; +import javax.ws.rs.core.Response; +import org.openecomp.sdc.be.togglz.ToggleableFeature; import org.openecomp.sdcrests.togglz.rest.TogglzFeatures; import org.openecomp.sdcrests.togglz.rest.mapping.MapToggleableFeatureToDto; import org.openecomp.sdcrests.togglz.types.FeatureDto; import org.openecomp.sdcrests.togglz.types.FeatureSetDto; -import org.openecomp.sdc.be.togglz.ToggleableFeature; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.togglz.core.Feature; @@ -27,10 +30,6 @@ import org.togglz.core.context.FeatureContext; import org.togglz.core.repository.FeatureState; import org.togglz.core.util.NamedFeature; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Arrays; - @Named @Service("TogglzFeature") @Scope(value = "prototype") @@ -49,7 +48,7 @@ public class TogglzFeaturesImpl implements TogglzFeatures { new MapToggleableFeatureToDto().doMapping(Arrays.asList(ToggleableFeature.values()), featureSetDto); featureSetDto.getFeatures().forEach(featureDto -> { Feature feature = new NamedFeature(featureDto.getName()); - FeatureState featureState = new FeatureState(feature,active); + FeatureState featureState = new FeatureState(feature, active); FeatureContext.getFeatureManager().setFeatureState(featureState); }); return Response.ok().build(); @@ -58,7 +57,7 @@ public class TogglzFeaturesImpl implements TogglzFeatures { @Override public Response setFeatureState(String featureName, boolean active) { Feature feature = new NamedFeature(featureName); - FeatureState featureState = new FeatureState(feature,active); + FeatureState featureState = new FeatureState(feature, active); FeatureContext.getFeatureManager().setFeatureState(featureState); return Response.ok().build(); } @@ -66,10 +65,7 @@ public class TogglzFeaturesImpl implements TogglzFeatures { @Override public Response getFeatureState(String featureName) { boolean active = ToggleableFeature.valueOf(featureName).isActive(); - FeatureDto featureDto = new FeatureDto(featureName,active); - + FeatureDto featureDto = new FeatureDto(featureName, active); return Response.ok(featureDto).build(); } - } - diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureDto.java index d6e2fbd669..786ee06c3a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureDto.java @@ -18,7 +18,7 @@ package org.openecomp.sdcrests.togglz.types; import java.util.Objects; public class FeatureDto { - + private final String name; private final boolean active; @@ -37,8 +37,12 @@ public class FeatureDto { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof FeatureDto)) return false; + if (this == o) { + return true; + } + if (!(o instanceof FeatureDto)) { + return false; + } FeatureDto that = (FeatureDto) o; return Objects.equals(getName(), that.getName()); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureSetDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureSetDto.java index cf7ee71a35..6862041b63 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureSetDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/togglz-rest/togglz-rest-types/src/main/java/org/openecomp/sdcrests/togglz/types/FeatureSetDto.java @@ -18,7 +18,7 @@ package org.openecomp.sdcrests.togglz.types; import java.util.Set; public class FeatureSetDto { - + private Set features; public Set getFeatures() { diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/UniqueTypes.java b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/UniqueTypes.java index 2e91c7a6b7..1bd3b460f7 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/UniqueTypes.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/UniqueTypes.java @@ -15,22 +15,24 @@ */ package org.openecomp.sdcrests.uniquevalue.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.springframework.validation.annotation.Validated; - import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/unique-types") @Produces(MediaType.APPLICATION_JSON) @@ -39,19 +41,17 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface UniqueTypes { - @GET - @Path("/") - @Operation(description = "Lists unique value types") - Response listUniqueTypes(@NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "Lists unique value types") + Response listUniqueTypes(@NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{type}/values/{value}") - @Operation(description = "Gets unique value") - @ApiResponse(responseCode = "200", description = "Indication whether the unique value is occupied") - @ApiResponse(responseCode = "404", description = "Unsupported unique type") - Response getUniqueValue( - @Parameter(description = "The unique value type, for example: 'VlmName'") @PathParam("type") String type, - @Parameter(description = "The unique value") @PathParam("value") String value, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{type}/values/{value}") + @Operation(description = "Gets unique value") + @ApiResponse(responseCode = "200", description = "Indication whether the unique value is occupied") + @ApiResponse(responseCode = "404", description = "Unsupported unique type") + Response getUniqueValue(@Parameter(description = "The unique value type, for example: 'VlmName'") @PathParam("type") String type, + @Parameter(description = "The unique value") @PathParam("value") String value, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/services/UniqueTypesImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/services/UniqueTypesImpl.java index 0e657903b6..4df0ff5532 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/services/UniqueTypesImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-services/src/main/java/org/openecomp/sdcrests/uniquevalue/rest/services/UniqueTypesImpl.java @@ -18,7 +18,16 @@ */ package org.openecomp.sdcrests.uniquevalue.rest.services; +import static javax.ws.rs.core.Response.Status.NOT_FOUND; + import com.google.common.annotations.VisibleForTesting; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.ServiceLoader; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.core.dao.UniqueValueDaoFactory; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -30,65 +39,48 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; - -import java.util.*; - -import static javax.ws.rs.core.Response.Status.NOT_FOUND; - @Named @Service("uniqueTypes") @Scope(value = "prototype") public class UniqueTypesImpl implements UniqueTypes { - private static final String UNIQUE_TYPE_NOT_FOUND_ERR_ID = "UNIQUE_TYPE_NOT_FOUND"; - private static final String UNIQUE_TYPE_NOT_FOUND_MSG = "%s is not a supported unique type."; - - private static final Map UNIQUE_TYPE_TO_INTERNAL; - private UniqueValueUtil uniqueValueUtil; - - static { - Map uniqueTypes = new HashMap<>(); - ServiceLoader.load(UniqueTypesProvider.class) - .forEach(typesProvider -> uniqueTypes.putAll(typesProvider.listUniqueTypes())); - UNIQUE_TYPE_TO_INTERNAL = Collections.unmodifiableMap(uniqueTypes); - } + private static final String UNIQUE_TYPE_NOT_FOUND_ERR_ID = "UNIQUE_TYPE_NOT_FOUND"; + private static final String UNIQUE_TYPE_NOT_FOUND_MSG = "%s is not a supported unique type."; + private static final Map UNIQUE_TYPE_TO_INTERNAL; + static { + Map uniqueTypes = new HashMap<>(); + ServiceLoader.load(UniqueTypesProvider.class).forEach(typesProvider -> uniqueTypes.putAll(typesProvider.listUniqueTypes())); + UNIQUE_TYPE_TO_INTERNAL = Collections.unmodifiableMap(uniqueTypes); + } - @Override - public Response listUniqueTypes(String user) { - return Response.ok( - new GenericCollectionWrapper<>(new ArrayList<>(UNIQUE_TYPE_TO_INTERNAL.keySet()))) - .build(); - } - - @Override - public Response getUniqueValue(String type, String value, String user) { - String internalType = UNIQUE_TYPE_TO_INTERNAL.get(type); + private UniqueValueUtil uniqueValueUtil; - if (internalType == null) { - ErrorCode error = new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId(UNIQUE_TYPE_NOT_FOUND_ERR_ID) - .withMessage(String.format(UNIQUE_TYPE_NOT_FOUND_MSG, type)).build(); - return Response.status(NOT_FOUND).entity(new ErrorCodeAndMessage(NOT_FOUND, error)).build(); + @Override + public Response listUniqueTypes(String user) { + return Response.ok(new GenericCollectionWrapper<>(new ArrayList<>(UNIQUE_TYPE_TO_INTERNAL.keySet()))).build(); } - return Response.ok(Collections - .singletonMap("occupied", getUniqueValueUtil().isUniqueValueOccupied(internalType, value))) - .build(); - } + @Override + public Response getUniqueValue(String type, String value, String user) { + String internalType = UNIQUE_TYPE_TO_INTERNAL.get(type); + if (internalType == null) { + ErrorCode error = new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(UNIQUE_TYPE_NOT_FOUND_ERR_ID) + .withMessage(String.format(UNIQUE_TYPE_NOT_FOUND_MSG, type)).build(); + return Response.status(NOT_FOUND).entity(new ErrorCodeAndMessage(NOT_FOUND, error)).build(); + } + return Response.ok(Collections.singletonMap("occupied", getUniqueValueUtil().isUniqueValueOccupied(internalType, value))).build(); + } - @VisibleForTesting - void setUniqueValueUtil(UniqueValueUtil uniqueValueUtil) { - this.uniqueValueUtil = uniqueValueUtil; - } + private UniqueValueUtil getUniqueValueUtil() { + if (uniqueValueUtil == null) { + uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + } + return uniqueValueUtil; + } - private UniqueValueUtil getUniqueValueUtil() { - if (uniqueValueUtil == null){ - uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + @VisibleForTesting + void setUniqueValueUtil(UniqueValueUtil uniqueValueUtil) { + this.uniqueValueUtil = uniqueValueUtil; } - return uniqueValueUtil; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-types/src/main/java/org/openecomp/sdcrests/uniquevalue/types/UniqueTypesProvider.java b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-types/src/main/java/org/openecomp/sdcrests/uniquevalue/types/UniqueTypesProvider.java index 986667227c..533ba46e59 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-types/src/main/java/org/openecomp/sdcrests/uniquevalue/types/UniqueTypesProvider.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/unique-type-rest/unique-type-rest-types/src/main/java/org/openecomp/sdcrests/uniquevalue/types/UniqueTypesProvider.java @@ -18,12 +18,10 @@ package org.openecomp.sdcrests.uniquevalue.types; import java.util.Map; /** - * The unique value service exposes APIs to list unique types and check whether a value is - * already taken. - * The modules which uses the unique value logic and would like to enable these APIs must - * implement this class. + * The unique value service exposes APIs to list unique types and check whether a value is already taken. The modules which uses the unique value + * logic and would like to enable these APIs must implement this class. */ public interface UniqueTypesProvider { - Map listUniqueTypes(); + Map listUniqueTypes(); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/Validation.java b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/Validation.java index ec8c8eb945..e354abf85a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/Validation.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/Validation.java @@ -13,33 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.validation.rest; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.apache.cxf.jaxrs.ext.multipart.Multipart; -import org.springframework.validation.annotation.Validated; - -import javax.ws.rs.*; +import java.io.InputStream; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.InputStream; - +import org.apache.cxf.jaxrs.ext.multipart.Multipart; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/validation") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Validation")}) @Validated - public interface Validation { - - @POST - @Path("{type}/validate") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response validateFile(@PathParam("type") String type, - @Multipart("validate") InputStream fileToValidate); + @POST + @Path("{type}/validate") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response validateFile(@PathParam("type") String type, @Multipart("validate") InputStream fileToValidate); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/ValidationForSwaggerUsage.java b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/ValidationForSwaggerUsage.java index e184b9e2a4..ac4f0ad64d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/ValidationForSwaggerUsage.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/ValidationForSwaggerUsage.java @@ -13,35 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.validation.rest; import com.sun.jersey.multipart.FormDataParam; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.springframework.validation.annotation.Validated; - -import javax.ws.rs.*; +import java.io.InputStream; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.InputStream; - +import org.springframework.validation.annotation.Validated; @Path("/v1.0/validation") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Validation")}) @Validated - public interface ValidationForSwaggerUsage { - - @POST - @Path("{type}/validate") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Validate a package") - Response validateFile(@PathParam("type") String type, - @FormDataParam("validate") InputStream fileToValidate); + @POST + @Path("{type}/validate") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Validate a package") + Response validateFile(@PathParam("type") String type, @FormDataParam("validate") InputStream fileToValidate); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/mapping/MapValidationFileResponseToValidationFileResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/mapping/MapValidationFileResponseToValidationFileResponseDto.java index 9f8ae80e18..99e375d07e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/mapping/MapValidationFileResponseToValidationFileResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/mapping/MapValidationFileResponseToValidationFileResponseDto.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.validation.rest.mapping; - import org.openecomp.sdc.validation.types.ValidationFileResponse; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.validation.types.ValidationFileResponseDto; @@ -24,10 +22,10 @@ import org.openecomp.sdcrests.validation.types.ValidationFileResponseDto; /** * Created by TALIO on 4/27/2016. */ -public class MapValidationFileResponseToValidationFileResponseDto - extends MappingBase { - @Override - public void doMapping(ValidationFileResponse source, ValidationFileResponseDto target) { - target.setValidationData(source.getValidationData()); - } +public class MapValidationFileResponseToValidationFileResponseDto extends MappingBase { + + @Override + public void doMapping(ValidationFileResponse source, ValidationFileResponseDto target) { + target.setValidationData(source.getValidationData()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/services/ValidationImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/services/ValidationImpl.java index 1ece6f75f8..da604b7cb1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/services/ValidationImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-services/src/main/java/org/openecomp/sdcrests/validation/rest/services/ValidationImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,10 +19,12 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdcrests.validation.rest.services; - +import java.io.IOException; +import java.io.InputStream; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.validation.UploadValidationManager; import org.openecomp.sdc.validation.types.ValidationFileResponse; import org.openecomp.sdcrests.validation.rest.Validation; @@ -32,37 +34,28 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.io.InputStream; - @Named @Service("validation") @Scope(value = "prototype") public class ValidationImpl implements Validation { - private final UploadValidationManager uploadValidationManager; - - @Autowired - public ValidationImpl(UploadValidationManager uploadValidationManager) { - this.uploadValidationManager = uploadValidationManager; - } + private final UploadValidationManager uploadValidationManager; - @Override - public Response validateFile(String type, InputStream fileToValidate) { - ValidationFileResponse validationFileResponse; - try { - validationFileResponse = uploadValidationManager.validateFile(type, fileToValidate); - } catch (IOException exception) { - throw new RuntimeException(exception); + @Autowired + public ValidationImpl(UploadValidationManager uploadValidationManager) { + this.uploadValidationManager = uploadValidationManager; } - ValidationFileResponseDto validationFileResponseDto = - new MapValidationFileResponseToValidationFileResponseDto() + @Override + public Response validateFile(String type, InputStream fileToValidate) { + ValidationFileResponse validationFileResponse; + try { + validationFileResponse = uploadValidationManager.validateFile(type, fileToValidate); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + ValidationFileResponseDto validationFileResponseDto = new MapValidationFileResponseToValidationFileResponseDto() .applyMapping(validationFileResponse, ValidationFileResponseDto.class); - return Response.ok(validationFileResponseDto).build(); - } - - + return Response.ok(validationFileResponseDto).build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-types/src/main/java/org/openecomp/sdcrests/validation/types/ValidationFileResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-types/src/main/java/org/openecomp/sdcrests/validation/types/ValidationFileResponseDto.java index 1ec6568a73..3e82a063b6 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-types/src/main/java/org/openecomp/sdcrests/validation/types/ValidationFileResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/validation-rest/validation-rest-types/src/main/java/org/openecomp/sdcrests/validation/types/ValidationFileResponseDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.validation.types; import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; @@ -26,16 +25,18 @@ import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; * Created by TALIO on 4/27/2016. */ public class ValidationFileResponseDto { - //private List fileNames; - //private Map> errors; - //private ValidationFileStatus status; - private ValidationStructureList validationData; + //private List fileNames; + + //private Map> errors; + + //private ValidationFileStatus status; + private ValidationStructureList validationData; - public ValidationStructureList getValidationData() { - return validationData; - } + public ValidationStructureList getValidationData() { + return validationData; + } - public void setValidationData(ValidationStructureList validationData) { - this.validationData = validationData; - } + public void setValidationData(ValidationStructureList validationData) { + this.validationData = validationData; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPoolLimits.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPoolLimits.java index 7caa639bac..7225a36f55 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPoolLimits.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPoolLimits.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,102 +17,83 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; -import org.openecomp.sdcrests.vendorlicense.types.LimitRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.LimitRequestDto; +import org.springframework.validation.annotation.Validated; -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - -@Path( - "/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/entitlement-pools/{entitlementPoolId}/limits") +@Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/entitlement-pools/{entitlementPoolId}/limits") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor License Model - Entitlement Pool Limits")}) @Validated public interface EntitlementPoolLimits { - @POST - @Path("/") - @Operation(description = "Create vendor entitlement pool limits") - Response createLimit(@Valid LimitRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") - String versionId, - @Parameter(description = "Vendor license model Entitlement Pool Id") - @PathParam("entitlementPoolId") - String entitlementPoolId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - - @GET - @Path("/") - @Operation(description = "List vendor entitlement pool limits", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = LimitRequestDto.class))))) - Response listLimits( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam("entitlementPoolId") - String entitlementPoolId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Operation(description = "Create vendor entitlement pool limits") + Response createLimit(@Valid LimitRequestDto request, @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam("entitlementPoolId") String entitlementPoolId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{limitId}") - @Operation(description = "Update vendor entitlement pool limit") - Response updateLimit(@Valid LimitRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") - String versionId, - @Parameter(description = "Vendor license model Entitlement Pool Id") - @PathParam("entitlementPoolId") - String entitlementPoolId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @PathParam("limitId") String limitId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor entitlement pool limits", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LimitRequestDto.class))))) + Response listLimits(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam("entitlementPoolId") String entitlementPoolId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{limitId}") - @Operation(description = "Get vendor entitlement pool limit", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LimitEntityDto.class)))) - Response getLimit( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam - ("entitlementPoolId") String entitlementPoolId, - @Parameter(description = "Vendor license model Entitlement Pool Limit Id") @PathParam("limitId") - String limitId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{limitId}") + @Operation(description = "Update vendor entitlement pool limit") + Response updateLimit(@Valid LimitRequestDto request, @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam("entitlementPoolId") String entitlementPoolId, + @NotNull(message = USER_MISSING_ERROR_MSG) @PathParam("limitId") String limitId, + @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{limitId}") - @Operation(description = "Delete vendor entitlement pool limit") - Response deleteLimit( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model Entitlement pool Id") @PathParam("entitlementPoolId") - String entitlementPoolId, - @PathParam("limitId") String limitId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{limitId}") + @Operation(description = "Get vendor entitlement pool limit", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LimitEntityDto.class)))) + Response getLimit(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model Entitlement Pool Id") @PathParam("entitlementPoolId") String entitlementPoolId, + @Parameter(description = "Vendor license model Entitlement Pool Limit Id") @PathParam("limitId") String limitId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{limitId}") + @Operation(description = "Delete vendor entitlement pool limit") + Response deleteLimit(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model Entitlement pool Id") @PathParam("entitlementPoolId") String entitlementPoolId, + @PathParam("limitId") String limitId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPools.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPools.java index 89b632f2e5..b2d320023e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPools.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/EntitlementPools.java @@ -17,30 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolEntityDto; -import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/entitlement-pools") @Produces(MediaType.APPLICATION_JSON) @@ -48,52 +53,44 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor License Model - Entitlement Pools")}) @Validated public interface EntitlementPools { + @GET @Path("/") - @Operation(description = "List vendor entitlement pools", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = EntitlementPoolEntityDto.class))))) - Response listEntitlementPools( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @Operation(description = "List vendor entitlement pools", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = EntitlementPoolEntityDto.class))))) + Response listEntitlementPools(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); @POST @Path("/") @Operation(description = "Create vendor entitlement pool") Response createEntitlementPool(@Valid EntitlementPoolRequestDto request, @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam ("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); @PUT @Path("/{entitlementPoolId}") @Operation(description = "Update vendor entitlement pool") Response updateEntitlementPool(@Valid EntitlementPoolRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @PathParam("entitlementPoolId") String entitlementPoolId, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @PathParam("entitlementPoolId") String entitlementPoolId, @HeaderParam(USER_ID_HEADER_PARAM) String user); @GET @Path("/{entitlementPoolId}") @Operation(description = "Get vendor entitlement pool", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = EntitlementPoolEntityDto.class)))) - Response getEntitlementPool( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("entitlementPoolId") String entitlementPoolId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + Response getEntitlementPool(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("entitlementPoolId") String entitlementPoolId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); @DELETE @Path("/{entitlementPoolId}") @Operation(description = "Delete vendor entitlement pool") - Response deleteEntitlementPool( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("entitlementPoolId") String entitlementPoolId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - + Response deleteEntitlementPool(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("entitlementPoolId") String entitlementPoolId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/FeatureGroups.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/FeatureGroups.java index 80403f59e1..efb6479b0f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/FeatureGroups.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/FeatureGroups.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,34 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupEntityDto; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupModelDto; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupRequestDto; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupUpdateRequestDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - - @Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/feature-groups") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -52,51 +56,43 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface FeatureGroups { - @GET - @Path("/") - @Operation(description = "List vendor feature groups",responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation =FeatureGroupEntityDto.class))))) - Response listFeatureGroups( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @POST - @Path("/") - @Operation(description = "Create vendor feature group") - Response createFeatureGroup(@Valid FeatureGroupRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor feature groups", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = FeatureGroupEntityDto.class))))) + Response listFeatureGroups(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{featureGroupId}") - @Operation(description = "Update vendor feature group") - Response updateFeatureGroup(@Valid FeatureGroupUpdateRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("featureGroupId") String featureGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Operation(description = "Create vendor feature group") + Response createFeatureGroup(@Valid FeatureGroupRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{featureGroupId}") - @Operation(description = "Get vendor feature group", responses = @ApiResponse(content = @Content(schema = @Schema(implementation =FeatureGroupModelDto.class)))) - Response getFeatureGroup( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("featureGroupId") String featureGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{featureGroupId}") + @Operation(description = "Update vendor feature group") + Response updateFeatureGroup(@Valid FeatureGroupUpdateRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("featureGroupId") String featureGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{featureGroupId}") - @Operation(description = "Delete vendor feature group") - Response deleteFeatureGroup( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("featureGroupId") String featureGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{featureGroupId}") + @Operation(description = "Get vendor feature group", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = FeatureGroupModelDto.class)))) + Response getFeatureGroup(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("featureGroupId") String featureGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{featureGroupId}") + @Operation(description = "Delete vendor feature group") + Response deleteFeatureGroup(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("featureGroupId") String featureGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseAgreements.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseAgreements.java index 0d384ed7bb..d74ddaa8fe 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseAgreements.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseAgreements.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,89 +17,82 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementEntityDto; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementModelDto; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementRequestDto; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementUpdateRequestDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - - @Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/license-agreements") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor License Model - License Agreements")}) @Validated - public interface LicenseAgreements { - @GET - @Path("/") - @Operation(description = "List vendor license agreements", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation =LicenseAgreementEntityDto.class))))) - Response listLicenseAgreements( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @POST - @Path("/") - @Operation(description = "Create vendor license agreement") - Response createLicenseAgreement(@Valid LicenseAgreementRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor license agreements", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LicenseAgreementEntityDto.class))))) + Response listLicenseAgreements(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{licenseAgreementId}") - @Operation(description = "Update vendor license agreement") - Response updateLicenseAgreement(@Valid LicenseAgreementUpdateRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @PathParam("licenseAgreementId") String licenseAgreementId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Operation(description = "Create vendor license agreement") + Response createLicenseAgreement(@Valid LicenseAgreementRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{licenseAgreementId}") - @Operation(description = "Get vendor license agreement", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LicenseAgreementModelDto.class)))) - Response getLicenseAgreement( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("licenseAgreementId") String licenseAgreementId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{licenseAgreementId}") + @Operation(description = "Update vendor license agreement") + Response updateLicenseAgreement(@Valid LicenseAgreementUpdateRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseAgreementId") String licenseAgreementId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{licenseAgreementId}") - @Operation(description = "Delete vendor license agreement") - Response deleteLicenseAgreement( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("licenseAgreementId") String licenseAgreementId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{licenseAgreementId}") + @Operation(description = "Get vendor license agreement", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LicenseAgreementModelDto.class)))) + Response getLicenseAgreement(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseAgreementId") String licenseAgreementId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{licenseAgreementId}") + @Operation(description = "Delete vendor license agreement") + Response deleteLicenseAgreement(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseAgreementId") String licenseAgreementId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroupLimits.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroupLimits.java index afa9663b10..898f084d5f 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroupLimits.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroupLimits.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,100 +17,83 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; -import org.openecomp.sdcrests.vendorlicense.types.LimitRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.LimitRequestDto; +import org.springframework.validation.annotation.Validated; -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - -@Path( - "/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/license-key-groups/{licenseKeyGroupId}/limits") +@Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/license-key-groups/{licenseKeyGroupId}/limits") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor License Model - License Key Group Limits")}) @Validated public interface LicenseKeyGroupLimits { - @POST - @Path("/") - @Operation(description = "Create vendor license key group limit") - Response createLimit(@Valid LimitRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") - String versionId, - @Parameter(description = "Vendor license model License Key Group Id") - @PathParam("licenseKeyGroupId") - String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Operation(description = "Create vendor license key group limit") + Response createLimit(@Valid LimitRequestDto request, @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model License Key Group Id") @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/") - @Operation(description = "List vendor license key group limits", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = LimitEntityDto.class))))) - Response listLimits( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model License Key Group Id") @PathParam("licenseKeyGroupId") - String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor license key group limits", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LimitEntityDto.class))))) + Response listLimits(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model License Key Group Id") @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{limitId}") - @Operation(description = "Update vendor license key group limit") - Response updateLimit(@Valid LimitRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") - String versionId, - @Parameter(description = "Vendor license model License Key Group Id") - @PathParam("licenseKeyGroupId") - String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @PathParam("limitId") String limitId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{limitId}") + @Operation(description = "Update vendor license key group limit") + Response updateLimit(@Valid LimitRequestDto request, @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model License Key Group Id") @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @PathParam("limitId") String limitId, + @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{limitId}") - @Operation(description = "Get vendor entitlement pool limit", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LimitEntityDto.class)))) - Response getLimit( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model License Key Group") @PathParam - ("licenseKeyGroupId") String entitlementPoolId, - @Parameter(description = "Vendor license model License Key Group Limit Id") @PathParam("limitId") - String limitId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{limitId}") + @Operation(description = "Get vendor entitlement pool limit", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LimitEntityDto.class)))) + Response getLimit(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model License Key Group") @PathParam("licenseKeyGroupId") String entitlementPoolId, + @Parameter(description = "Vendor license model License Key Group Limit Id") @PathParam("limitId") String limitId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{limitId}") - @Operation(description = "Delete vendor license key group limit") - Response deleteLimit( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor license model license key group Id") @PathParam("licenseKeyGroupId") - String licenseKeyGroupId, - @PathParam("limitId") String limitId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{limitId}") + @Operation(description = "Delete vendor license key group limit") + Response deleteLimit(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor license model license key group Id") @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @PathParam("limitId") String limitId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroups.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroups.java index 50dc3c82a1..2bb565b124 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroups.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/LicenseKeyGroups.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupEntityDto; -import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - +import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupEntityDto; +import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-license-models/{vlmId}/versions/{versionId}/license-key-groups") @Produces(MediaType.APPLICATION_JSON) @@ -49,52 +53,44 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor License Model - License Key Groups")}) @Validated public interface LicenseKeyGroups { - @GET - @Path("/") - @Operation(description = "List vendor license key groups", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation =LicenseKeyGroupEntityDto.class))))) - Response listLicenseKeyGroups( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/") - @Operation(description = "Create vendor license key group") - Response createLicenseKeyGroup(@Valid LicenseKeyGroupRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor license key groups", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = LicenseKeyGroupEntityDto.class))))) + Response listLicenseKeyGroups(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @POST + @Path("/") + @Operation(description = "Create vendor license key group") + Response createLicenseKeyGroup(@Valid LicenseKeyGroupRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{licenseKeyGroupId}") - @Operation(description = "Update vendor license key group") - Response updateLicenseKeyGroup(@Valid LicenseKeyGroupRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @PathParam("licenseKeyGroupId") String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{licenseKeyGroupId}") + @Operation(description = "Update vendor license key group") + Response updateLicenseKeyGroup(@Valid LicenseKeyGroupRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{licenseKeyGroupId}") - @Operation(description = "Get vendor license key group",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LicenseKeyGroupEntityDto.class)))) - Response getLicenseKeyGroup( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("licenseKeyGroupId") String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{licenseKeyGroupId}") + @Operation(description = "Get vendor license key group", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = LicenseKeyGroupEntityDto.class)))) + Response getLicenseKeyGroup(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{licenseKeyGroupId}") - @Operation(description = "Delete vendor license key group") - Response deleteLicenseKeyGroup( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, - @PathParam("licenseKeyGroupId") String licenseKeyGroupId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{licenseKeyGroupId}") + @Operation(description = "Delete vendor license key group") + Response deleteLicenseKeyGroup(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @PathParam("licenseKeyGroupId") String licenseKeyGroupId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/VendorLicenseModels.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/VendorLicenseModels.java index 3778129f7f..0636b6e599 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/VendorLicenseModels.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/VendorLicenseModels.java @@ -13,19 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdcrests.vendorlicense.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.common.RestConstants; import org.openecomp.sdcrests.item.types.ItemDto; import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelActionRequestDto; @@ -33,15 +46,6 @@ import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelEntityDto; import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelRequestDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - - @Path("/v1.0/vendor-license-models") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -49,64 +53,48 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface VendorLicenseModels { - @GET - @Path("/") - @Operation(description = "List vendor license models", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation=ItemDto.class))))) - Response listLicenseModels(@Parameter(description = "Filter to return only Vendor License Models with at" + - " least one version at this status. Currently supported values: 'Certified' , 'Draft'") - @QueryParam("versionFilter") String versionStatus, - @Parameter(description = "Filter to only return Vendor License Models at this status." + - "Currently supported values: 'ACTIVE' , 'ARCHIVED'." + - "Default value = 'ACTIVE'.") - @QueryParam("Status") String itemStatus, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - - @POST - @Path("/") - @Operation(description = "Create vendor license model") - Response createLicenseModel(@Valid VendorLicenseModelRequestDto request, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @GET + @Path("/") + @Operation(description = "List vendor license models", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ItemDto.class))))) + Response listLicenseModels(@Parameter(description = "Filter to return only Vendor License Models with at" + + " least one version at this status. Currently supported values: 'Certified' , 'Draft'") @QueryParam("versionFilter") String versionStatus, + @Parameter(description = "Filter to only return Vendor License Models at this status." + + "Currently supported values: 'ACTIVE' , 'ARCHIVED'." + + "Default value = 'ACTIVE'.") @QueryParam("Status") String itemStatus, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{vlmId}") - @Operation(description = "Delete vendor license model") - Response deleteLicenseModel( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create vendor license model") + Response createLicenseModel(@Valid VendorLicenseModelRequestDto request, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{vlmId}/versions/{versionId}") - @Operation(description = "Update vendor license model") - Response updateLicenseModel(@Valid VendorLicenseModelRequestDto request, - @Parameter(description = "Vendor license model Id") - @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{vlmId}") + @Operation(description = "Delete vendor license model") + Response deleteLicenseModel(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{vlmId}/versions/{versionId}") - @Operation(description = "Get vendor license model", responses = @ApiResponse(content = @Content(schema = @Schema(implementation=VendorLicenseModelEntityDto.class)))) - Response getLicenseModel( - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) - String user); + @PUT + @Path("/{vlmId}/versions/{versionId}") + @Operation(description = "Update vendor license model") + Response updateLicenseModel(@Valid VendorLicenseModelRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{vlmId}/versions/{versionId}") + @Operation(description = "Get vendor license model", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = VendorLicenseModelEntityDto.class)))) + Response getLicenseModel(@Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{vlmId}/versions/{versionId}/actions") - @Operation(description = "Update vendor license model") - Response actOnLicenseModel(@Valid VendorLicenseModelActionRequestDto request, - @Parameter(description = "Vendor license model Id") @PathParam("vlmId") - String vlmId, - @Parameter(description = "Vendor license model version Id") @PathParam - ("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{vlmId}/versions/{versionId}/actions") + @Operation(description = "Update vendor license model") + Response actOnLicenseModel(@Valid VendorLicenseModelActionRequestDto request, + @Parameter(description = "Vendor license model Id") @PathParam("vlmId") String vlmId, + @Parameter(description = "Vendor license model version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(RestConstants.USER_ID_HEADER_PARAM) String user); } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/LimitCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/LimitCreationDto.java index 35833e9621..05d2d1ac77 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/LimitCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/LimitCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; public class LimitCreationDto { - private String limitId; - public String getLimitId() { - return limitId; - } + private String limitId; + + public String getLimitId() { + return limitId; + } - public void setLimitId(String limitId) { - this.limitId = limitId; - } + public void setLimitId(String limitId) { + this.limitId = limitId; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherDtoToChoiceOrOther.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherDtoToChoiceOrOther.java index 28eeb29018..f4b6119056 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherDtoToChoiceOrOther.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherDtoToChoiceOrOther.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.ChoiceOrOtherDto; -public class MapChoiceOrOtherDtoToChoiceOrOther - extends MappingBase { +public class MapChoiceOrOtherDtoToChoiceOrOther extends MappingBase { - @Override - public void doMapping(ChoiceOrOtherDto source, ChoiceOrOther target) { - target.setChoice(source.getChoice()); - target.setOther(source.getOther()); - target.setResult(null); - } + @Override + public void doMapping(ChoiceOrOtherDto source, ChoiceOrOther target) { + target.setChoice(source.getChoice()); + target.setOther(source.getOther()); + target.setResult(null); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherToChoiceOrOtherDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherToChoiceOrOtherDto.java index 2d686110d5..aad72491ac 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherToChoiceOrOtherDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapChoiceOrOtherToChoiceOrOtherDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.ChoiceOrOtherDto; -public class MapChoiceOrOtherToChoiceOrOtherDto - extends MappingBase { +public class MapChoiceOrOtherToChoiceOrOtherDto extends MappingBase { - @Override - public void doMapping(ChoiceOrOther source, ChoiceOrOtherDto target) { - target.setChoice(source.getChoice()); - target.setOther(source.getOther()); - } + @Override + public void doMapping(ChoiceOrOther source, ChoiceOrOtherDto target) { + target.setChoice(source.getChoice()); + target.setOther(source.getOther()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolEntityToEntitlementPoolEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolEntityToEntitlementPoolEntityDto.java index 2510bd0634..6dc6e6af92 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolEntityToEntitlementPoolEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolEntityToEntitlementPoolEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; @@ -25,26 +24,23 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolEntityDto; import org.openecomp.sdcrests.vendorlicense.types.MultiChoiceOrOtherDto; -public class MapEntitlementPoolEntityToEntitlementPoolEntityDto - extends MappingBase { - @Override - public void doMapping(EntitlementPoolEntity source, EntitlementPoolEntityDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - target.setThresholdValue(source.getThresholdValue()); - target.setThresholdUnits(source.getThresholdUnit()); - target.setIncrements(source.getIncrements()); - - target.setOperationalScope(new MapMultiChoiceOrOtherToMultiChoiceOrOtherDto() - .applyMapping(source.getOperationalScope(), MultiChoiceOrOtherDto.class)); - - target.setReferencingFeatureGroups(source.getReferencingFeatureGroups()); +public class MapEntitlementPoolEntityToEntitlementPoolEntityDto extends MappingBase { - target.setStartDate(source.getStartDate()); - target.setExpiryDate(source.getExpiryDate()); - target.setVersionUUID(source.getVersionUuId()); - target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); - } + @Override + public void doMapping(EntitlementPoolEntity source, EntitlementPoolEntityDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + target.setThresholdValue(source.getThresholdValue()); + target.setThresholdUnits(source.getThresholdUnit()); + target.setIncrements(source.getIncrements()); + target.setOperationalScope( + new MapMultiChoiceOrOtherToMultiChoiceOrOtherDto().applyMapping(source.getOperationalScope(), MultiChoiceOrOtherDto.class)); + target.setReferencingFeatureGroups(source.getReferencingFeatureGroups()); + target.setStartDate(source.getStartDate()); + target.setExpiryDate(source.getExpiryDate()); + target.setVersionUUID(source.getVersionUuId()); + target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolRequestDtoToEntitlementPoolEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolRequestDtoToEntitlementPoolEntity.java index 5c45ed652a..1058a869aa 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolRequestDtoToEntitlementPoolEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapEntitlementPoolRequestDtoToEntitlementPoolEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; @@ -25,21 +24,20 @@ import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.EntitlementPoolRequestDto; -public class MapEntitlementPoolRequestDtoToEntitlementPoolEntity - extends MappingBase { - @Override - public void doMapping(EntitlementPoolRequestDto source, EntitlementPoolEntity target) { - target.setName(source.getName()); - target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - target.setThresholdValue(source.getThresholdValue()); - target.setThresholdUnit(source.getThresholdUnits()); - target.setIncrements(source.getIncrements()); - target.setOperationalScope(new MapMultiChoiceOrOtherDtoToMultiChoiceOrOther() - .applyMapping(source.getOperationalScope(), MultiChoiceOrOther.class)); +public class MapEntitlementPoolRequestDtoToEntitlementPoolEntity extends MappingBase { - target.setStartDate(source.getStartDate()); - target.setExpiryDate(source.getExpiryDate()); - } + @Override + public void doMapping(EntitlementPoolRequestDto source, EntitlementPoolEntity target) { + target.setName(source.getName()); + target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + target.setThresholdValue(source.getThresholdValue()); + target.setThresholdUnit(source.getThresholdUnits()); + target.setIncrements(source.getIncrements()); + target.setOperationalScope( + new MapMultiChoiceOrOtherDtoToMultiChoiceOrOther().applyMapping(source.getOperationalScope(), MultiChoiceOrOther.class)); + target.setStartDate(source.getStartDate()); + target.setExpiryDate(source.getExpiryDate()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupDescriptorDtoToFeatureGroupEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupDescriptorDtoToFeatureGroupEntity.java index 5dbf087e45..e362c92196 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupDescriptorDtoToFeatureGroupEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupDescriptorDtoToFeatureGroupEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupDescriptorDto; -public class MapFeatureGroupDescriptorDtoToFeatureGroupEntity - extends MappingBase { - @Override - public void doMapping(FeatureGroupDescriptorDto source, FeatureGroupEntity target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setPartNumber(source.getPartNumber()); - } -} \ No newline at end of file +public class MapFeatureGroupDescriptorDtoToFeatureGroupEntity extends MappingBase { + + @Override + public void doMapping(FeatureGroupDescriptorDto source, FeatureGroupEntity target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setPartNumber(source.getPartNumber()); + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupEntityToFeatureGroupDescriptorDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupEntityToFeatureGroupDescriptorDto.java index 70f5666bcb..ee8626abaa 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupEntityToFeatureGroupDescriptorDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapFeatureGroupEntityToFeatureGroupDescriptorDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.FeatureGroupDescriptorDto; -public class MapFeatureGroupEntityToFeatureGroupDescriptorDto - extends MappingBase { - @Override - public void doMapping(FeatureGroupEntity source, FeatureGroupDescriptorDto target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setPartNumber(source.getPartNumber()); - } +public class MapFeatureGroupEntityToFeatureGroupDescriptorDto extends MappingBase { + + @Override + public void doMapping(FeatureGroupEntity source, FeatureGroupDescriptorDto target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setPartNumber(source.getPartNumber()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity.java index f5ea8414d5..98d703299b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; @@ -25,14 +24,13 @@ import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementDescriptorDto; -public class MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity - extends MappingBase { - @Override - public void doMapping(LicenseAgreementDescriptorDto source, LicenseAgreementEntity target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setLicenseTerm(new MapChoiceOrOtherDtoToChoiceOrOther() - .applyMapping(source.getLicenseTerm(), ChoiceOrOther.class)); - target.setRequirementsAndConstrains(source.getRequirementsAndConstrains()); - } +public class MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity extends MappingBase { + + @Override + public void doMapping(LicenseAgreementDescriptorDto source, LicenseAgreementEntity target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setLicenseTerm(new MapChoiceOrOtherDtoToChoiceOrOther().applyMapping(source.getLicenseTerm(), ChoiceOrOther.class)); + target.setRequirementsAndConstrains(source.getRequirementsAndConstrains()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementEntityToLicenseAgreementDescriptorDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementEntityToLicenseAgreementDescriptorDto.java index 2fd4f669cf..46de11f021 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementEntityToLicenseAgreementDescriptorDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseAgreementEntityToLicenseAgreementDescriptorDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; @@ -25,14 +24,13 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.ChoiceOrOtherDto; import org.openecomp.sdcrests.vendorlicense.types.LicenseAgreementDescriptorDto; -public class MapLicenseAgreementEntityToLicenseAgreementDescriptorDto - extends MappingBase { - @Override - public void doMapping(LicenseAgreementEntity source, LicenseAgreementDescriptorDto target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setLicenseTerm(new MapChoiceOrOtherToChoiceOrOtherDto() - .applyMapping(source.getLicenseTerm(), ChoiceOrOtherDto.class)); - target.setRequirementsAndConstrains(source.getRequirementsAndConstrains()); - } +public class MapLicenseAgreementEntityToLicenseAgreementDescriptorDto extends MappingBase { + + @Override + public void doMapping(LicenseAgreementEntity source, LicenseAgreementDescriptorDto target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setLicenseTerm(new MapChoiceOrOtherToChoiceOrOtherDto().applyMapping(source.getLicenseTerm(), ChoiceOrOtherDto.class)); + target.setRequirementsAndConstrains(source.getRequirementsAndConstrains()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto.java index c543cf402e..3690a7c5d3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; @@ -25,23 +24,23 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupEntityDto; import org.openecomp.sdcrests.vendorlicense.types.MultiChoiceOrOtherDto; -public class MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto - extends MappingBase { - @Override - public void doMapping(LicenseKeyGroupEntity source, LicenseKeyGroupEntityDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - target.setOperationalScope(new MapMultiChoiceOrOtherToMultiChoiceOrOtherDto() - .applyMapping(source.getOperationalScope(), MultiChoiceOrOtherDto.class)); - target.setReferencingFeatureGroups(source.getReferencingFeatureGroups()); - target.setStartDate(source.getStartDate()); - target.setExpiryDate(source.getExpiryDate()); - target.setThresholdUnits(source.getThresholdUnits()); - target.setThresholdValue(source.getThresholdValue()); - target.setIncrements(source.getIncrements()); - target.setVersionUUID(source.getVersionUuId()); - target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); - } +public class MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto extends MappingBase { + + @Override + public void doMapping(LicenseKeyGroupEntity source, LicenseKeyGroupEntityDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + target.setOperationalScope( + new MapMultiChoiceOrOtherToMultiChoiceOrOtherDto().applyMapping(source.getOperationalScope(), MultiChoiceOrOtherDto.class)); + target.setReferencingFeatureGroups(source.getReferencingFeatureGroups()); + target.setStartDate(source.getStartDate()); + target.setExpiryDate(source.getExpiryDate()); + target.setThresholdUnits(source.getThresholdUnits()); + target.setThresholdValue(source.getThresholdValue()); + target.setIncrements(source.getIncrements()); + target.setVersionUUID(source.getVersionUuId()); + target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity.java index 87eea4ba1e..ed0e79d0a5 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; @@ -25,20 +24,20 @@ import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.LicenseKeyGroupRequestDto; -public class MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity - extends MappingBase { - @Override - public void doMapping(LicenseKeyGroupRequestDto source, LicenseKeyGroupEntity target) { - target.setName(source.getName()); - target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - target.setOperationalScope(new MapMultiChoiceOrOtherDtoToMultiChoiceOrOther() - .applyMapping(source.getOperationalScope(), MultiChoiceOrOther.class)); - target.setStartDate(source.getStartDate()); - target.setExpiryDate(source.getExpiryDate()); - target.setThresholdUnits(source.getThresholdUnits()); - target.setThresholdValue(source.getThresholdValue()); - target.setIncrements(source.getIncrements()); - } +public class MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity extends MappingBase { + + @Override + public void doMapping(LicenseKeyGroupRequestDto source, LicenseKeyGroupEntity target) { + target.setName(source.getName()); + target.setManufacturerReferenceNumber(source.getManufacturerReferenceNumber()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + target.setOperationalScope( + new MapMultiChoiceOrOtherDtoToMultiChoiceOrOther().applyMapping(source.getOperationalScope(), MultiChoiceOrOther.class)); + target.setStartDate(source.getStartDate()); + target.setExpiryDate(source.getExpiryDate()); + target.setThresholdUnits(source.getThresholdUnits()); + target.setThresholdValue(source.getThresholdValue()); + target.setIncrements(source.getIncrements()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitCreationDto.java index ef4ae1ccdc..eb1a8a2def 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; import org.openecomp.sdcrests.mapping.MappingBase; -public class MapLimitEntityToLimitCreationDto extends - MappingBase { - @Override - public void doMapping(LimitEntity source, LimitCreationDto target) { - target.setLimitId(source.getId()); - } +public class MapLimitEntityToLimitCreationDto extends MappingBase { + + @Override + public void doMapping(LimitEntity source, LimitCreationDto target) { + target.setLimitId(source.getId()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitDto.java index b17a0e08d4..030fcc1c91 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitEntityToLimitDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; @@ -26,17 +25,16 @@ import org.openecomp.sdcrests.vendorlicense.types.LimitEntityDto; public class MapLimitEntityToLimitDto extends MappingBase { - @Override - public void doMapping(LimitEntity source, LimitEntityDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setMetric(source.getMetric()); - target.setAggregationFunction(source.getAggregationFunction() != null ? source - .getAggregationFunction().name() : null); - target.setTime(source.getTime()); - target.setType(source.getType() != null ? source.getType().name() : null); - target.setUnit(source.getUnit()); - target.setValue(source.getValue()); - } + @Override + public void doMapping(LimitEntity source, LimitEntityDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setMetric(source.getMetric()); + target.setAggregationFunction(source.getAggregationFunction() != null ? source.getAggregationFunction().name() : null); + target.setTime(source.getTime()); + target.setType(source.getType() != null ? source.getType().name() : null); + target.setUnit(source.getUnit()); + target.setValue(source.getValue()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitRequestDtoToLimitEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitRequestDtoToLimitEntity.java index 99f45bfc18..2de29c6e0c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitRequestDtoToLimitEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapLimitRequestDtoToLimitEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.common.errors.CoreException; @@ -32,11 +31,9 @@ import org.openecomp.sdc.vendorlicense.errors.VendorLicenseErrorCodes; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.LimitRequestDto; - public class MapLimitRequestDtoToLimitEntity extends MappingBase { - private static final Logger logger = - LoggerFactory.getLogger(MapLimitRequestDtoToLimitEntity.class); + private static final Logger logger = LoggerFactory.getLogger(MapLimitRequestDtoToLimitEntity.class); @Override public void doMapping(LimitRequestDto source, LimitEntity target) { @@ -49,27 +46,22 @@ public class MapLimitRequestDtoToLimitEntity extends MappingBase { +public class MapMultiChoiceOrOtherDtoToMultiChoiceOrOther extends MappingBase { - @Override - public void doMapping(MultiChoiceOrOtherDto source, MultiChoiceOrOther target) { - target.setChoices(source.getChoices()); - target.setOther(source.getOther()); - target.setResults(null); - } + @Override + public void doMapping(MultiChoiceOrOtherDto source, MultiChoiceOrOther target) { + target.setChoices(source.getChoices()); + target.setOther(source.getOther()); + target.setResults(null); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapMultiChoiceOrOtherToMultiChoiceOrOtherDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapMultiChoiceOrOtherToMultiChoiceOrOtherDto.java index 9649053fb4..93a2007897 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapMultiChoiceOrOtherToMultiChoiceOrOtherDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapMultiChoiceOrOtherToMultiChoiceOrOtherDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.MultiChoiceOrOtherDto; -public class MapMultiChoiceOrOtherToMultiChoiceOrOtherDto - extends MappingBase { +public class MapMultiChoiceOrOtherToMultiChoiceOrOtherDto extends MappingBase { - @Override - public void doMapping(MultiChoiceOrOther source, MultiChoiceOrOtherDto target) { - target.setChoices(source.getChoices()); - target.setOther(source.getOther()); - } + @Override + public void doMapping(MultiChoiceOrOther source, MultiChoiceOrOtherDto target) { + target.setChoices(source.getChoices()); + target.setOther(source.getOther()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelEntityToDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelEntityToDto.java index 7bdde1d592..5b0bfb7d73 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelEntityToDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelEntityToDto.java @@ -17,20 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelEntityDto; -public class MapVendorLicenseModelEntityToDto - extends MappingBase { - @Override - public void doMapping(VendorLicenseModelEntity source, VendorLicenseModelEntityDto target) { - target.setId(source.getId()); - target.setVendorName(source.getVendorName()); - target.setDescription(source.getDescription()); - target.setIconRef(source.getIconRef()); - } +public class MapVendorLicenseModelEntityToDto extends MappingBase { + + @Override + public void doMapping(VendorLicenseModelEntity source, VendorLicenseModelEntityDto target) { + target.setId(source.getId()); + target.setVendorName(source.getVendorName()); + target.setDescription(source.getDescription()); + target.setIconRef(source.getIconRef()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity.java index 593a4a37b0..2cbc81980a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/mapping/MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.mapping; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelRequestDto; -public class MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity - extends MappingBase { - @Override - public void doMapping(VendorLicenseModelRequestDto source, VendorLicenseModelEntity target) { - target.setVendorName(source.getVendorName()); - target.setDescription(source.getDescription()); - target.setIconRef(source.getIconRef()); - } +public class MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity extends MappingBase { + + @Override + public void doMapping(VendorLicenseModelRequestDto source, VendorLicenseModelEntity target) { + target.setVendorName(source.getVendorName()); + target.setDescription(source.getDescription()); + target.setIconRef(source.getIconRef()); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolLimitsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolLimitsImpl.java index 544c1d7331..38e0a78154 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolLimitsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolLimitsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; - +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; import org.openecomp.sdc.vendorlicense.VendorLicenseManagerFactory; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; @@ -37,126 +38,89 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("entitlementPoolLimits") @Scope(value = "prototype") public class EntitlementPoolLimitsImpl implements EntitlementPoolLimits { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); - - private static final String PARENT = "EntitlementPool"; - - @Override - public Response createLimit(LimitRequestDto request, - String vlmId, - String versionId, - String entitlementPoolId, - String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); - - LimitEntity limitEntity = - new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); - limitEntity.setVendorLicenseModelId(vlmId); - limitEntity.setVersion(version); - limitEntity.setEpLkgId(entitlementPoolId); - limitEntity.setParent(PARENT); - LimitEntity createdLimit = vendorLicenseManager.createLimit(limitEntity); - MapLimitEntityToLimitCreationDto mapper = new MapLimitEntityToLimitCreationDto(); - LimitCreationDto createdLimitDto = mapper.applyMapping(createdLimit, LimitCreationDto.class); - - return Response.ok(createdLimitDto != null ? createdLimitDto : null).build(); - } - - @Override - public Response listLimits(String vlmId, String versionId, String entitlementPoolId, String - user) { - Version version = new Version(versionId); - vendorLicenseManager - .getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); - - Collection limits = - vendorLicenseManager.listLimits(vlmId, version, entitlementPoolId); - - GenericCollectionWrapper result = new GenericCollectionWrapper<>(); - MapLimitEntityToLimitDto outputMapper = - new MapLimitEntityToLimitDto(); - for (LimitEntity limit : limits) { - result.add(outputMapper.applyMapping(limit, LimitEntityDto.class)); + private static final String PARENT = "EntitlementPool"; + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); + + @Override + public Response createLimit(LimitRequestDto request, String vlmId, String versionId, String entitlementPoolId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + LimitEntity limitEntity = new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); + limitEntity.setVendorLicenseModelId(vlmId); + limitEntity.setVersion(version); + limitEntity.setEpLkgId(entitlementPoolId); + limitEntity.setParent(PARENT); + LimitEntity createdLimit = vendorLicenseManager.createLimit(limitEntity); + MapLimitEntityToLimitCreationDto mapper = new MapLimitEntityToLimitCreationDto(); + LimitCreationDto createdLimitDto = mapper.applyMapping(createdLimit, LimitCreationDto.class); + return Response.ok(createdLimitDto != null ? createdLimitDto : null).build(); } - return Response.ok(result).build(); - } - - @Override - public Response getLimit(String vlmId, String versionId, String entitlementPoolId, - String limitId, String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); - LimitEntity limitInput = new LimitEntity(); - limitInput.setVendorLicenseModelId(vlmId); - limitInput.setVersion(version); - limitInput.setEpLkgId(entitlementPoolId); - limitInput.setId(limitId); - LimitEntity limit = vendorLicenseManager.getLimit(limitInput); - - LimitEntityDto entitlementPoolEntityDto = limit == null ? null : - new MapLimitEntityToLimitDto().applyMapping(limit, LimitEntityDto.class); - return Response.ok(entitlementPoolEntityDto).build(); - } - @Override - public Response updateLimit(LimitRequestDto request, - String vlmId, - String versionId, - String entitlementPoolId, - String limitId, - String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); - - LimitEntity limitEntity = - new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); - limitEntity.setVendorLicenseModelId(vlmId); - limitEntity.setVersion(version); - limitEntity.setEpLkgId(entitlementPoolId); - limitEntity.setId(limitId); - limitEntity.setParent(PARENT); - - vendorLicenseManager.updateLimit(limitEntity); - return Response.ok().build(); - } + @Override + public Response listLimits(String vlmId, String versionId, String entitlementPoolId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + Collection limits = vendorLicenseManager.listLimits(vlmId, version, entitlementPoolId); + GenericCollectionWrapper result = new GenericCollectionWrapper<>(); + MapLimitEntityToLimitDto outputMapper = new MapLimitEntityToLimitDto(); + for (LimitEntity limit : limits) { + result.add(outputMapper.applyMapping(limit, LimitEntityDto.class)); + } + return Response.ok(result).build(); + } - /** - * Delete entitlement pool. - * - * @param vlmId the vlm id - * @param entitlementPoolId the entitlement pool id - * @param limitId the limitId - * @param user the user - * @return the response - */ - public Response deleteLimit(String vlmId, String versionId, String entitlementPoolId, - String limitId, String user) { - Version version = new Version(versionId); - vendorLicenseManager.getEntitlementPool( - new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + @Override + public Response getLimit(String vlmId, String versionId, String entitlementPoolId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + LimitEntity limitInput = new LimitEntity(); + limitInput.setVendorLicenseModelId(vlmId); + limitInput.setVersion(version); + limitInput.setEpLkgId(entitlementPoolId); + limitInput.setId(limitId); + LimitEntity limit = vendorLicenseManager.getLimit(limitInput); + LimitEntityDto entitlementPoolEntityDto = limit == null ? null : new MapLimitEntityToLimitDto().applyMapping(limit, LimitEntityDto.class); + return Response.ok(entitlementPoolEntityDto).build(); + } - LimitEntity limitInput = new LimitEntity(); - limitInput.setVendorLicenseModelId(vlmId); - limitInput.setVersion(version); - limitInput.setEpLkgId(entitlementPoolId); - limitInput.setId(limitId); - limitInput.setParent(PARENT); + @Override + public Response updateLimit(LimitRequestDto request, String vlmId, String versionId, String entitlementPoolId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + LimitEntity limitEntity = new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); + limitEntity.setVendorLicenseModelId(vlmId); + limitEntity.setVersion(version); + limitEntity.setEpLkgId(entitlementPoolId); + limitEntity.setId(limitId); + limitEntity.setParent(PARENT); + vendorLicenseManager.updateLimit(limitEntity); + return Response.ok().build(); + } - vendorLicenseManager.deleteLimit(limitInput); - return Response.ok().build(); - } + /** + * Delete entitlement pool. + * + * @param vlmId the vlm id + * @param entitlementPoolId the entitlement pool id + * @param limitId the limitId + * @param user the user + * @return the response + */ + public Response deleteLimit(String vlmId, String versionId, String entitlementPoolId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getEntitlementPool(new EntitlementPoolEntity(vlmId, version, entitlementPoolId)); + LimitEntity limitInput = new LimitEntity(); + limitInput.setVendorLicenseModelId(vlmId); + limitInput.setVersion(version); + limitInput.setEpLkgId(entitlementPoolId); + limitInput.setId(limitId); + limitInput.setParent(PARENT); + vendorLicenseManager.deleteLimit(limitInput); + return Response.ok().build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolsImpl.java index 83519198b7..bff8c7a449 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/EntitlementPoolsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; import java.util.Comparator; @@ -42,115 +41,97 @@ import org.springframework.stereotype.Service; @Service("entitlementPools") @Scope(value = "prototype") public class EntitlementPoolsImpl implements EntitlementPools { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); - - /** - * List entitlement pools response. - * - * @param vlmId the vlm id - * @param versionId the version - * @param user the user - * @return the response - */ - public Response listEntitlementPools(String vlmId, String versionId, String user) { - MapEntitlementPoolEntityToEntitlementPoolEntityDto outputMapper = - new MapEntitlementPoolEntityToEntitlementPoolEntityDto(); + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); + /** + * List entitlement pools response. + * + * @param vlmId the vlm id + * @param versionId the version + * @param user the user + * @return the response + */ + public Response listEntitlementPools(String vlmId, String versionId, String user) { + MapEntitlementPoolEntityToEntitlementPoolEntityDto outputMapper = new MapEntitlementPoolEntityToEntitlementPoolEntityDto(); GenericCollectionWrapper result = new GenericCollectionWrapper<>( - vendorLicenseManager.listEntitlementPools(vlmId, new Version(versionId)).stream() - .sorted(Comparator.comparing(EntitlementPoolEntity::getName)) - .map(item -> outputMapper.applyMapping(item, EntitlementPoolEntityDto.class)) - .collect(Collectors.toList())); - + vendorLicenseManager.listEntitlementPools(vlmId, new Version(versionId)).stream() + .sorted(Comparator.comparing(EntitlementPoolEntity::getName)) + .map(item -> outputMapper.applyMapping(item, EntitlementPoolEntityDto.class)).collect(Collectors.toList())); return Response.ok(result).build(); } - /** - * Create entitlement pool response. - * - * @param request the request - * @param vlmId the vlm id - * @param user the user - * @return the response - */ - public Response createEntitlementPool(EntitlementPoolRequestDto request, String vlmId, - String versionId, String user) { - EntitlementPoolEntity entitlementPoolEntity = - new MapEntitlementPoolRequestDtoToEntitlementPoolEntity() + /** + * Create entitlement pool response. + * + * @param request the request + * @param vlmId the vlm id + * @param user the user + * @return the response + */ + public Response createEntitlementPool(EntitlementPoolRequestDto request, String vlmId, String versionId, String user) { + EntitlementPoolEntity entitlementPoolEntity = new MapEntitlementPoolRequestDtoToEntitlementPoolEntity() .applyMapping(request, EntitlementPoolEntity.class); - entitlementPoolEntity.setVendorLicenseModelId(vlmId); - entitlementPoolEntity.setVersion(new Version(versionId)); - - EntitlementPoolEntity createdEntitlementPool = - vendorLicenseManager.createEntitlementPool(entitlementPoolEntity); - StringWrapperResponse result = - createdEntitlementPool != null ? new StringWrapperResponse(createdEntitlementPool.getId()) - : null; - return Response.ok(result).build(); - } + entitlementPoolEntity.setVendorLicenseModelId(vlmId); + entitlementPoolEntity.setVersion(new Version(versionId)); + EntitlementPoolEntity createdEntitlementPool = vendorLicenseManager.createEntitlementPool(entitlementPoolEntity); + StringWrapperResponse result = createdEntitlementPool != null ? new StringWrapperResponse(createdEntitlementPool.getId()) : null; + return Response.ok(result).build(); + } - /** - * Update entitlement pool response. - * - * @param request the request - * @param vlmId the vlm id - * @param entitlementPoolId the entitlement pool id - * @param user the user - * @return the response - */ - public Response updateEntitlementPool(EntitlementPoolRequestDto request, String vlmId, - String versionId, String entitlementPoolId, String user) { - EntitlementPoolEntity entitlementPoolEntity = - new MapEntitlementPoolRequestDtoToEntitlementPoolEntity() + /** + * Update entitlement pool response. + * + * @param request the request + * @param vlmId the vlm id + * @param entitlementPoolId the entitlement pool id + * @param user the user + * @return the response + */ + public Response updateEntitlementPool(EntitlementPoolRequestDto request, String vlmId, String versionId, String entitlementPoolId, String user) { + EntitlementPoolEntity entitlementPoolEntity = new MapEntitlementPoolRequestDtoToEntitlementPoolEntity() .applyMapping(request, EntitlementPoolEntity.class); - entitlementPoolEntity.setVendorLicenseModelId(vlmId); - entitlementPoolEntity.setVersion(new Version(versionId)); - entitlementPoolEntity.setId(entitlementPoolId); - - vendorLicenseManager.updateEntitlementPool(entitlementPoolEntity); - return Response.ok().build(); - } - - /** - * Gets entitlement pool. - * - * @param vlmId the vlm id - * @param versionId the version id - * @param entitlementPoolId the entitlement pool id - * @param user the user - * @return the entitlement pool - */ - public Response getEntitlementPool(String vlmId, String versionId, String entitlementPoolId, - String user) { - EntitlementPoolEntity epInput = new EntitlementPoolEntity(); - epInput.setVendorLicenseModelId(vlmId); - epInput.setVersion(new Version(versionId)); - epInput.setId(entitlementPoolId); - EntitlementPoolEntity entitlementPool = vendorLicenseManager.getEntitlementPool(epInput); + entitlementPoolEntity.setVendorLicenseModelId(vlmId); + entitlementPoolEntity.setVersion(new Version(versionId)); + entitlementPoolEntity.setId(entitlementPoolId); + vendorLicenseManager.updateEntitlementPool(entitlementPoolEntity); + return Response.ok().build(); + } - EntitlementPoolEntityDto entitlementPoolEntityDto = entitlementPool == null ? null : - new MapEntitlementPoolEntityToEntitlementPoolEntityDto() - .applyMapping(entitlementPool, EntitlementPoolEntityDto.class); - return Response.ok(entitlementPoolEntityDto).build(); - } + /** + * Gets entitlement pool. + * + * @param vlmId the vlm id + * @param versionId the version id + * @param entitlementPoolId the entitlement pool id + * @param user the user + * @return the entitlement pool + */ + public Response getEntitlementPool(String vlmId, String versionId, String entitlementPoolId, String user) { + EntitlementPoolEntity epInput = new EntitlementPoolEntity(); + epInput.setVendorLicenseModelId(vlmId); + epInput.setVersion(new Version(versionId)); + epInput.setId(entitlementPoolId); + EntitlementPoolEntity entitlementPool = vendorLicenseManager.getEntitlementPool(epInput); + EntitlementPoolEntityDto entitlementPoolEntityDto = entitlementPool == null ? null + : new MapEntitlementPoolEntityToEntitlementPoolEntityDto().applyMapping(entitlementPool, EntitlementPoolEntityDto.class); + return Response.ok(entitlementPoolEntityDto).build(); + } - /** - * Delete entitlement pool response. - * - * @param vlmId the vlm id - * @param entitlementPoolId the entitlement pool id - * @param user the user - * @return the response - */ - public Response deleteEntitlementPool(String vlmId, String versionId, String entitlementPoolId, - String user) { - EntitlementPoolEntity epInput = new EntitlementPoolEntity(); - epInput.setVendorLicenseModelId(vlmId); - epInput.setId(entitlementPoolId); - epInput.setVersion(new Version(versionId)); - vendorLicenseManager.deleteEntitlementPool(epInput); - return Response.ok().build(); - } + /** + * Delete entitlement pool response. + * + * @param vlmId the vlm id + * @param entitlementPoolId the entitlement pool id + * @param user the user + * @return the response + */ + public Response deleteEntitlementPool(String vlmId, String versionId, String entitlementPoolId, String user) { + EntitlementPoolEntity epInput = new EntitlementPoolEntity(); + epInput.setVendorLicenseModelId(vlmId); + epInput.setId(entitlementPoolId); + epInput.setVersion(new Version(versionId)); + vendorLicenseManager.deleteEntitlementPool(epInput); + return Response.ok().build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/FeatureGroupsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/FeatureGroupsImpl.java index 4ea35d321d..a945784213 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/FeatureGroupsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/FeatureGroupsImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; import java.util.Comparator; @@ -54,104 +53,75 @@ import org.springframework.stereotype.Service; @Scope(value = "prototype") public class FeatureGroupsImpl implements FeatureGroups { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); @Override public Response listFeatureGroups(String vlmId, String versionId, String user) { - - MapFeatureGroupEntityToFeatureGroupDescriptorDto outputMapper = - new MapFeatureGroupEntityToFeatureGroupDescriptorDto(); - + MapFeatureGroupEntityToFeatureGroupDescriptorDto outputMapper = new MapFeatureGroupEntityToFeatureGroupDescriptorDto(); GenericCollectionWrapper results = new GenericCollectionWrapper<>( - vendorLicenseManager.listFeatureGroups(vlmId, new Version(versionId)).stream() - .sorted(Comparator.comparing(FeatureGroupEntity::getName)) - .map(fg -> getFeatureGroupEntityDto(outputMapper,fg)).collect(Collectors.toList())); - + vendorLicenseManager.listFeatureGroups(vlmId, new Version(versionId)).stream().sorted(Comparator.comparing(FeatureGroupEntity::getName)) + .map(fg -> getFeatureGroupEntityDto(outputMapper, fg)).collect(Collectors.toList())); return Response.ok(results).build(); } @Override - public Response createFeatureGroup(FeatureGroupRequestDto request, String vlmId, String versionId, - String user) { + public Response createFeatureGroup(FeatureGroupRequestDto request, String vlmId, String versionId, String user) { FeatureGroupEntity featureGroupEntity = new MapFeatureGroupDescriptorDtoToFeatureGroupEntity() - .applyMapping(request, FeatureGroupEntity.class); + .applyMapping(request, FeatureGroupEntity.class); featureGroupEntity.setVendorLicenseModelId(vlmId); featureGroupEntity.setVersion(new Version(versionId)); featureGroupEntity.setLicenseKeyGroupIds(request.getAddedLicenseKeyGroupsIds()); featureGroupEntity.setEntitlementPoolIds(request.getAddedEntitlementPoolsIds()); - - FeatureGroupEntity createdFeatureGroup = - vendorLicenseManager.createFeatureGroup(featureGroupEntity); - - StringWrapperResponse result = - createdFeatureGroup != null ? new StringWrapperResponse(createdFeatureGroup.getId()) : null; + FeatureGroupEntity createdFeatureGroup = vendorLicenseManager.createFeatureGroup(featureGroupEntity); + StringWrapperResponse result = createdFeatureGroup != null ? new StringWrapperResponse(createdFeatureGroup.getId()) : null; return Response.ok(result).build(); } @Override - public Response updateFeatureGroup(FeatureGroupUpdateRequestDto request, String vlmId, - String versionId, String featureGroupId, String user) { + public Response updateFeatureGroup(FeatureGroupUpdateRequestDto request, String vlmId, String versionId, String featureGroupId, String user) { FeatureGroupEntity featureGroupEntity = new MapFeatureGroupDescriptorDtoToFeatureGroupEntity() - .applyMapping(request, FeatureGroupEntity.class); + .applyMapping(request, FeatureGroupEntity.class); featureGroupEntity.setVendorLicenseModelId(vlmId); featureGroupEntity.setVersion(new Version(versionId)); featureGroupEntity.setId(featureGroupId); - - vendorLicenseManager - .updateFeatureGroup(featureGroupEntity, request.getAddedLicenseKeyGroupsIds(), - request.getRemovedLicenseKeyGroupsIds(), request.getAddedEntitlementPoolsIds(), - request.getRemovedEntitlementPoolsIds()); + vendorLicenseManager.updateFeatureGroup(featureGroupEntity, request.getAddedLicenseKeyGroupsIds(), request.getRemovedLicenseKeyGroupsIds(), + request.getAddedEntitlementPoolsIds(), request.getRemovedEntitlementPoolsIds()); return Response.ok().build(); } @Override - public Response getFeatureGroup(String vlmId, String versionId, String featureGroupId, - String user) { + public Response getFeatureGroup(String vlmId, String versionId, String featureGroupId, String user) { FeatureGroupEntity fgInput = new FeatureGroupEntity(); fgInput.setVendorLicenseModelId(vlmId); fgInput.setVersion(new Version(versionId)); fgInput.setId(featureGroupId); FeatureGroupModel featureGroupModel = vendorLicenseManager.getFeatureGroupModel(fgInput); - if (featureGroupModel == null) { return Response.ok().build(); } - FeatureGroupModelDto fgmDto = new FeatureGroupModelDto(); fgmDto.setId(featureGroupModel.getFeatureGroup().getId()); - fgmDto.setReferencingLicenseAgreements( - featureGroupModel.getFeatureGroup().getReferencingLicenseAgreements()); - new MapFeatureGroupEntityToFeatureGroupDescriptorDto() - .doMapping(featureGroupModel.getFeatureGroup(), fgmDto); - + fgmDto.setReferencingLicenseAgreements(featureGroupModel.getFeatureGroup().getReferencingLicenseAgreements()); + new MapFeatureGroupEntityToFeatureGroupDescriptorDto().doMapping(featureGroupModel.getFeatureGroup(), fgmDto); if (!CollectionUtils.isEmpty(featureGroupModel.getLicenseKeyGroups())) { fgmDto.setLicenseKeyGroups(new HashSet<>()); - - MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto lkgMapper = - new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(); + MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto lkgMapper = new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(); for (LicenseKeyGroupEntity lkg : featureGroupModel.getLicenseKeyGroups()) { - fgmDto.getLicenseKeyGroups() - .add(lkgMapper.applyMapping(lkg, LicenseKeyGroupEntityDto.class)); + fgmDto.getLicenseKeyGroups().add(lkgMapper.applyMapping(lkg, LicenseKeyGroupEntityDto.class)); } } - if (!CollectionUtils.isEmpty(featureGroupModel.getEntitlementPools())) { fgmDto.setEntitlementPools(new HashSet<>()); - - MapEntitlementPoolEntityToEntitlementPoolEntityDto epMapper = - new MapEntitlementPoolEntityToEntitlementPoolEntityDto(); + MapEntitlementPoolEntityToEntitlementPoolEntityDto epMapper = new MapEntitlementPoolEntityToEntitlementPoolEntityDto(); for (EntitlementPoolEntity ep : featureGroupModel.getEntitlementPools()) { fgmDto.getEntitlementPools().add(epMapper.applyMapping(ep, EntitlementPoolEntityDto.class)); - } } return Response.ok(fgmDto).build(); } @Override - public Response deleteFeatureGroup(String vlmId, String versionId, String featureGroupId, - String user) { + public Response deleteFeatureGroup(String vlmId, String versionId, String featureGroupId, String user) { FeatureGroupEntity fgInput = new FeatureGroupEntity(); fgInput.setVendorLicenseModelId(vlmId); fgInput.setVersion(new Version(versionId)); @@ -160,7 +130,7 @@ public class FeatureGroupsImpl implements FeatureGroups { return Response.ok().build(); } - private FeatureGroupEntityDto getFeatureGroupEntityDto(MapFeatureGroupEntityToFeatureGroupDescriptorDto mapper,FeatureGroupEntity fg) { + private FeatureGroupEntityDto getFeatureGroupEntityDto(MapFeatureGroupEntityToFeatureGroupDescriptorDto mapper, FeatureGroupEntity fg) { FeatureGroupEntityDto fgDto = new FeatureGroupEntityDto(); fgDto.setId(fg.getId()); fgDto.setLicenseKeyGroupsIds(fg.getLicenseKeyGroupIds()); @@ -169,5 +139,4 @@ public class FeatureGroupsImpl implements FeatureGroups { mapper.doMapping(fg, fgDto); return fgDto; } - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseAgreementsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseAgreementsImpl.java index 7c0539931b..fb67b237f0 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseAgreementsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseAgreementsImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; import java.util.Comparator; @@ -51,8 +50,7 @@ import org.springframework.stereotype.Service; @Scope(value = "prototype") public class LicenseAgreementsImpl implements LicenseAgreements { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); /** * List license agreements response. @@ -63,20 +61,14 @@ public class LicenseAgreementsImpl implements LicenseAgreements { * @return the response */ public Response listLicenseAgreements(String vlmId, String versionId, String user) { - - MapLicenseAgreementEntityToLicenseAgreementDescriptorDto outputMapper = - new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto(); - + MapLicenseAgreementEntityToLicenseAgreementDescriptorDto outputMapper = new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto(); GenericCollectionWrapper results = new GenericCollectionWrapper<>( - vendorLicenseManager.listLicenseAgreements(vlmId, new Version(versionId)).stream() - .sorted(Comparator.comparing(LicenseAgreementEntity::getName)) - .map(lae -> getLicenseAgreementEntityDto(outputMapper, lae)) - .collect(Collectors.toList())); - + vendorLicenseManager.listLicenseAgreements(vlmId, new Version(versionId)).stream() + .sorted(Comparator.comparing(LicenseAgreementEntity::getName)).map(lae -> getLicenseAgreementEntityDto(outputMapper, lae)) + .collect(Collectors.toList())); return Response.ok(results).build(); } - /** * Create license agreement response. * @@ -85,20 +77,14 @@ public class LicenseAgreementsImpl implements LicenseAgreements { * @param user the user * @return the response */ - public Response createLicenseAgreement(LicenseAgreementRequestDto request, String vlmId, - String versionId, String user) { - LicenseAgreementEntity licenseAgreementEntity = - new MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity() - .applyMapping(request, LicenseAgreementEntity.class); + public Response createLicenseAgreement(LicenseAgreementRequestDto request, String vlmId, String versionId, String user) { + LicenseAgreementEntity licenseAgreementEntity = new MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity() + .applyMapping(request, LicenseAgreementEntity.class); licenseAgreementEntity.setVendorLicenseModelId(vlmId); licenseAgreementEntity.setVersion(new Version(versionId)); licenseAgreementEntity.setFeatureGroupIds(request.getAddedFeatureGroupsIds()); - - LicenseAgreementEntity createdLicenseAgreement = - vendorLicenseManager.createLicenseAgreement(licenseAgreementEntity); - StringWrapperResponse result = - createdLicenseAgreement != null ? new StringWrapperResponse(createdLicenseAgreement.getId()) - : null; + LicenseAgreementEntity createdLicenseAgreement = vendorLicenseManager.createLicenseAgreement(licenseAgreementEntity); + StringWrapperResponse result = createdLicenseAgreement != null ? new StringWrapperResponse(createdLicenseAgreement.getId()) : null; return Response.ok(result).build(); } @@ -111,18 +97,14 @@ public class LicenseAgreementsImpl implements LicenseAgreements { * @param user the user * @return the response */ - public Response updateLicenseAgreement(LicenseAgreementUpdateRequestDto request, String vlmId, - String versionId, String licenseAgreementId, String user) { - LicenseAgreementEntity licenseAgreementEntity = - new MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity() - .applyMapping(request, LicenseAgreementEntity.class); + public Response updateLicenseAgreement(LicenseAgreementUpdateRequestDto request, String vlmId, String versionId, String licenseAgreementId, + String user) { + LicenseAgreementEntity licenseAgreementEntity = new MapLicenseAgreementDescriptorDtoToLicenseAgreementEntity() + .applyMapping(request, LicenseAgreementEntity.class); licenseAgreementEntity.setVendorLicenseModelId(vlmId); licenseAgreementEntity.setVersion(new Version(versionId)); licenseAgreementEntity.setId(licenseAgreementId); - - vendorLicenseManager - .updateLicenseAgreement(licenseAgreementEntity, request.getAddedFeatureGroupsIds(), - request.getRemovedFeatureGroupsIds()); + vendorLicenseManager.updateLicenseAgreement(licenseAgreementEntity, request.getAddedFeatureGroupsIds(), request.getRemovedFeatureGroupsIds()); return Response.ok().build(); } @@ -135,32 +117,24 @@ public class LicenseAgreementsImpl implements LicenseAgreements { * @param user the user * @return the license agreement */ - public Response getLicenseAgreement(String vlmId, String versionId, String licenseAgreementId, - String user) { + public Response getLicenseAgreement(String vlmId, String versionId, String licenseAgreementId, String user) { LicenseAgreementModel licenseAgreementModel = vendorLicenseManager - .getLicenseAgreementModel(vlmId, new Version(versionId), licenseAgreementId); - + .getLicenseAgreementModel(vlmId, new Version(versionId), licenseAgreementId); if (licenseAgreementModel == null) { return Response.ok().build(); } - LicenseAgreementModelDto lamDto = new LicenseAgreementModelDto(); lamDto.setId(licenseAgreementModel.getLicenseAgreement().getId()); - new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto() - .doMapping(licenseAgreementModel.getLicenseAgreement(), lamDto); - + new MapLicenseAgreementEntityToLicenseAgreementDescriptorDto().doMapping(licenseAgreementModel.getLicenseAgreement(), lamDto); if (!CollectionUtils.isEmpty(licenseAgreementModel.getFeatureGroups())) { lamDto.setFeatureGroups(new HashSet<>()); - - MapFeatureGroupEntityToFeatureGroupDescriptorDto fgMapper = - new MapFeatureGroupEntityToFeatureGroupDescriptorDto(); + MapFeatureGroupEntityToFeatureGroupDescriptorDto fgMapper = new MapFeatureGroupEntityToFeatureGroupDescriptorDto(); for (FeatureGroupEntity fg : licenseAgreementModel.getFeatureGroups()) { FeatureGroupEntityDto fgeDto = new FeatureGroupEntityDto(); fgeDto.setId(fg.getId()); fgeDto.setEntitlementPoolsIds(fg.getEntitlementPoolIds()); fgeDto.setLicenseKeyGroupsIds(fg.getLicenseKeyGroupIds()); fgMapper.doMapping(fg, fgeDto); - lamDto.getFeatureGroups().add(fgeDto); } } @@ -176,14 +150,13 @@ public class LicenseAgreementsImpl implements LicenseAgreements { * @param user the user * @return the response */ - public Response deleteLicenseAgreement(String vlmId, String versionId, String licenseAgreementId, - String user) { + public Response deleteLicenseAgreement(String vlmId, String versionId, String licenseAgreementId, String user) { vendorLicenseManager.deleteLicenseAgreement(vlmId, new Version(versionId), licenseAgreementId); return Response.ok().build(); } - private LicenseAgreementEntityDto getLicenseAgreementEntityDto( - MapLicenseAgreementEntityToLicenseAgreementDescriptorDto mapper, LicenseAgreementEntity lae) { + private LicenseAgreementEntityDto getLicenseAgreementEntityDto(MapLicenseAgreementEntityToLicenseAgreementDescriptorDto mapper, + LicenseAgreementEntity lae) { LicenseAgreementEntityDto laeDto = new LicenseAgreementEntityDto(); laeDto.setId(lae.getId()); laeDto.setFeatureGroupsIds(lae.getFeatureGroupIds()); diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupLimitsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupLimitsImpl.java index 14491b0e6a..7d4f1f7679 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupLimitsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupLimitsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; import org.openecomp.sdc.vendorlicense.VendorLicenseManagerFactory; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; @@ -36,126 +38,89 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("licenseKeyGroupLimits") @Scope(value = "prototype") public class LicenseKeyGroupLimitsImpl implements LicenseKeyGroupLimits { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); - - private static final String PARENT = "LicenseKeyGroup"; - - - @Override - public Response createLimit(LimitRequestDto request, - String vlmId, - String versionId, - String licenseKeyGroupId, - String user) { - Version version = new Version(versionId); - vendorLicenseManager.getLicenseKeyGroup( - new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); - - LimitEntity limitEntity = - new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); - limitEntity.setVendorLicenseModelId(vlmId); - limitEntity.setVersion(version); - limitEntity.setEpLkgId(licenseKeyGroupId); - limitEntity.setParent(PARENT); - LimitEntity createdLimit = vendorLicenseManager.createLimit(limitEntity); - MapLimitEntityToLimitCreationDto mapper = new MapLimitEntityToLimitCreationDto(); - LimitCreationDto createdLimitDto = mapper.applyMapping(createdLimit, LimitCreationDto.class); - return Response.ok(createdLimitDto != null ? createdLimitDto : null).build(); - } - - @Override - public Response listLimits(String vlmId, String versionId, String licenseKeyGroupId, - String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); - - Collection limits = - vendorLicenseManager.listLimits(vlmId, version, licenseKeyGroupId); - - GenericCollectionWrapper result = new GenericCollectionWrapper<>(); - MapLimitEntityToLimitDto outputMapper = - new MapLimitEntityToLimitDto(); - for (LimitEntity limit : limits) { - result.add(outputMapper.applyMapping(limit, LimitEntityDto.class)); + private static final String PARENT = "LicenseKeyGroup"; + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); + + @Override + public Response createLimit(LimitRequestDto request, String vlmId, String versionId, String licenseKeyGroupId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); + LimitEntity limitEntity = new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); + limitEntity.setVendorLicenseModelId(vlmId); + limitEntity.setVersion(version); + limitEntity.setEpLkgId(licenseKeyGroupId); + limitEntity.setParent(PARENT); + LimitEntity createdLimit = vendorLicenseManager.createLimit(limitEntity); + MapLimitEntityToLimitCreationDto mapper = new MapLimitEntityToLimitCreationDto(); + LimitCreationDto createdLimitDto = mapper.applyMapping(createdLimit, LimitCreationDto.class); + return Response.ok(createdLimitDto != null ? createdLimitDto : null).build(); } - return Response.ok(result).build(); - } - - @Override - public Response updateLimit(LimitRequestDto request, - String vlmId, - String versionId, - String licenseKeyGroupId, - String limitId, - String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); - - LimitEntity limitEntity = - new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); - limitEntity.setVendorLicenseModelId(vlmId); - limitEntity.setVersion(version); - limitEntity.setEpLkgId(licenseKeyGroupId); - limitEntity.setId(limitId); - limitEntity.setParent(PARENT); - - vendorLicenseManager.updateLimit(limitEntity); - return Response.ok().build(); - } - /** - * Delete License Key Group. - * - * @param vlmId the vlm id - * @param licenseKeyGroupId the license Key Group id - * @param limitId the limitId - * @param user the user - * @return the response - */ - public Response deleteLimit(String vlmId, String versionId, String licenseKeyGroupId, - String limitId, String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); - - LimitEntity limitInput = new LimitEntity(); - limitInput.setVendorLicenseModelId(vlmId); - limitInput.setVersion(version); - limitInput.setEpLkgId(licenseKeyGroupId); - limitInput.setId(limitId); - limitInput.setParent(PARENT); + @Override + public Response listLimits(String vlmId, String versionId, String licenseKeyGroupId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); + Collection limits = vendorLicenseManager.listLimits(vlmId, version, licenseKeyGroupId); + GenericCollectionWrapper result = new GenericCollectionWrapper<>(); + MapLimitEntityToLimitDto outputMapper = new MapLimitEntityToLimitDto(); + for (LimitEntity limit : limits) { + result.add(outputMapper.applyMapping(limit, LimitEntityDto.class)); + } + return Response.ok(result).build(); + } - vendorLicenseManager.deleteLimit(limitInput); - return Response.ok().build(); - } + @Override + public Response updateLimit(LimitRequestDto request, String vlmId, String versionId, String licenseKeyGroupId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); + LimitEntity limitEntity = new MapLimitRequestDtoToLimitEntity().applyMapping(request, LimitEntity.class); + limitEntity.setVendorLicenseModelId(vlmId); + limitEntity.setVersion(version); + limitEntity.setEpLkgId(licenseKeyGroupId); + limitEntity.setId(limitId); + limitEntity.setParent(PARENT); + vendorLicenseManager.updateLimit(limitEntity); + return Response.ok().build(); + } - @Override - public Response getLimit(String vlmId, String versionId, String licenseKeyGroupId, - String limitId, String user) { - Version version = new Version(versionId); - vendorLicenseManager - .getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); - LimitEntity limitInput = new LimitEntity(); - limitInput.setVendorLicenseModelId(vlmId); - limitInput.setVersion(version); - limitInput.setEpLkgId(licenseKeyGroupId); - limitInput.setId(limitId); - LimitEntity limit = vendorLicenseManager.getLimit(limitInput); + /** + * Delete License Key Group. + * + * @param vlmId the vlm id + * @param licenseKeyGroupId the license Key Group id + * @param limitId the limitId + * @param user the user + * @return the response + */ + public Response deleteLimit(String vlmId, String versionId, String licenseKeyGroupId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); + LimitEntity limitInput = new LimitEntity(); + limitInput.setVendorLicenseModelId(vlmId); + limitInput.setVersion(version); + limitInput.setEpLkgId(licenseKeyGroupId); + limitInput.setId(limitId); + limitInput.setParent(PARENT); + vendorLicenseManager.deleteLimit(limitInput); + return Response.ok().build(); + } - LimitEntityDto entitlementPoolEntityDto = limit == null ? null - : new MapLimitEntityToLimitDto().applyMapping(limit, LimitEntityDto.class); - return Response.ok(entitlementPoolEntityDto).build(); - } + @Override + public Response getLimit(String vlmId, String versionId, String licenseKeyGroupId, String limitId, String user) { + Version version = new Version(versionId); + vendorLicenseManager.getLicenseKeyGroup(new LicenseKeyGroupEntity(vlmId, version, licenseKeyGroupId)); + LimitEntity limitInput = new LimitEntity(); + limitInput.setVendorLicenseModelId(vlmId); + limitInput.setVersion(version); + limitInput.setEpLkgId(licenseKeyGroupId); + limitInput.setId(limitId); + LimitEntity limit = vendorLicenseManager.getLimit(limitInput); + LimitEntityDto entitlementPoolEntityDto = limit == null ? null : new MapLimitEntityToLimitDto().applyMapping(limit, LimitEntityDto.class); + return Response.ok(entitlementPoolEntityDto).build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupsImpl.java index 3edee02080..f7ddc25eba 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/LicenseKeyGroupsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.rest.services; import java.util.Comparator; import java.util.stream.Collectors; -import java.util.stream.Stream; import javax.inject.Named; import javax.ws.rs.core.Response; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; @@ -45,116 +43,97 @@ import org.springframework.validation.annotation.Validated; @Scope(value = "prototype") @Validated public class LicenseKeyGroupsImpl implements LicenseKeyGroups { - private VendorLicenseManager vendorLicenseManager = - VendorLicenseManagerFactory.getInstance().createInterface(); - - /** - * List license key groups response. - * - * @param vlmId the vlm id - * @param versionId the version - * @param user the user - * @return the response - */ - public Response listLicenseKeyGroups(String vlmId, String versionId, String user) { - MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto outputMapper = - new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(); + private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); - GenericCollectionWrapper result = new GenericCollectionWrapper<>( + /** + * List license key groups response. + * + * @param vlmId the vlm id + * @param versionId the version + * @param user the user + * @return the response + */ + public Response listLicenseKeyGroups(String vlmId, String versionId, String user) { + MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto outputMapper = new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto(); + GenericCollectionWrapper result = new GenericCollectionWrapper<>( vendorLicenseManager.listLicenseKeyGroups(vlmId, new Version(versionId)).stream() - .sorted(Comparator.comparing(LicenseKeyGroupEntity::getName)) - .map(item -> outputMapper.applyMapping(item, LicenseKeyGroupEntityDto.class)) - .collect(Collectors.toList())); - - return Response.ok(result).build(); - } + .sorted(Comparator.comparing(LicenseKeyGroupEntity::getName)) + .map(item -> outputMapper.applyMapping(item, LicenseKeyGroupEntityDto.class)).collect(Collectors.toList())); + return Response.ok(result).build(); + } - /** - * Create license key group response. - * - * @param request the request - * @param vlmId the vlm id - * @param user the user - * @return the response - */ - public Response createLicenseKeyGroup(LicenseKeyGroupRequestDto request, String vlmId, - String versionId, String user) { - LicenseKeyGroupEntity licenseKeyGroupEntity = - new MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity() + /** + * Create license key group response. + * + * @param request the request + * @param vlmId the vlm id + * @param user the user + * @return the response + */ + public Response createLicenseKeyGroup(LicenseKeyGroupRequestDto request, String vlmId, String versionId, String user) { + LicenseKeyGroupEntity licenseKeyGroupEntity = new MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity() .applyMapping(request, LicenseKeyGroupEntity.class); - licenseKeyGroupEntity.setVendorLicenseModelId(vlmId); - licenseKeyGroupEntity.setVersion(new Version(versionId)); + licenseKeyGroupEntity.setVendorLicenseModelId(vlmId); + licenseKeyGroupEntity.setVersion(new Version(versionId)); + LicenseKeyGroupEntity createdLicenseKeyGroup = vendorLicenseManager.createLicenseKeyGroup(licenseKeyGroupEntity); + StringWrapperResponse result = createdLicenseKeyGroup != null ? new StringWrapperResponse(createdLicenseKeyGroup.getId()) : null; + return Response.ok(result).build(); + } - LicenseKeyGroupEntity createdLicenseKeyGroup = - vendorLicenseManager.createLicenseKeyGroup(licenseKeyGroupEntity); - StringWrapperResponse result = - createdLicenseKeyGroup != null ? new StringWrapperResponse(createdLicenseKeyGroup.getId()) - : null; - return Response.ok(result).build(); - } - - /** - * Update license key group response. - * - * @param request the request - * @param vlmId the vlm id - * @param licenseKeyGroupId the license key group id - * @param user the user - * @return the response - */ - public Response updateLicenseKeyGroup(LicenseKeyGroupRequestDto request, String vlmId, - String versionId, - String licenseKeyGroupId, String user) { - LicenseKeyGroupEntity licenseKeyGroupEntity = - new MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity() + /** + * Update license key group response. + * + * @param request the request + * @param vlmId the vlm id + * @param licenseKeyGroupId the license key group id + * @param user the user + * @return the response + */ + public Response updateLicenseKeyGroup(LicenseKeyGroupRequestDto request, String vlmId, String versionId, String licenseKeyGroupId, String user) { + LicenseKeyGroupEntity licenseKeyGroupEntity = new MapLicenseKeyGroupRequestDtoToLicenseKeyGroupEntity() .applyMapping(request, LicenseKeyGroupEntity.class); - licenseKeyGroupEntity.setVendorLicenseModelId(vlmId); - licenseKeyGroupEntity.setVersion(new Version(versionId)); - licenseKeyGroupEntity.setId(licenseKeyGroupId); - - vendorLicenseManager.updateLicenseKeyGroup(licenseKeyGroupEntity); - return Response.ok().build(); - } - - /** - * Gets license key group. - * - * @param vlmId the vlm id - * @param versionId the version - * @param licenseKeyGroupId the license key group id - * @param user the user - * @return the license key group - */ - public Response getLicenseKeyGroup(String vlmId, String versionId, String licenseKeyGroupId, - String user) { - LicenseKeyGroupEntity lkgInput = new LicenseKeyGroupEntity(); - lkgInput.setVendorLicenseModelId(vlmId); - lkgInput.setVersion(new Version(versionId)); - lkgInput.setId(licenseKeyGroupId); - LicenseKeyGroupEntity licenseKeyGroup = vendorLicenseManager.getLicenseKeyGroup(lkgInput); + licenseKeyGroupEntity.setVendorLicenseModelId(vlmId); + licenseKeyGroupEntity.setVersion(new Version(versionId)); + licenseKeyGroupEntity.setId(licenseKeyGroupId); + vendorLicenseManager.updateLicenseKeyGroup(licenseKeyGroupEntity); + return Response.ok().build(); + } - LicenseKeyGroupEntityDto licenseKeyGroupEntityDto = licenseKeyGroup == null ? null : - new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto() - .applyMapping(licenseKeyGroup, LicenseKeyGroupEntityDto.class); - return Response.ok(licenseKeyGroupEntityDto).build(); - } + /** + * Gets license key group. + * + * @param vlmId the vlm id + * @param versionId the version + * @param licenseKeyGroupId the license key group id + * @param user the user + * @return the license key group + */ + public Response getLicenseKeyGroup(String vlmId, String versionId, String licenseKeyGroupId, String user) { + LicenseKeyGroupEntity lkgInput = new LicenseKeyGroupEntity(); + lkgInput.setVendorLicenseModelId(vlmId); + lkgInput.setVersion(new Version(versionId)); + lkgInput.setId(licenseKeyGroupId); + LicenseKeyGroupEntity licenseKeyGroup = vendorLicenseManager.getLicenseKeyGroup(lkgInput); + LicenseKeyGroupEntityDto licenseKeyGroupEntityDto = licenseKeyGroup == null ? null + : new MapLicenseKeyGroupEntityToLicenseKeyGroupEntityDto().applyMapping(licenseKeyGroup, LicenseKeyGroupEntityDto.class); + return Response.ok(licenseKeyGroupEntityDto).build(); + } - /** - * Delete license key group response. - * - * @param vlmId the vlm id - * @param licenseKeyGroupId the license key group id - * @param user the user - * @return the response - */ - public Response deleteLicenseKeyGroup(String vlmId, String versionId, String licenseKeyGroupId, - String user) { - LicenseKeyGroupEntity lkgInput = new LicenseKeyGroupEntity(); - lkgInput.setVendorLicenseModelId(vlmId); - lkgInput.setVersion(new Version(versionId)); - lkgInput.setId(licenseKeyGroupId); - vendorLicenseManager.deleteLicenseKeyGroup(lkgInput); - return Response.ok().build(); - } + /** + * Delete license key group response. + * + * @param vlmId the vlm id + * @param licenseKeyGroupId the license key group id + * @param user the user + * @return the response + */ + public Response deleteLicenseKeyGroup(String vlmId, String versionId, String licenseKeyGroupId, String user) { + LicenseKeyGroupEntity lkgInput = new LicenseKeyGroupEntity(); + lkgInput.setVendorLicenseModelId(vlmId); + lkgInput.setVersion(new Version(versionId)); + lkgInput.setId(licenseKeyGroupId); + vendorLicenseManager.deleteLicenseKeyGroup(lkgInput); + return Response.ok().build(); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VendorLicenseModelsImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VendorLicenseModelsImpl.java index df6363c883..0255b14753 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VendorLicenseModelsImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VendorLicenseModelsImpl.java @@ -13,10 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdcrests.vendorlicense.rest.services; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; +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; +import static org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelActionRequestDto.VendorLicenseModelAction.Submit; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Predicate; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.core.dao.UniqueValueDaoFactory; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.sdc.activitylog.ActivityLogManager; @@ -65,17 +77,6 @@ import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.function.Predicate; - -import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; -import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.*; -import static org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelActionRequestDto.VendorLicenseModelAction.Submit; - @Named @Service("vendorLicenseModels") @Scope(value = "prototype") @@ -83,75 +84,57 @@ import static org.openecomp.sdcrests.vendorlicense.types.VendorLicenseModelActio public class VendorLicenseModelsImpl implements VendorLicenseModels { private static final String SUBMIT_ITEM_ACTION = "Submit_Item"; - private static final String SUBMIT_HEALED_VERSION_ERROR = - "VLM Id %s: Error while submitting version %s created based on Certified version %s for healing purpose."; + private static final String SUBMIT_HEALED_VERSION_ERROR = "VLM Id %s: Error while submitting version %s created based on Certified version %s for healing purpose."; private static final Logger LOGGER = LoggerFactory.getLogger(VendorLicenseModelsImpl.class); private PermissionsManager permissionsManager = PermissionsManagerFactory.getInstance().createInterface(); - private NotificationPropagationManager notifier = - NotificationPropagationManagerFactory.getInstance().createInterface(); - + private NotificationPropagationManager notifier = NotificationPropagationManagerFactory.getInstance().createInterface(); private AsdcItemManager asdcItemManager = AsdcItemManagerFactory.getInstance().createInterface(); private VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); private VendorLicenseManager vendorLicenseManager = VendorLicenseManagerFactory.getInstance().createInterface(); private ActivityLogManager activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); - private UniqueValueUtil uniqueValueUtil = - new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + private UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); @Override public Response listLicenseModels(String versionStatus, String itemStatus, String user) { Predicate itemPredicate = createItemPredicate(versionStatus, itemStatus, user); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapItemToDto mapper = new MapItemToDto(); - asdcItemManager.list(itemPredicate).stream() - .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) - .forEach(item -> results.add(mapper.applyMapping(item, ItemDto.class))); - + asdcItemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) + .forEach(item -> results.add(mapper.applyMapping(item, ItemDto.class))); return Response.ok(results).build(); } @Override public Response createLicenseModel(VendorLicenseModelRequestDto request, String user) { - Item item = new Item(); item.setType(ItemType.vlm.name()); item.setOwner(user); item.setStatus(ItemStatus.ACTIVE); item.setName(request.getVendorName()); item.setDescription(request.getDescription()); - uniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, item.getName()); item = asdcItemManager.create(item); uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, item.getName()); - Version version = versioningManager.create(item.getId(), new Version(), null); - VendorLicenseModelEntity vlm = new MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity() - .applyMapping(request, VendorLicenseModelEntity.class); + .applyMapping(request, VendorLicenseModelEntity.class); vlm.setId(item.getId()); vlm.setVersion(version); - vendorLicenseManager.createVendorLicenseModel(vlm); versioningManager.publish(item.getId(), version, "Initial vlm:" + vlm.getVendorName()); - ItemCreationDto itemCreationDto = new ItemCreationDto(); itemCreationDto.setItemId(item.getId()); itemCreationDto.setVersion(new MapVersionToDto().applyMapping(version, VersionDto.class)); - - activityLogManager - .logActivity(new ActivityLogEntity(vlm.getId(), version, ActivityType.Create, user, true, "", "")); - + activityLogManager.logActivity(new ActivityLogEntity(vlm.getId(), version, ActivityType.Create, user, true, "", "")); return Response.ok(itemCreationDto).build(); } @Override - public Response updateLicenseModel(VendorLicenseModelRequestDto request, String vlmId, String versionId, - String user) { + public Response updateLicenseModel(VendorLicenseModelRequestDto request, String vlmId, String versionId, String user) { VendorLicenseModelEntity vlm = new MapVendorLicenseModelRequestDtoToVendorLicenseModelEntity() - .applyMapping(request, VendorLicenseModelEntity.class); + .applyMapping(request, VendorLicenseModelEntity.class); vlm.setId(vlmId); vlm.setVersion(new Version(versionId)); - vendorLicenseManager.updateVendorLicenseModel(vlm); return Response.ok().build(); } @@ -160,74 +143,56 @@ public class VendorLicenseModelsImpl implements VendorLicenseModels { public Response getLicenseModel(String vlmId, String versionId, String user) { Version version = versioningManager.get(vlmId, new Version(versionId)); VendorLicenseModelEntity vlm = vendorLicenseManager.getVendorLicenseModel(vlmId, version); - try { - HealingManagerFactory.getInstance().createInterface() - .healItemVersion(vlmId, version, ItemType.vlm, false) - .ifPresent(healedVersion -> { - vlm.setVersion(healedVersion); - if (version.getStatus() == VersionStatus.Certified) { - submitHealedVersion(vlmId, healedVersion, versionId, user); - } - }); + HealingManagerFactory.getInstance().createInterface().healItemVersion(vlmId, version, ItemType.vlm, false).ifPresent(healedVersion -> { + vlm.setVersion(healedVersion); + if (version.getStatus() == VersionStatus.Certified) { + submitHealedVersion(vlmId, healedVersion, versionId, user); + } + }); } catch (Exception e) { LOGGER.error(String.format("Error while auto healing VLM with Id %s and version %s", vlmId, versionId), e); } - - VendorLicenseModelEntityDto vlmDto = - new MapVendorLicenseModelEntityToDto().applyMapping(vlm, VendorLicenseModelEntityDto.class); + VendorLicenseModelEntityDto vlmDto = new MapVendorLicenseModelEntityToDto().applyMapping(vlm, VendorLicenseModelEntityDto.class); return Response.ok(vlmDto).build(); } @Override public Response deleteLicenseModel(String vlmId, String user) { Item vlm = asdcItemManager.get(vlmId); - if (!vlm.getType().equals(ItemType.vlm.name())) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder() - .withMessage(String.format("Vlm with id %s does not exist.", vlmId)) - .build())); + throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vlm with id %s does not exist.", vlmId)).build())); } - Integer certifiedVersionsCounter = vlm.getVersionStatusCounters().get(VersionStatus.Certified); if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) { asdcItemManager.delete(vlm); permissionsManager.deleteItemPermissions(vlmId); uniqueValueUtil.deleteUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, vlm.getName()); notifyUsers(vlmId, vlm.getName(), null, null, user, NotificationEventTypes.DELETE); - return Response.ok().build(); } else { - return Response.status(Response.Status.FORBIDDEN) - .entity(new Exception(Messages.DELETE_VLM_ERROR.getErrorMessage())).build(); + return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.DELETE_VLM_ERROR.getErrorMessage())).build(); } } @Override - public Response actOnLicenseModel(VendorLicenseModelActionRequestDto request, String vlmId, String versionId, - String user) { + public Response actOnLicenseModel(VendorLicenseModelActionRequestDto request, String vlmId, String versionId, String user) { Version version = new Version(versionId); - if (request.getAction() == Submit) { if (!permissionsManager.isAllowed(vlmId, user, SUBMIT_ITEM_ACTION)) { - return Response.status(Response.Status.FORBIDDEN) - .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); + return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); } String message = request.getSubmitRequest() == null ? "Submit" : request.getSubmitRequest().getMessage(); submit(vlmId, version, message, user); - notifyUsers(vlmId, null, version, message, user, NotificationEventTypes.SUBMIT); - } return Response.ok().build(); } private void submit(String vlmId, Version version, String message, String user) { - vendorLicenseManager.validate(vlmId, version); versioningManager.submit(vlmId, version, message); - activityLogManager - .logActivity(new ActivityLogEntity(vlmId, version, ActivityType.Submit, user, true, "", message)); + activityLogManager.logActivity(new ActivityLogEntity(vlmId, version, ActivityType.Submit, user, true, "", message)); } private void submitHealedVersion(String vlmId, Version healedVersion, String baseVersionId, String user) { @@ -238,21 +203,16 @@ public class VendorLicenseModelsImpl implements VendorLicenseModels { } } - private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, - NotificationEventTypes eventType) { + private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) { Map eventProperties = new HashMap<>(); eventProperties.put(ITEM_NAME, itemName == null ? asdcItemManager.get(itemId).getName() : itemName); eventProperties.put(ITEM_ID, itemId); - if (version != null) { - eventProperties.put(VERSION_NAME, - version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName()); + eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName()); eventProperties.put(VERSION_ID, version.getId()); } - eventProperties.put(SUBMIT_DESCRIPTION, message); eventProperties.put(PERMISSION_USER, userName); - Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); try { notifier.notifySubscribers(syncEvent, userName); @@ -261,6 +221,27 @@ public class VendorLicenseModelsImpl implements VendorLicenseModels { } } + private boolean userHasPermission(String itemId, String userId) { + return permissionsManager.getUserItemPermission(itemId, userId) + .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false); + } + + private Predicate createItemPredicate(String versionStatus, String itemStatus, String user) { + Predicate itemPredicate = item -> ItemType.vlm.name().equals(item.getType()); + if (ItemStatus.ARCHIVED.name().equals(itemStatus)) { + itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus())); + } else { + itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus())); + if (VersionStatus.Certified.name().equals(versionStatus)) { + itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified)); + } else if (VersionStatus.Draft.name().equals(versionStatus)) { + itemPredicate = itemPredicate + .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user)); + } + } + return itemPredicate; + } + private class SyncEvent implements Event { private String eventType; @@ -295,33 +276,4 @@ public class VendorLicenseModelsImpl implements VendorLicenseModels { return entityId; } } - - private boolean userHasPermission(String itemId, String userId) { - return permissionsManager.getUserItemPermission(itemId, userId) - .map(permission -> permission - .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())) - .orElse(false); - } - - private Predicate createItemPredicate(String versionStatus, String itemStatus, String user) { - Predicate itemPredicate = item -> ItemType.vlm.name().equals(item.getType()); - - if (ItemStatus.ARCHIVED.name().equals(itemStatus)) { - itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus())); - } else { - itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus())); - - if (VersionStatus.Certified.name().equals(versionStatus)) { - itemPredicate = - itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified)); - - } else if (VersionStatus.Draft.name().equals(versionStatus)) { - itemPredicate = itemPredicate - .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) - && userHasPermission(item.getId(), user)); - } - } - return itemPredicate; - } - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VlmUniqueTypeProvider.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VlmUniqueTypeProvider.java index 5beeec242f..91e1ac5593 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VlmUniqueTypeProvider.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-services/src/main/java/org/openecomp/sdcrests/vendorlicense/rest/services/VlmUniqueTypeProvider.java @@ -15,20 +15,18 @@ */ package org.openecomp.sdcrests.vendorlicense.rest.services; -import org.openecomp.sdcrests.uniquevalue.types.UniqueTypesProvider; +import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.UniqueValues.VENDOR_NAME; import java.util.Collections; import java.util.Map; - -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.UniqueValues.VENDOR_NAME; +import org.openecomp.sdcrests.uniquevalue.types.UniqueTypesProvider; public class VlmUniqueTypeProvider implements UniqueTypesProvider { - private static final Map uniqueTypes = - Collections.singletonMap("VlmName", VENDOR_NAME); + private static final Map uniqueTypes = Collections.singletonMap("VlmName", VENDOR_NAME); - @Override - public Map listUniqueTypes() { - return uniqueTypes; - } + @Override + public Map listUniqueTypes() { + return uniqueTypes; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/ChoiceOrOtherDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/ChoiceOrOtherDto.java index ba8f57f79f..fc3a41903b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/ChoiceOrOtherDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/ChoiceOrOtherDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,59 +17,53 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; +import javax.validation.constraints.NotNull; import org.hibernate.validator.group.GroupSequenceProvider; import org.openecomp.sdcrests.vendorlicense.types.validation.ChoiceOrOtherSequenceProvider; import org.openecomp.sdcrests.vendorlicense.types.validation.OtherChoiceValidation; -import javax.validation.constraints.NotNull; - @GroupSequenceProvider(value = ChoiceOrOtherSequenceProvider.class) public class ChoiceOrOtherDto> { - @NotNull - private E choice; - @NotNull(message = "may not be null when choice is set to 'Other'.", - groups = OtherChoiceValidation.class) - private String other; - - public E getChoice() { - return choice; - } - - public void setChoice(E choice) { - this.choice = choice; - } - public String getOther() { - return other; - } + @NotNull + private E choice; + @NotNull(message = "may not be null when choice is set to 'Other'.", groups = OtherChoiceValidation.class) + private String other; - public void setOther(String other) { - this.other = other; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + public E getChoice() { + return choice; } - if (obj == null || getClass() != obj.getClass()) { - return false; + + public void setChoice(E choice) { + this.choice = choice; } - ChoiceOrOtherDto that = (ChoiceOrOtherDto) obj; + public String getOther() { + return other; + } - return choice != null ? choice.equals(that.choice) - : that.choice == null && (other != null ? other.equals(that.other) : that.other == null); + public void setOther(String other) { + this.other = other; + } - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + ChoiceOrOtherDto that = (ChoiceOrOtherDto) obj; + return choice != null ? choice.equals(that.choice) : that.choice == null && (other != null ? other.equals(that.other) : that.other == null); + } - @Override - public int hashCode() { - int result = choice != null ? choice.hashCode() : 0; - result = 31 * result + (other != null ? other.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = choice != null ? choice.hashCode() : 0; + result = 31 * result + (other != null ? other.hashCode() : 0); + return result; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolEntityDto.java index 88d08d6aa1..835d6fcbfe 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "EntitlementPoolEntity") public class EntitlementPoolEntityDto extends EntitlementPoolRequestDto { - private String id; - private Set referencingFeatureGroups; - private String versionUUID; - public String getId() { - return id; - } + private String id; + private Set referencingFeatureGroups; + private String versionUUID; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getReferencingFeatureGroups() { - return referencingFeatureGroups; - } + public Set getReferencingFeatureGroups() { + return referencingFeatureGroups; + } - public void setReferencingFeatureGroups(Set referencingFeatureGroups) { - this.referencingFeatureGroups = referencingFeatureGroups; - } + public void setReferencingFeatureGroups(Set referencingFeatureGroups) { + this.referencingFeatureGroups = referencingFeatureGroups; + } - public String getversionUUID() { - return versionUUID; - } + public String getversionUUID() { + return versionUUID; + } - public void setVersionUUID(String versionUUID) { - this.versionUUID = versionUUID; - } + public void setVersionUUID(String versionUUID) { + this.versionUUID = versionUUID; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolRequestDto.java index 642156fa30..35e6f31e28 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/EntitlementPoolRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.validator.constraints.NotBlank; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolType; import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; - import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @@ -36,109 +33,102 @@ import javax.validation.constraints.Size; @JsonIgnoreProperties({"time", "aggregationFunction", "entitlementMetric"}) public class EntitlementPoolRequestDto { - @NotNull - @Size(max = 120) - private String name; - - @NotBlank(message = "is mandatory and should not be empty") - @Size(max = 100) - private String manufacturerReferenceNumber; - - @Size(max = 1000) - private String description; - - @NotNull - private EntitlementPoolType type; - - private Integer thresholdValue; - - private ThresholdUnit thresholdUnits; - @Size(max = 120) - private String increments; - - @Valid - private MultiChoiceOrOtherDto operationalScope; - - private String startDate; - private String expiryDate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getManufacturerReferenceNumber() { - return manufacturerReferenceNumber; - } - - public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { - this.manufacturerReferenceNumber = manufacturerReferenceNumber; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public EntitlementPoolType getType() { - return type; - } - - public void setType(EntitlementPoolType type) { - this.type = type; - } - - public Integer getThresholdValue() { - return thresholdValue; - } - - public void setThresholdValue(Integer thresholdValue) { - this.thresholdValue = thresholdValue; - } - - public ThresholdUnit getThresholdUnits() { - return thresholdUnits; - } - - public void setThresholdUnits(ThresholdUnit thresholdUnits) { - this.thresholdUnits = thresholdUnits; - } - - public String getIncrements() { - return increments; - } - - public void setIncrements(String increments) { - this.increments = increments; - } - - public MultiChoiceOrOtherDto getOperationalScope() { - return operationalScope; - } - - public void setOperationalScope(MultiChoiceOrOtherDto operationalScope) { - this.operationalScope = operationalScope; - } - - public String getStartDate() { - return startDate; - } - - public void setStartDate(String startDate) { - this.startDate = startDate; - } - - public String getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(String expiryDate) { - this.expiryDate = expiryDate; - } + @NotNull + @Size(max = 120) + private String name; + @NotBlank(message = "is mandatory and should not be empty") + @Size(max = 100) + private String manufacturerReferenceNumber; + @Size(max = 1000) + private String description; + @NotNull + private EntitlementPoolType type; + private Integer thresholdValue; + private ThresholdUnit thresholdUnits; + @Size(max = 120) + private String increments; + @Valid + private MultiChoiceOrOtherDto operationalScope; + private String startDate; + private String expiryDate; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getManufacturerReferenceNumber() { + return manufacturerReferenceNumber; + } + + public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { + this.manufacturerReferenceNumber = manufacturerReferenceNumber; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public EntitlementPoolType getType() { + return type; + } + + public void setType(EntitlementPoolType type) { + this.type = type; + } + + public Integer getThresholdValue() { + return thresholdValue; + } + + public void setThresholdValue(Integer thresholdValue) { + this.thresholdValue = thresholdValue; + } + + public ThresholdUnit getThresholdUnits() { + return thresholdUnits; + } + + public void setThresholdUnits(ThresholdUnit thresholdUnits) { + this.thresholdUnits = thresholdUnits; + } + + public String getIncrements() { + return increments; + } + + public void setIncrements(String increments) { + this.increments = increments; + } + + public MultiChoiceOrOtherDto getOperationalScope() { + return operationalScope; + } + + public void setOperationalScope(MultiChoiceOrOtherDto operationalScope) { + this.operationalScope = operationalScope; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getExpiryDate() { + return expiryDate; + } + + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupDescriptorDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupDescriptorDto.java index 919fdb21c2..03bf2de328 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupDescriptorDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupDescriptorDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,45 +17,42 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class FeatureGroupDescriptorDto { - @NotNull - @Size(max = 120) - private String name; - - @Size(max = 1000) - private String description; - @NotNull - private String partNumber; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getPartNumber() { - return partNumber; - } - - public void setPartNumber(String partNumber) { - this.partNumber = partNumber; - } + @NotNull + @Size(max = 120) + private String name; + @Size(max = 1000) + private String description; + @NotNull + private String partNumber; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getPartNumber() { + return partNumber; + } + + public void setPartNumber(String partNumber) { + this.partNumber = partNumber; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupEntityDto.java index eac6ed38fe..679dfbbeca 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,52 +17,50 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - -import javax.validation.constraints.Size; import java.util.Set; +import javax.validation.constraints.Size; @Schema(description = "FeatureGroupEntity") public class FeatureGroupEntityDto extends FeatureGroupDescriptorDto { - private String id; - private Set licenseKeyGroupsIds; - @Size(min = 1) - private Set entitlementPoolsIds; - private Set referencingLicenseAgreements; - public String getId() { - return id; - } + private String id; + private Set licenseKeyGroupsIds; + @Size(min = 1) + private Set entitlementPoolsIds; + private Set referencingLicenseAgreements; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getLicenseKeyGroupsIds() { - return licenseKeyGroupsIds; - } + public Set getLicenseKeyGroupsIds() { + return licenseKeyGroupsIds; + } - public void setLicenseKeyGroupsIds(Set licenseKeyGroupsIds) { - this.licenseKeyGroupsIds = licenseKeyGroupsIds; - } + public void setLicenseKeyGroupsIds(Set licenseKeyGroupsIds) { + this.licenseKeyGroupsIds = licenseKeyGroupsIds; + } - public Set getEntitlementPoolsIds() { - return entitlementPoolsIds; - } + public Set getEntitlementPoolsIds() { + return entitlementPoolsIds; + } - public void setEntitlementPoolsIds(Set entitlementPoolsIds) { - this.entitlementPoolsIds = entitlementPoolsIds; - } + public void setEntitlementPoolsIds(Set entitlementPoolsIds) { + this.entitlementPoolsIds = entitlementPoolsIds; + } - public Set getReferencingLicenseAgreements() { - return referencingLicenseAgreements; - } + public Set getReferencingLicenseAgreements() { + return referencingLicenseAgreements; + } - public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { - this.referencingLicenseAgreements = referencingLicenseAgreements; - } + public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { + this.referencingLicenseAgreements = referencingLicenseAgreements; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupModelDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupModelDto.java index 44404c3b1f..485e362288 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupModelDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupModelDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,52 +17,49 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Collection; import java.util.Set; @Schema(description = "FeatureGroupModel") public class FeatureGroupModelDto extends FeatureGroupDescriptorDto { - private String id; - private Set referencingLicenseAgreements; - private Collection licenseKeyGroups; - private Collection entitlementPools; - public String getId() { - return id; - } + private String id; + private Set referencingLicenseAgreements; + private Collection licenseKeyGroups; + private Collection entitlementPools; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getReferencingLicenseAgreements() { - return referencingLicenseAgreements; - } + public Set getReferencingLicenseAgreements() { + return referencingLicenseAgreements; + } - public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { - this.referencingLicenseAgreements = referencingLicenseAgreements; - } + public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { + this.referencingLicenseAgreements = referencingLicenseAgreements; + } - public Collection getLicenseKeyGroups() { - return licenseKeyGroups; - } + public Collection getLicenseKeyGroups() { + return licenseKeyGroups; + } - public void setLicenseKeyGroups(Collection licenseKeyGroups) { - this.licenseKeyGroups = licenseKeyGroups; - } + public void setLicenseKeyGroups(Collection licenseKeyGroups) { + this.licenseKeyGroups = licenseKeyGroups; + } - public Collection getEntitlementPools() { - return entitlementPools; - } + public Collection getEntitlementPools() { + return entitlementPools; + } - public void setEntitlementPools(Collection entitlementPools) { - this.entitlementPools = entitlementPools; - } + public void setEntitlementPools(Collection entitlementPools) { + this.entitlementPools = entitlementPools; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupRequestDto.java index 3aefaa1d45..27fb954957 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "FeatureGroupRequest") public class FeatureGroupRequestDto extends FeatureGroupDescriptorDto { - private Set addedLicenseKeyGroupsIds; - private Set addedEntitlementPoolsIds; + private Set addedLicenseKeyGroupsIds; + private Set addedEntitlementPoolsIds; - public Set getAddedLicenseKeyGroupsIds() { - return addedLicenseKeyGroupsIds; - } + public Set getAddedLicenseKeyGroupsIds() { + return addedLicenseKeyGroupsIds; + } - public void setAddedLicenseKeyGroupsIds(Set addedLicenseKeyGroupsIds) { - this.addedLicenseKeyGroupsIds = addedLicenseKeyGroupsIds; - } + public void setAddedLicenseKeyGroupsIds(Set addedLicenseKeyGroupsIds) { + this.addedLicenseKeyGroupsIds = addedLicenseKeyGroupsIds; + } - public Set getAddedEntitlementPoolsIds() { - return addedEntitlementPoolsIds; - } + public Set getAddedEntitlementPoolsIds() { + return addedEntitlementPoolsIds; + } - public void setAddedEntitlementPoolsIds(Set addedEntitlementPoolsIds) { - this.addedEntitlementPoolsIds = addedEntitlementPoolsIds; - } + public void setAddedEntitlementPoolsIds(Set addedEntitlementPoolsIds) { + this.addedEntitlementPoolsIds = addedEntitlementPoolsIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupUpdateRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupUpdateRequestDto.java index 9e3fab59ee..016735fced 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupUpdateRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/FeatureGroupUpdateRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "FeatureGroupUpdateRequest") public class FeatureGroupUpdateRequestDto extends FeatureGroupRequestDto { - private Set removedLicenseKeyGroupsIds; - private Set removedEntitlementPoolsIds; + private Set removedLicenseKeyGroupsIds; + private Set removedEntitlementPoolsIds; - public Set getRemovedLicenseKeyGroupsIds() { - return removedLicenseKeyGroupsIds; - } + public Set getRemovedLicenseKeyGroupsIds() { + return removedLicenseKeyGroupsIds; + } - public void setRemovedLicenseKeyGroupsIds(Set removedLicenseKeyGroupsIds) { - this.removedLicenseKeyGroupsIds = removedLicenseKeyGroupsIds; - } + public void setRemovedLicenseKeyGroupsIds(Set removedLicenseKeyGroupsIds) { + this.removedLicenseKeyGroupsIds = removedLicenseKeyGroupsIds; + } - public Set getRemovedEntitlementPoolsIds() { - return removedEntitlementPoolsIds; - } + public Set getRemovedEntitlementPoolsIds() { + return removedEntitlementPoolsIds; + } - public void setRemovedEntitlementPoolsIds(Set removedEntitlementPoolsIds) { - this.removedEntitlementPoolsIds = removedEntitlementPoolsIds; - } + public void setRemovedEntitlementPoolsIds(Set removedEntitlementPoolsIds) { + this.removedEntitlementPoolsIds = removedEntitlementPoolsIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementDescriptorDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementDescriptorDto.java index 4239488124..cd72d151dc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementDescriptorDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementDescriptorDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,58 +17,55 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; - import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; public class LicenseAgreementDescriptorDto { - @NotNull - @Size(max = 120) - private String name; - - @Size(max = 1000) - private String description; - @NotNull - @Valid - private ChoiceOrOtherDto licenseTerm; - @Size(max = 1000) - private String requirementsAndConstrains; + @NotNull + @Size(max = 120) + private String name; + @Size(max = 1000) + private String description; + @NotNull + @Valid + private ChoiceOrOtherDto licenseTerm; + @Size(max = 1000) + private String requirementsAndConstrains; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public ChoiceOrOtherDto getLicenseTerm() { - return licenseTerm; - } + public ChoiceOrOtherDto getLicenseTerm() { + return licenseTerm; + } - public void setLicenseTerm(ChoiceOrOtherDto licenseTerm) { - this.licenseTerm = licenseTerm; - } + public void setLicenseTerm(ChoiceOrOtherDto licenseTerm) { + this.licenseTerm = licenseTerm; + } - public String getRequirementsAndConstrains() { - return requirementsAndConstrains; - } + public String getRequirementsAndConstrains() { + return requirementsAndConstrains; + } - public void setRequirementsAndConstrains(String requirementsAndConstrains) { - this.requirementsAndConstrains = requirementsAndConstrains; - } + public void setRequirementsAndConstrains(String requirementsAndConstrains) { + this.requirementsAndConstrains = requirementsAndConstrains; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementEntityDto.java index e3b6207eaa..423edcfe59 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,35 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - - import io.swagger.v3.oas.annotations.media.Schema; - -import javax.validation.constraints.Size; import java.util.Set; +import javax.validation.constraints.Size; @Schema(description = "LicenseAgreementEntity") public class LicenseAgreementEntityDto extends LicenseAgreementDescriptorDto { - private String id; - @Size(min = 1) - private Set featureGroupsIds; - public String getId() { - return id; - } + private String id; + @Size(min = 1) + private Set featureGroupsIds; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getFeatureGroupsIds() { - return featureGroupsIds; - } + public Set getFeatureGroupsIds() { + return featureGroupsIds; + } - public void setFeatureGroupsIds(Set featureGroupsIds) { - this.featureGroupsIds = featureGroupsIds; - } + public void setFeatureGroupsIds(Set featureGroupsIds) { + this.featureGroupsIds = featureGroupsIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementModelDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementModelDto.java index 3c97756c3c..8365476e8d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementModelDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementModelDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "LicenseAgreementModel") public class LicenseAgreementModelDto extends LicenseAgreementDescriptorDto { - private String id; - private Set featureGroups; - public String getId() { - return id; - } + private String id; + private Set featureGroups; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getFeatureGroups() { - return featureGroups; - } + public Set getFeatureGroups() { + return featureGroups; + } - public void setFeatureGroups(Set featureGroups) { - this.featureGroups = featureGroups; - } + public void setFeatureGroups(Set featureGroups) { + this.featureGroups = featureGroups; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementRequestDto.java index 358dcef8e2..ee90e989e2 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "LicenseAgreementRequest") public class LicenseAgreementRequestDto extends LicenseAgreementDescriptorDto { - private Set addedFeatureGroupsIds; + private Set addedFeatureGroupsIds; - public Set getAddedFeatureGroupsIds() { - return addedFeatureGroupsIds; - } + public Set getAddedFeatureGroupsIds() { + return addedFeatureGroupsIds; + } - public void setAddedFeatureGroupsIds(Set addedFeatureGroupsIds) { - this.addedFeatureGroupsIds = addedFeatureGroupsIds; - } + public void setAddedFeatureGroupsIds(Set addedFeatureGroupsIds) { + this.addedFeatureGroupsIds = addedFeatureGroupsIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementUpdateRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementUpdateRequestDto.java index 6baba8acb3..3fbba212dd 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementUpdateRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseAgreementUpdateRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; - import java.util.Set; @Schema(description = "LicenseAgreementUpdateRequest") public class LicenseAgreementUpdateRequestDto extends LicenseAgreementRequestDto { - private Set removedFeatureGroupsIds; - public Set getRemovedFeatureGroupsIds() { - return removedFeatureGroupsIds; - } + private Set removedFeatureGroupsIds; + + public Set getRemovedFeatureGroupsIds() { + return removedFeatureGroupsIds; + } - public void setRemovedFeatureGroupsIds(Set removedFeatureGroupsIds) { - this.removedFeatureGroupsIds = removedFeatureGroupsIds; - } + public void setRemovedFeatureGroupsIds(Set removedFeatureGroupsIds) { + this.removedFeatureGroupsIds = removedFeatureGroupsIds; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupEntityDto.java index 6186398d29..6ee80bd801 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import java.util.Set; public class LicenseKeyGroupEntityDto extends LicenseKeyGroupRequestDto { - private String id; - private Set referencingFeatureGroups; - private String versionUUID; - public String getId() { - return id; - } + private String id; + private Set referencingFeatureGroups; + private String versionUUID; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Set getReferencingFeatureGroups() { - return referencingFeatureGroups; - } + public Set getReferencingFeatureGroups() { + return referencingFeatureGroups; + } - public void setReferencingFeatureGroups(Set referencingFeatureGroups) { - this.referencingFeatureGroups = referencingFeatureGroups; - } + public void setReferencingFeatureGroups(Set referencingFeatureGroups) { + this.referencingFeatureGroups = referencingFeatureGroups; + } - public String getVersionUUID() { - return versionUUID; - } + public String getVersionUUID() { + return versionUUID; + } - public void setVersionUUID(String versionUUID) { - this.versionUUID = versionUUID; - } + public void setVersionUUID(String versionUUID) { + this.versionUUID = versionUUID; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupRequestDto.java index c1e2ef05bf..2eabb0aa4a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LicenseKeyGroupRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,121 +17,112 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; -import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; -import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; - import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; public class LicenseKeyGroupRequestDto { - @NotNull - @Size(max = 120) - private String name; - - @Size(max = 100) - private String manufacturerReferenceNumber; - - @Size(max = 1000) - private String description; - - @NotNull - private LicenseKeyType type; - - @Valid - private MultiChoiceOrOtherDto operationalScope; - - private String startDate; - private String expiryDate; - - private Integer thresholdValue; - - private ThresholdUnit thresholdUnits; - - @Size(max = 120) - private String increments; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getManufacturerReferenceNumber() { - return manufacturerReferenceNumber; - } - - public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { - this.manufacturerReferenceNumber = manufacturerReferenceNumber; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LicenseKeyType getType() { - return type; - } - - public void setType(LicenseKeyType type) { - this.type = type; - } - - public MultiChoiceOrOtherDto getOperationalScope() { - return operationalScope; - } - - public void setOperationalScope(MultiChoiceOrOtherDto operationalScope) { - this.operationalScope = operationalScope; - } - - public String getStartDate() { - return startDate; - } - - public void setStartDate(String startDate) { - this.startDate = startDate; - } - - public String getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(String expiryDate) { - this.expiryDate = expiryDate; - } - - public Integer getThresholdValue() { - return thresholdValue; - } - - public void setThresholdValue(Integer thresholdValue) { - this.thresholdValue = thresholdValue; - } - - public ThresholdUnit getThresholdUnits() { - return thresholdUnits; - } - - public void setThresholdUnits(ThresholdUnit thresholdUnits) { - this.thresholdUnits = thresholdUnits; - } - - public String getIncrements() { - return increments; - } - public void setIncrements(String increments) { - this.increments = increments; - } + @NotNull + @Size(max = 120) + private String name; + @Size(max = 100) + private String manufacturerReferenceNumber; + @Size(max = 1000) + private String description; + @NotNull + private LicenseKeyType type; + @Valid + private MultiChoiceOrOtherDto operationalScope; + private String startDate; + private String expiryDate; + private Integer thresholdValue; + private ThresholdUnit thresholdUnits; + @Size(max = 120) + private String increments; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getManufacturerReferenceNumber() { + return manufacturerReferenceNumber; + } + + public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { + this.manufacturerReferenceNumber = manufacturerReferenceNumber; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LicenseKeyType getType() { + return type; + } + + public void setType(LicenseKeyType type) { + this.type = type; + } + + public MultiChoiceOrOtherDto getOperationalScope() { + return operationalScope; + } + + public void setOperationalScope(MultiChoiceOrOtherDto operationalScope) { + this.operationalScope = operationalScope; + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getExpiryDate() { + return expiryDate; + } + + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } + + public Integer getThresholdValue() { + return thresholdValue; + } + + public void setThresholdValue(Integer thresholdValue) { + this.thresholdValue = thresholdValue; + } + + public ThresholdUnit getThresholdUnits() { + return thresholdUnits; + } + + public void setThresholdUnits(ThresholdUnit thresholdUnits) { + this.thresholdUnits = thresholdUnits; + } + + public String getIncrements() { + return increments; + } + + public void setIncrements(String increments) { + this.increments = increments; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitEntityDto.java index e3e3584b34..a22bb0a64d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,90 +17,89 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; public class LimitEntityDto { - private String id; - private String name; - private String type; - private String description; - private String metric; - private String value; - private String unit; - private String aggregationFunction; - private String time; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getMetric() { - return metric; - } - - public void setMetric(String metric) { - this.metric = metric; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public String getAggregationFunction() { - return aggregationFunction; - } - - public void setAggregationFunction(String aggregationFunction) { - this.aggregationFunction = aggregationFunction; - } - - public String getTime() { - return time; - } - - public void setTime(String time) { - this.time = time; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } + private String id; + private String name; + private String type; + private String description; + private String metric; + private String value; + private String unit; + private String aggregationFunction; + private String time; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getMetric() { + return metric; + } + + public void setMetric(String metric) { + this.metric = metric; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public String getAggregationFunction() { + return aggregationFunction; + } + + public void setAggregationFunction(String aggregationFunction) { + this.aggregationFunction = aggregationFunction; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitRequestDto.java index 116be31a40..fff840c402 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/LimitRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,95 +17,91 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; import io.swagger.v3.oas.annotations.media.Schema; -import org.hibernate.validator.constraints.NotBlank; - import javax.validation.constraints.Size; +import org.hibernate.validator.constraints.NotBlank; @Schema(description = "LimitRequest") public class LimitRequestDto { - @NotBlank(message = "is mandatory and should not be empty") - @Size(max = 120, message = "length should not exceed 120 characters.") - private String name; - @NotBlank(message = "is mandatory and should not be empty") - private String type; - @Size(max = 1000, message = "length should not exceed 1000 characters.") - private String description; - @NotBlank(message = "is mandatory and should not be empty") - private String metric; - @NotBlank(message = "is mandatory and should not be empty") - private String value; - private String unit; - private String aggregationFunction; - private String time; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getMetric() { - return metric; - } - - public void setMetric(String metric) { - this.metric = metric; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getAggregationFunction() { - return aggregationFunction; - } - - public void setAggregationFunction( - String aggregationFunction) { - this.aggregationFunction = aggregationFunction; - } - - public String getTime() { - return time; - } - - public void setTime(String time) { - this.time = time; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - + @NotBlank(message = "is mandatory and should not be empty") + @Size(max = 120, message = "length should not exceed 120 characters.") + private String name; + @NotBlank(message = "is mandatory and should not be empty") + private String type; + @Size(max = 1000, message = "length should not exceed 1000 characters.") + private String description; + @NotBlank(message = "is mandatory and should not be empty") + private String metric; + @NotBlank(message = "is mandatory and should not be empty") + private String value; + private String unit; + private String aggregationFunction; + private String time; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getMetric() { + return metric; + } + + public void setMetric(String metric) { + this.metric = metric; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getAggregationFunction() { + return aggregationFunction; + } + + public void setAggregationFunction(String aggregationFunction) { + this.aggregationFunction = aggregationFunction; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/MultiChoiceOrOtherDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/MultiChoiceOrOtherDto.java index 1dc8ff2bdd..7a3266da96 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/MultiChoiceOrOtherDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/MultiChoiceOrOtherDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,62 +17,57 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; +import java.util.Set; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; import org.hibernate.validator.group.GroupSequenceProvider; import org.openecomp.sdcrests.vendorlicense.types.validation.MultiChoiceOrOtherSequenceProvider; import org.openecomp.sdcrests.vendorlicense.types.validation.OtherChoiceValidation; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; -import java.util.Set; - @GroupSequenceProvider(value = MultiChoiceOrOtherSequenceProvider.class) public class MultiChoiceOrOtherDto> { - @NotNull - @Size(min = 1, message = "must contain at least 1 choice.") - private Set choices; - @NotNull(message = "may not be null when choices is set to 'Other'.", - groups = OtherChoiceValidation.class) - private String other; - public Set getChoices() { - return choices; - } + @NotNull + @Size(min = 1, message = "must contain at least 1 choice.") + private Set choices; + @NotNull(message = "may not be null when choices is set to 'Other'.", groups = OtherChoiceValidation.class) + private String other; - public void setChoices(Set choices) { - this.choices = choices; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + public Set getChoices() { + return choices; } - if (obj == null || getClass() != obj.getClass()) { - return false; + + public void setChoices(Set choices) { + this.choices = choices; } - MultiChoiceOrOtherDto that = (MultiChoiceOrOtherDto) obj; + public String getOther() { + return other; + } - return choices != null ? choices.equals(that.choices) - : that.choices == null && (other != null ? other.equals(that.other) : that.other == null); + public void setOther(String other) { + this.other = other; + } - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + MultiChoiceOrOtherDto that = (MultiChoiceOrOtherDto) obj; + return choices != null ? choices.equals(that.choices) + : that.choices == null && (other != null ? other.equals(that.other) : that.other == null); + } - @Override - public int hashCode() { - int result = choices != null ? choices.hashCode() : 0; - result = 31 * result + (other != null ? other.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = choices != null ? choices.hashCode() : 0; + result = 31 * result + (other != null ? other.hashCode() : 0); + return result; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelActionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelActionRequestDto.java index 68e0fd8552..53be21f0bc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelActionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelActionRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; import org.openecomp.sdcrests.item.types.SubmitRequestDto; public class VendorLicenseModelActionRequestDto { - private VendorLicenseModelAction action; - private SubmitRequestDto submitRequest; + private VendorLicenseModelAction action; + private SubmitRequestDto submitRequest; - public VendorLicenseModelAction getAction() { - return action; - } + public VendorLicenseModelAction getAction() { + return action; + } - public void setAction(VendorLicenseModelAction action) { - this.action = action; - } + public void setAction(VendorLicenseModelAction action) { + this.action = action; + } - public SubmitRequestDto getSubmitRequest() { - return submitRequest; - } + public SubmitRequestDto getSubmitRequest() { + return submitRequest; + } - public void setSubmitRequest(SubmitRequestDto submitRequest) { - this.submitRequest = submitRequest; - } + public void setSubmitRequest(SubmitRequestDto submitRequest) { + this.submitRequest = submitRequest; + } - public enum VendorLicenseModelAction { - Submit - } + public enum VendorLicenseModelAction {Submit} } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelEntityDto.java index 2162006c16..2c647647d8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "VendorLicenseModelEntity") public class VendorLicenseModelEntityDto extends VendorLicenseModelRequestDto { - private String id; - public String getId() { - return id; - } + private String id; + + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelRequestDto.java index da2a3e742d..625cc721a9 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/VendorLicenseModelRequestDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,48 +17,45 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types; - - import io.swagger.v3.oas.annotations.media.Schema; - import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Schema(description = "VendorLicenseModelRequest") public class VendorLicenseModelRequestDto { - @NotNull - @Size(max = 25) - private String vendorName; - @NotNull - @Size(max = 1000) - private String description; - @NotNull - private String iconRef; - - public String getVendorName() { - return vendorName; - } - - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getIconRef() { - return iconRef; - } - public void setIconRef(String iconRef) { - this.iconRef = iconRef; - } + @NotNull + @Size(max = 25) + private String vendorName; + @NotNull + @Size(max = 1000) + private String description; + @NotNull + private String iconRef; + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIconRef() { + return iconRef; + } + + public void setIconRef(String iconRef) { + this.iconRef = iconRef; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/ChoiceOrOtherSequenceProvider.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/ChoiceOrOtherSequenceProvider.java index 8be0ba3231..d2cc51c769 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/ChoiceOrOtherSequenceProvider.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/ChoiceOrOtherSequenceProvider.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types.validation; +import java.util.ArrayList; +import java.util.List; import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdcrests.vendorlicense.types.ChoiceOrOtherDto; -import java.util.ArrayList; -import java.util.List; - -public class ChoiceOrOtherSequenceProvider - implements DefaultGroupSequenceProvider { +public class ChoiceOrOtherSequenceProvider implements DefaultGroupSequenceProvider { - @Override - public List> getValidationGroups(ChoiceOrOtherDto choiceOrOther) { - List> sequence = new ArrayList<>(); - sequence.add(ChoiceOrOtherDto.class); - - if (choiceOrOther != null && choiceOrOther.getChoice() != null - && ChoiceOrOther.OTHER_ENUM_VALUE.equals(choiceOrOther.getChoice().name())) { - sequence.add(OtherChoiceValidation.class); + @Override + public List> getValidationGroups(ChoiceOrOtherDto choiceOrOther) { + List> sequence = new ArrayList<>(); + sequence.add(ChoiceOrOtherDto.class); + if (choiceOrOther != null && choiceOrOther.getChoice() != null && ChoiceOrOther.OTHER_ENUM_VALUE.equals(choiceOrOther.getChoice().name())) { + sequence.add(OtherChoiceValidation.class); + } + return sequence; } - - return sequence; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/MultiChoiceOrOtherSequenceProvider.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/MultiChoiceOrOtherSequenceProvider.java index 7cc9bbd2a2..446a7c2ec7 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/MultiChoiceOrOtherSequenceProvider.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/MultiChoiceOrOtherSequenceProvider.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types.validation; +import java.util.ArrayList; +import java.util.List; import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider; import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; import org.openecomp.sdcrests.vendorlicense.types.MultiChoiceOrOtherDto; -import java.util.ArrayList; -import java.util.List; - -public class MultiChoiceOrOtherSequenceProvider - implements DefaultGroupSequenceProvider { +public class MultiChoiceOrOtherSequenceProvider implements DefaultGroupSequenceProvider { - @Override - public List> getValidationGroups(MultiChoiceOrOtherDto multiChoiceOrOther) { - List> sequence = new ArrayList<>(); - sequence.add(MultiChoiceOrOtherDto.class); - - if (multiChoiceOrOther != null && multiChoiceOrOther.getChoices() != null - && multiChoiceOrOther.getChoices().size() == 1 - && MultiChoiceOrOther.OTHER_ENUM_VALUE - .equals((((Enum) (multiChoiceOrOther.getChoices().iterator().next())).name()))) { - sequence.add(OtherChoiceValidation.class); + @Override + public List> getValidationGroups(MultiChoiceOrOtherDto multiChoiceOrOther) { + List> sequence = new ArrayList<>(); + sequence.add(MultiChoiceOrOtherDto.class); + if (multiChoiceOrOther != null && multiChoiceOrOther.getChoices() != null && multiChoiceOrOther.getChoices().size() == 1 + && MultiChoiceOrOther.OTHER_ENUM_VALUE.equals((((Enum) (multiChoiceOrOther.getChoices().iterator().next())).name()))) { + sequence.add(OtherChoiceValidation.class); + } + return sequence; } - - return sequence; - } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/OtherChoiceValidation.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/OtherChoiceValidation.java index ff682dd8b5..7bffee5749 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/OtherChoiceValidation.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-license-rest/vendor-license-rest-types/src/main/java/org/openecomp/sdcrests/vendorlicense/types/validation/OtherChoiceValidation.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorlicense.types.validation; public interface OtherChoiceValidation { + } 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/ComponentDependencies.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/ComponentDependencies.java index bfeb476836..732167937d 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/ComponentDependencies.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/ComponentDependencies.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,30 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyModel; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyResponseDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyModel; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyResponseDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/component-dependencies") @Produces(MediaType.APPLICATION_JSON) @@ -49,54 +54,41 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface ComponentDependencies extends VspEntities { - @POST - @Path("/") - @Operation( description= "Create a vendor software product component dependency") - Response create(@Valid ComponentDependencyModel request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product component dependency") + Response create(@Valid ComponentDependencyModel request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/") - @Operation(description = "Get component dependencies for vendor software product", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation = ComponentDependencyResponseDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") - String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/") + @Operation(description = "Get component dependencies for vendor software product", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ComponentDependencyResponseDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{dependencyId}") - @Operation(description = "Delete component dependency for vendor software product") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") - @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product Component Dependency Id") @PathParam - ("dependencyId") String dependencyId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{dependencyId}") + @Operation(description = "Delete component dependency for vendor software product") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Component Dependency Id") @PathParam("dependencyId") String dependencyId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{dependencyId}") - @Operation(description = "Update component dependency for vendor software product") - Response update(@Valid ComponentDependencyModel request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") - String versionId, - @Parameter(description = "Vendor software product Component Dependency Id") @PathParam - ("dependencyId") String dependencyId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @PUT + @Path("/{dependencyId}") + @Operation(description = "Update component dependency for vendor software product") + Response update(@Valid ComponentDependencyModel request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Component Dependency Id") @PathParam("dependencyId") String dependencyId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{dependencyId}") - @Operation(description = "Get component dependency for vendor software product", responses = @ApiResponse(content = @Content(schema = @Schema(implementation =ComponentDependencyResponseDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product Component Dependency Id") @PathParam - ("dependencyId") String dependencyId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{dependencyId}") + @Operation(description = "Get component dependency for vendor software product", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ComponentDependencyResponseDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Component Dependency Id") @PathParam("dependencyId") String dependencyId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/ComponentMonitoringUploads.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/ComponentMonitoringUploads.java index f575991456..1a34bfc47c 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/ComponentMonitoringUploads.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/ComponentMonitoringUploads.java @@ -17,73 +17,67 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.vendorsoftwareproducts.types.MonitoringUploadStatusDto; import org.springframework.validation.annotation.Validated; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - -@Path( - "/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId}/uploads/") +@Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId}/uploads/") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Component Uploads")}) @Validated public interface ComponentMonitoringUploads extends VspEntities { - @POST - @Path("types/{type}/") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Upload file for component by type") - Response upload(@Multipart("upload") Attachment attachment, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") - String vspId, - @Parameter(description = "Vendor software product version Id") - @PathParam("versionId") String versionId, - @Parameter(description = "Component Id") @PathParam("componentId") String - componentId, - @Parameter(description = "Upload Type") @PathParam("type") String type, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; - @DELETE - @Path("types/{type}") - @Operation(description = "Delete file uploaded for component") - Response delete( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") - String versionId, - @Parameter(description = "Component Id") @PathParam("componentId") String componentId, - @Parameter(description = "Upload Type") @PathParam("type") String type, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws Exception; + @POST + @Path("types/{type}/") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Upload file for component by type") + Response upload(@Multipart("upload") Attachment attachment, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Upload Type") @PathParam("type") String type, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; + + @DELETE + @Path("types/{type}") + @Operation(description = "Delete file uploaded for component") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Upload Type") @PathParam("type") String type, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; - @GET - @Path("") - @Operation(description = "Get the filenames of uploaded files by type", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation =MonitoringUploadStatusDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") - String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("") + @Operation(description = "Get the filenames of uploaded files by type", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = MonitoringUploadStatusDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/ComponentProcesses.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/ComponentProcesses.java index b5907d5d30..3289238eb5 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/ComponentProcesses.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/ComponentProcesses.java @@ -17,145 +17,124 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessEntityDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessRequestDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import java.util.List; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId}/processes") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Component Processes")}) @Validated public interface ComponentProcesses extends VspEntities { - @GET - @Path("/") - @Operation(description = "List vendor software product component processes", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProcessEntityDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - - @DELETE - @Path("/") - @Operation(description = "Delete vendor software product processes",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) - Response deleteList( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product process") - Response create(@Valid ProcessRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product component processes", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProcessEntityDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{processId}") - @Operation(description = "Get vendor software product process",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ProcessEntityDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/") + @Operation(description = "Delete vendor software product processes", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) + Response deleteList(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{processId}") - @Operation(description = "Delete vendor software product process") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product process") + Response create(@Valid ProcessRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{processId}") - @Operation(description = "Update vendor software product process") - Response update(@Valid ProcessRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{processId}") + @Operation(description = "Get vendor software product process", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ProcessEntityDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @DELETE + @Path("/{processId}") + @Operation(description = "Delete vendor software product process") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{processId}") + @Operation(description = "Update vendor software product process") + Response update(@Valid ProcessRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{processId}/upload") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get vendor software product process uploaded file") - Response getUploadedFile( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{processId}/upload") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Get vendor software product process uploaded file") + Response getUploadedFile(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{processId}/upload") - @Operation(description = "Delete vendor software product process uploaded file") - Response deleteUploadedFile( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{processId}/upload") + @Operation(description = "Delete vendor software product process uploaded file") + Response deleteUploadedFile(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/{processId}/upload") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Update vendor software product process upload") - Response uploadFile(@Multipart("upload") Attachment attachment, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product process Id") - @PathParam("processId") String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/{processId}/upload") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Update vendor software product process upload") + Response uploadFile(@Multipart("upload") Attachment attachment, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/Components.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/Components.java index fa0ecbdcbe..ccad46bb3e 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/Components.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/Components.java @@ -17,18 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentRequestDto; @@ -36,99 +51,72 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponse import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.IsValidJson; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import java.util.List; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Components")}) @Validated public interface Components extends VspEntities { - @GET - @Path("/") - @Operation(description = "List vendor software product components", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ComponentDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - - @DELETE - @Path("/") - @Operation(description = "Delete vendor software product components", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) - Response deleteList( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product component") - Response create(@Valid ComponentRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product components", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ComponentDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{componentId}") - @Operation(description = "Get vendor software product component", responses = @ApiResponse(content = @Content(schema = @Schema(implementation =ComponentData.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/") + @Operation(description = "Delete vendor software product components", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) + Response deleteList(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{componentId}") - @Operation(description = "Delete vendor software product component") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product component") + Response create(@Valid ComponentRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{componentId}") - @Operation(description = "Update vendor software product component") - Response update(@Valid ComponentRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{componentId}") + @Operation(description = "Get vendor software product component", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ComponentData.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @DELETE + @Path("/{componentId}") + @Operation(description = "Delete vendor software product component") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{componentId}") + @Operation(description = "Update vendor software product component") + Response update(@Valid ComponentRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{componentId}/questionnaire") - @Operation(description = "Get vendor software product component questionnaire",responses = @ApiResponse(content = @Content(schema = @Schema(implementation =QuestionnaireResponseDto.class)))) - Response getQuestionnaire( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{componentId}/questionnaire") + @Operation(description = "Get vendor software product component questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response getQuestionnaire(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{componentId}/questionnaire") - @Operation(description = "Update vendor software product component questionnaire") - Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") - String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") - String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{componentId}/questionnaire") + @Operation(description = "Update vendor software product component questionnaire") + Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/Compute.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/Compute.java index ded4327dd2..666fad5ea3 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/Compute.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/Compute.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,125 +17,104 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDetailsDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.IsValidJson; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - -@Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId" + - "}/compute-flavors") +@Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId" + "}/compute-flavors") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Component Compute-flavors")}) @Validated public interface Compute extends VspEntities { - @GET - @Path("/") - @Operation(description = "Get list of vendor software product component compute-flavors", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation =ComputeDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/") + @Operation(description = "Get list of vendor software product component compute-flavors", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ComputeDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{computeFlavorId}") - @Operation(description = "Get vendor software product component compute-flavor", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation =ComputeDetailsDto.class))))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product compute-flavor Id") @PathParam - ("computeFlavorId") - String computeId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{computeFlavorId}") + @Operation(description = "Get vendor software product component compute-flavor", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ComputeDetailsDto.class))))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product compute-flavor Id") @PathParam("computeFlavorId") String computeId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product component compute-flavor") - Response create(@Valid ComputeDetailsDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product component compute-flavor") + Response create(@Valid ComputeDetailsDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{computeFlavorId}") - @Operation(description = "Update vendor software product component compute-flavor") - Response update(@Valid ComputeDetailsDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product compute-flavor Id") @PathParam - ("computeFlavorId") - String computeFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @PUT + @Path("/{computeFlavorId}") + @Operation(description = "Update vendor software product component compute-flavor") + Response update(@Valid ComputeDetailsDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product compute-flavor Id") @PathParam("computeFlavorId") String computeFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{computeFlavorId}/questionnaire") - @Operation(description = "Update vendor software product component compute-flavor questionnaire") - Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product compute-flavor Id") @PathParam - ("computeFlavorId") - String computeFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @PUT + @Path("/{computeFlavorId}/questionnaire") + @Operation(description = "Update vendor software product component compute-flavor questionnaire") + Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product compute-flavor Id") @PathParam("computeFlavorId") String computeFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{computeFlavorId}") - @Operation(description = "Delete vendor software product component compute-flavor") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product compute-flavor Id") @PathParam - ("computeFlavorId") - String computeFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{computeFlavorId}") + @Operation(description = "Delete vendor software product component compute-flavor") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product compute-flavor Id") @PathParam("computeFlavorId") String computeFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{computeFlavorId}/questionnaire") - @Operation(description = "Get vendor software product component compute-flavor questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation =QuestionnaireResponseDto.class)))) - Response getQuestionnaire( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product compute-flavor Id") @PathParam - ("computeFlavorId") String computeId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{computeFlavorId}/questionnaire") + @Operation(description = "Get vendor software product component compute-flavor questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response getQuestionnaire(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product compute-flavor Id") @PathParam("computeFlavorId") String computeId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/DeploymentFlavors.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/DeploymentFlavors.java index 7d74044645..4312b10ab3 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/DeploymentFlavors.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/DeploymentFlavors.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorListResponseDto; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorListResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/deployment-flavors") @Produces(MediaType.APPLICATION_JSON) @@ -51,59 +55,49 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface DeploymentFlavors extends VspEntities { - @POST - @Path("/") - @Operation(description = "Create a vendor software product Deployment Flavor") - Response create(@Valid DeploymentFlavorRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @POST + @Path("/") + @Operation(description = "Create a vendor software product Deployment Flavor") + Response create(@Valid DeploymentFlavorRequestDto request, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/") + @Operation(description = "List vendor software product Deployment Flavor", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DeploymentFlavorListResponseDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/") - @Operation(description = "List vendor software product Deployment Flavor", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = DeploymentFlavorListResponseDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{deploymentFlavorId}") + @Operation(description = "Get vendor software product Deployment Flavor", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = DeploymentFlavorDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Deployment Flavor Id") @PathParam("deploymentFlavorId") String deploymentFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{deploymentFlavorId}") - @Operation(description = "Get vendor software product Deployment Flavor",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = DeploymentFlavorDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product Deployment Flavor Id") @PathParam - ("deploymentFlavorId") String deploymentFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/schema") + Response getSchema(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/schema") - Response getSchema(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String - vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{deploymentFlavorId}") + @Operation(description = "Delete vendor software product Deployment Flavor") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Deployment Flavor Id") @PathParam("deploymentFlavorId") String deploymentFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{deploymentFlavorId}") - @Operation(description = "Delete vendor software product Deployment Flavor") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product Deployment Flavor Id") - @PathParam("deploymentFlavorId") String deploymentFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - - @PUT - @Path("/{deploymentFlavorId}") - @Operation(description = "Update vendor software product Deployment Flavor") - Response update(@Valid DeploymentFlavorRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product Deployment Flavor Id") - @PathParam("deploymentFlavorId") String deploymentFlavorId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @PUT + @Path("/{deploymentFlavorId}") + @Operation(description = "Update vendor software product Deployment Flavor") + Response update(@Valid DeploymentFlavorRequestDto request, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product Deployment Flavor Id") @PathParam("deploymentFlavorId") String deploymentFlavorId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/Images.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/Images.java index 49a25ed273..f480405e45 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/Images.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/Images.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageRequestDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.IsValidJson; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId}/images") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -51,117 +56,90 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface Images extends VspEntities { - @GET - @Path("/") - @Operation(description = "List vendor software product component images",responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ImageDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - - @POST - @Path("/") - @Operation(description = "Create a vendor software product component image") - Response create(@Valid ImageRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product component images", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ImageDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/schema") - //@Operation(description = "Get schema for vendor software product component Image" , - // response = QuestionnaireResponseDto.class) - Response getImageSchema(@Parameter(description = "Vendor software product Id") @PathParam("vspId") - String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId,@NotNull - (message = USER_MISSING_ERROR_MSG) @HeaderParam - (USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product component image") + Response create(@Valid ImageRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - /*@GET - @Path("/{imageId}") - @Operation(description = "Get vendor software product component Image", - response = ImageDto.class, - responseContainer = "ImageEntityResponse") - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product image Id") @PathParam("imageId") - String imageId, - @Pattern(regexp = Version.VERSION_REGEX, - message = Version.VERSION_STRING_VIOLATION_MSG) @QueryParam("version") - String version, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user);*/ + @GET + @Path("/schema") + //@Operation(description = "Get schema for vendor software product component Image" , - @GET - @Path("/{imageId}") - @Operation(description = "Get vendor software product component Image",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ImageDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product Image Id") @PathParam - ("imageId") - String imageId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + // response = QuestionnaireResponseDto.class) + Response getImageSchema(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{imageId}") - @Operation(description = "Delete vendor software product Image") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product Image Id") @PathParam("imageId") - String imageId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + /*@GET + @Path("/{imageId}") + @Operation(description = "Get vendor software product component Image", + response = ImageDto.class, + responseContainer = "ImageEntityResponse") + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") + String componentId, + @Parameter(description = "Vendor software product image Id") @PathParam("imageId") + String imageId, + @Pattern(regexp = Version.VERSION_REGEX, + message = Version.VERSION_STRING_VIOLATION_MSG) @QueryParam("version") + String version, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) + String user);*/ + @GET + @Path("/{imageId}") + @Operation(description = "Get vendor software product component Image", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ImageDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product Image Id") @PathParam("imageId") String imageId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{imageId}") - @Operation(description = "Update vendor software product Image") - Response update(@Valid ImageRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product Image Id") @PathParam("imageId") - String imageId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{imageId}") + @Operation(description = "Delete vendor software product Image") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product Image Id") @PathParam("imageId") String imageId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{imageId}") + @Operation(description = "Update vendor software product Image") + Response update(@Valid ImageRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product Image Id") @PathParam("imageId") String imageId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{imageId}/questionnaire") - @Operation(description = "Update vendor software product component image questionnaire") - Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, - @Parameter(description = "Vendor software product Id") - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") - @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product image Id") - @PathParam ("imageId") String imageId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{imageId}/questionnaire") + @Operation(description = "Update vendor software product component image questionnaire") + Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product image Id") @PathParam("imageId") String imageId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{imageId}/questionnaire") - @Operation(description = "Get vendor software product component image questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) - Response getQuestionnaire( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product image Id") @PathParam - ("imageId") String imageId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{imageId}/questionnaire") + @Operation(description = "Get vendor software product component image questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response getQuestionnaire(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product image Id") @PathParam("imageId") String imageId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/Networks.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/Networks.java index f269832d6b..b2e356c23d 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/Networks.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/Networks.java @@ -17,30 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkRequestDto; -import org.springframework.validation.annotation.Validated; - import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkRequestDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/networks") @Produces(MediaType.APPLICATION_JSON) @@ -48,51 +53,42 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Networks")}) @Validated public interface Networks extends VspEntities { - @GET - @Path("/") - @Operation(description = "List vendor software product networks",responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NetworkDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product network") - Response create(@Valid NetworkRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product networks", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NetworkDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{networkId}") - @Operation(description = "Get vendor software product network",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = NetworkDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product network Id") - @PathParam("networkId") String networkId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product network") + Response create(@Valid NetworkRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{networkId}") - @Operation(description = "Delete vendor software product network") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product network Id") @PathParam("networkId") - String networkId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{networkId}") + @Operation(description = "Get vendor software product network", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = NetworkDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product network Id") @PathParam("networkId") String networkId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{networkId}") - @Operation(description = "Update vendor software product network") - Response update(@Valid NetworkRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product network Id") @PathParam("networkId") - String networkId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{networkId}") + @Operation(description = "Delete vendor software product network") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product network Id") @PathParam("networkId") String networkId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{networkId}") + @Operation(description = "Update vendor software product network") + Response update(@Valid NetworkRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product network Id") @PathParam("networkId") String networkId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/Nics.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/Nics.java index c50c593fce..8d0b8ca617 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/Nics.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/Nics.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,118 +17,104 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicRequestDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.IsValidJson; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/components/{componentId}/nics") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Component NICs")}) @Validated public interface Nics extends VspEntities { - @GET - @Path("/") - @Operation(description = "List vendor software product component NICs",responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NicDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product NIC") - Response create(@Valid NicRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product component NICs", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = NicDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{nicId}") - @Operation(description = "Get vendor software product NIC", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = NicDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product NIC") + Response create(@Valid NicRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{nicId}") - @Operation(description = "Delete vendor software product NIC") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") - String nicId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{nicId}") + @Operation(description = "Get vendor software product NIC", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = NicDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{nicId}") - @Operation(description = "Update vendor software product NIC") - Response update(@Valid NicRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") - String nicId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/{nicId}") + @Operation(description = "Delete vendor software product NIC") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{nicId}") + @Operation(description = "Update vendor software product NIC") + Response update(@Valid NicRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{nicId}/questionnaire") - @Operation(description = "Get vendor software product component NIC questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) - Response getQuestionnaire( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") @PathParam("componentId") - String componentId, - @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{nicId}/questionnaire") + @Operation(description = "Get vendor software product component NIC questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response getQuestionnaire(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{nicId}/questionnaire") - @Operation(description = "Update vendor software product component NIC questionnaire") - Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") - String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product component Id") - @PathParam("componentId") String componentId, - @Parameter(description = "Vendor software product NIC Id") - @PathParam("nicId") String nicId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @PUT + @Path("/{nicId}/questionnaire") + @Operation(description = "Update vendor software product component NIC questionnaire") + Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product component Id") @PathParam("componentId") String componentId, + @Parameter(description = "Vendor software product NIC Id") @PathParam("nicId") String nicId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/OrchestrationTemplateCandidate.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/OrchestrationTemplateCandidate.java index 5d99e2dc84..23c8ef2481 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/OrchestrationTemplateCandidate.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/OrchestrationTemplateCandidate.java @@ -13,35 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/orchestration-template-candidate") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -49,60 +54,44 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface OrchestrationTemplateCandidate extends VspEntities { - @POST - @Path("/") - @Consumes(MediaType.MULTIPART_FORM_DATA) - Response upload( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Multipart("upload") Attachment fileToUpload, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @POST + @Path("/") + @Consumes(MediaType.MULTIPART_FORM_DATA) + Response upload(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Multipart("upload") Attachment fileToUpload, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get uploaded Network Package file", - summary = "Downloads in uploaded Network Package file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation =File.class)))) - Response get( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws IOException; + @GET + @Path("/") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Get uploaded Network Package file", summary = "Downloads in uploaded Network Package file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response get(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws IOException; - @DELETE - @Path("/") - @Operation(description = "Delete orchestration template candidate file and its files data structure") - Response abort( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId) - throws Exception; + @DELETE + @Path("/") + @Operation(description = "Delete orchestration template candidate file and its files data structure") + Response abort(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId) + throws Exception; - @PUT - @Path("/process") - @Operation(description = "process Orchestration Template Candidate",responses = @ApiResponse(content = @Content(schema = @Schema(implementation =UploadFileResponseDto.class)))) - Response process( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws InvocationTargetException, IllegalAccessException; + @PUT + @Path("/process") + @Operation(description = "process Orchestration Template Candidate", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UploadFileResponseDto.class)))) + Response process(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) + throws InvocationTargetException, IllegalAccessException; - @PUT - @Path("/manifest") - @Operation(description = "Update an existing vendor software product") - Response updateFilesDataStructure( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @Valid FileDataStructureDto fileDataStructureDto, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws Exception; + @PUT + @Path("/manifest") + @Operation(description = "Update an existing vendor software product") + Response updateFilesDataStructure(@PathParam("vspId") String vspId, + @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @Valid FileDataStructureDto fileDataStructureDto, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; - @GET - @Path("/manifest") - @Operation(description = "Get uploaded HEAT file files data structure", - summary = "Downloads the latest HEAT package",responses = @ApiResponse(content = @Content(schema = @Schema(implementation =FileDataStructureDto.class)))) - Response getFilesDataStructure( - @PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws Exception; + @GET + @Path("/manifest") + @Operation(description = "Get uploaded HEAT file files data structure", summary = "Downloads the latest HEAT package", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = FileDataStructureDto.class)))) + Response getFilesDataStructure(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; } 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/Processes.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/Processes.java index 27195e1cbb..5f4c6496ec 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/Processes.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/Processes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,127 +17,115 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; +import java.util.List; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessEntityDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessRequestDto; import org.springframework.validation.annotation.Validated; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import java.util.List; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; - @Path("/v1.0/vendor-software-products/{vspId}/versions/{versionId}/processes") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Tags({@Tag(name = "SDCE-1 APIs"), @Tag(name = "Vendor Software Product Processes")}) @Validated public interface Processes { - @GET - @Path("/") - @Operation(description = "List vendor software product processes", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProcessEntityDto.class))))) - Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); - - @DELETE - @Path("/") - @Operation(description = "Delete vendor software product processes", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) - Response deleteList( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/") - @Operation(description = "Create a vendor software product process") - Response create(@Valid ProcessRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @GET + @Path("/") + @Operation(description = "List vendor software product processes", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProcessEntityDto.class))))) + Response list(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{processId}") - @Operation(description = "Get vendor software product process", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ProcessEntityDto.class)))) - Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @DELETE + @Path("/") + @Operation(description = "Delete vendor software product processes", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = List.class)))) + Response deleteList(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{processId}") - @Operation(description = "Delete vendor software product process") - Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/") + @Operation(description = "Create a vendor software product process") + Response create(@Valid ProcessRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @PUT - @Path("/{processId}") - @Operation(description = "Update vendor software product process") - Response update(@Valid ProcessRequestDto request, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @GET + @Path("/{processId}") + @Operation(description = "Get vendor software product process", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ProcessEntityDto.class)))) + Response get(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @DELETE + @Path("/{processId}") + @Operation(description = "Delete vendor software product process") + Response delete(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{processId}") + @Operation(description = "Update vendor software product process") + Response update(@Valid ProcessRequestDto request, @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @GET - @Path("/{processId}/upload") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get vendor software product process uploaded file") - Response getUploadedFile( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{processId}/upload") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Get vendor software product process uploaded file") + Response getUploadedFile(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @DELETE - @Path("/{processId}/upload") - @Operation(description = "Delete vendor software product process uploaded file") - Response deleteUploadedFile( - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") @PathParam("processId") - String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + @DELETE + @Path("/{processId}/upload") + @Operation(description = "Delete vendor software product process uploaded file") + Response deleteUploadedFile(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); - @POST - @Path("/{processId}/upload") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Update vendor software product process upload") - Response uploadFile(@Multipart("upload") Attachment attachment, - @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, - @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, - @Parameter(description = "Vendor software product process Id") - @PathParam("processId") String processId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) - String user); + @POST + @Path("/{processId}/upload") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Update vendor software product process upload") + Response uploadFile(@Multipart("upload") Attachment attachment, + @Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @Parameter(description = "Vendor software product version Id") @PathParam("versionId") String versionId, + @Parameter(description = "Vendor software product process Id") @PathParam("processId") String processId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/VendorSoftwareProducts.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/VendorSoftwareProducts.java index af9953ae69..328c96254f 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/VendorSoftwareProducts.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/VendorSoftwareProducts.java @@ -13,35 +13,45 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.item.types.ItemCreationDto; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.IsValidJson; -import org.springframework.validation.annotation.Validated; - +import java.io.File; +import java.io.IOException; import javax.validation.Valid; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.item.types.ItemCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; +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.vendorsoftwareproducts.types.validation.IsValidJson; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-software-products") @Produces(MediaType.APPLICATION_JSON) @@ -50,145 +60,105 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface VendorSoftwareProducts extends VspEntities { - @POST - @Path("/") - @Operation(description = "Create a new vendor software product",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ItemCreationDto.class)))) - Response createVsp(@Valid VspRequestDto vspRequestDto, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/") - @Operation(description = "Get list of vendor software products and their description",responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = VspDetailsDto.class))))) - Response listVsps(@Parameter(description = "Filter to return only Vendor Software Products with at" + - " least one version at this status. Currently supported values: 'Certified' , 'Draft'") - @QueryParam("versionFilter") String versionStatus, - @Parameter(description = "Filter to only return Vendor Software Products at this status." + - "Currently supported values: 'ACTIVE' , 'ARCHIVED'." + - "Default value = 'ACTIVE'.") - @QueryParam("Status") String itemStatus, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/{vspId}/versions/{versionId}") - @Parameter(description = "Get details of a vendor software product") - Response getVsp(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @PUT - @Path("/{vspId}/versions/{versionId}") - @Parameter(description = "Update an existing vendor software product") - Response updateVsp(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @Valid VspDescriptionDto vspDescriptionDto, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @DELETE - @Path("/{vspId}") - @Parameter(description = "Deletes vendor software product by given id") - Response deleteVsp(@PathParam("vspId") String vspId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/packages") - @Operation(description = "Get list of translated CSAR files details", responses = @ApiResponse(content = @Content(array = @ArraySchema( schema = @Schema(implementation=PackageInfoDto.class))))) - Response listPackages(@Parameter(description = "Vendor Software Product status filter. " + - "Currently supported values: 'ACTIVE', 'ARCHIVED'") - @QueryParam("Status") String status, - @Parameter(description = "Category") @QueryParam("category") String category, - @Parameter(description = "Sub-category") @QueryParam("subCategory") String subCategory, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/{vspId}/versions/{versionId}/orchestration-template") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get Orchestration Template (HEAT) file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation=File.class)))) - Response getOrchestrationTemplate( - @PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - - @GET - @Path("/validation-vsp") - Response getValidationVsp( - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws Exception; - - @PUT - @Path("/{vspId}/versions/{versionId}/actions") - @Operation(description = "Actions on a vendor software product", - summary = "Performs one of the following actions on a vendor software product: |" - + "Checkout: Locks it for edits by other users. Only the locking user sees the edited " - + "version.|" - + "Undo_Checkout: Unlocks it and deletes the edits that were done.|" - + "Checkin: Unlocks it and activates the edited version to all users.| " - + "Submit: Finalize its active version.|" - + "Create_Package: Creates a CSAR zip file.|") - Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, - @PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user) - throws IOException; - - @GET - @Path("/packages/{vspId}") - @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get translated CSAR file", - summary = "Exports translated file to a zip file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation=File.class)))) - Response getTranslatedFile(@PathParam("vspId") String vspId, - @QueryParam("versionId") String versionId, - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/{vspId}/versions/{versionId}/questionnaire") - @Operation(description = "Get vendor software product questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation=QuestionnaireResponseDto.class)))) - Response getQuestionnaire(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @PUT - @Path("/{vspId}/versions/{versionId}/questionnaire") - @Operation(description = "Update vendor software product questionnaire") - Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, - @PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) + @POST + @Path("/") + @Operation(description = "Create a new vendor software product", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = ItemCreationDto.class)))) + Response createVsp(@Valid VspRequestDto vspRequestDto, @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/") + @Operation(description = "Get list of vendor software products and their description", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = VspDetailsDto.class))))) + Response listVsps(@Parameter(description = "Filter to return only Vendor Software Products with at" + + " least one version at this status. Currently supported values: 'Certified' , 'Draft'") @QueryParam("versionFilter") String versionStatus, + @Parameter(description = "Filter to only return Vendor Software Products at this status." + + "Currently supported values: 'ACTIVE' , 'ARCHIVED'." + + "Default value = 'ACTIVE'.") @QueryParam("Status") String itemStatus, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{vspId}/versions/{versionId}") + @Parameter(description = "Get details of a vendor software product") + Response getVsp(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{vspId}/versions/{versionId}") + @Parameter(description = "Update an existing vendor software product") + Response updateVsp(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, @Valid VspDescriptionDto vspDescriptionDto, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @DELETE + @Path("/{vspId}") + @Parameter(description = "Deletes vendor software product by given id") + Response deleteVsp(@PathParam("vspId") String vspId, @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/packages") + @Operation(description = "Get list of translated CSAR files details", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = PackageInfoDto.class))))) + Response listPackages(@Parameter(description = "Vendor Software Product status filter. " + + "Currently supported values: 'ACTIVE', 'ARCHIVED'") @QueryParam("Status") String status, + @Parameter(description = "Category") @QueryParam("category") String category, + @Parameter(description = "Sub-category") @QueryParam("subCategory") String subCategory, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{vspId}/versions/{versionId}/orchestration-template") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Get Orchestration Template (HEAT) file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response getOrchestrationTemplate(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/validation-vsp") + Response getValidationVsp(@NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; + + @PUT + @Path("/{vspId}/versions/{versionId}/actions") + @Operation(description = "Actions on a vendor software product", summary = "Performs one of the following actions on a vendor software product: |" + + "Checkout: Locks it for edits by other users. Only the locking user sees the edited " + "version.|" + + "Undo_Checkout: Unlocks it and deletes the edits that were done.|" + "Checkin: Unlocks it and activates the edited version to all users.| " + + "Submit: Finalize its active version.|" + "Create_Package: Creates a CSAR zip file.|") + Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, @PathParam("vspId") String vspId, + @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws IOException; + + @GET + @Path("/packages/{vspId}") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + @Operation(description = "Get translated CSAR file", summary = "Exports translated file to a zip file", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response getTranslatedFile(@PathParam("vspId") String vspId, @QueryParam("versionId") String versionId, @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @PUT - @Path("/{vspId}/versions/{versionId}/heal") - @Operation(description = "Checkout and heal vendor software product questionnaire",responses = @ApiResponse(content = @Content(schema = @Schema(implementation=QuestionnaireResponseDto.class)))) - Response heal(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - - @GET - @Path("/{vspId}/versions/{versionId}/vspInformationArtifact") - @Produces(MediaType.TEXT_PLAIN) - @Operation(description = "Get vendor software product information artifact for specified version",responses = @ApiResponse(content = @Content(schema = @Schema(implementation=File.class)))) - Response getVspInformationArtifact(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - @GET - @Path("/{vspId}/versions/{versionId}/compute-flavors") - @Operation(description = "Get list of vendor software product compute-flavors", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation=VspComputeDto.class))))) - Response listComputes(@Parameter(description = "Vendor software product Id") - @PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); + @GET + @Path("/{vspId}/versions/{versionId}/questionnaire") + @Operation(description = "Get vendor software product questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response getQuestionnaire(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{vspId}/versions/{versionId}/questionnaire") + @Operation(description = "Update vendor software product questionnaire") + Response updateQuestionnaire(@NotNull @IsValidJson String questionnaireData, @PathParam("vspId") String vspId, + @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @PUT + @Path("/{vspId}/versions/{versionId}/heal") + @Operation(description = "Checkout and heal vendor software product questionnaire", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = QuestionnaireResponseDto.class)))) + Response heal(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{vspId}/versions/{versionId}/vspInformationArtifact") + @Produces(MediaType.TEXT_PLAIN) + @Operation(description = "Get vendor software product information artifact for specified version", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response getVspInformationArtifact(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); + + @GET + @Path("/{vspId}/versions/{versionId}/compute-flavors") + @Operation(description = "Get list of vendor software product compute-flavors", responses = @ApiResponse(content = @Content(array = @ArraySchema(schema = @Schema(implementation = VspComputeDto.class))))) + Response listComputes(@Parameter(description = "Vendor software product Id") @PathParam("vspId") String vspId, + @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); } 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/VendorSoftwareProductsForSwaggerFileUpload.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/VendorSoftwareProductsForSwaggerFileUpload.java index cc94725501..70de99035b 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/VendorSoftwareProductsForSwaggerFileUpload.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/VendorSoftwareProductsForSwaggerFileUpload.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; +import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; +import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; + import com.sun.jersey.multipart.FormDataParam; import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tags; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; -import org.springframework.validation.annotation.Validated; - +import java.io.InputStream; import javax.validation.constraints.NotNull; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.io.InputStream; - -import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; -import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; +import org.springframework.validation.annotation.Validated; @Path("/v1.0/vendor-software-products") @Produces(MediaType.APPLICATION_JSON) @@ -47,17 +49,11 @@ import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG @Validated public interface VendorSoftwareProductsForSwaggerFileUpload { - - - @POST - @Path("/{vspId}/versions/{versionId}/orchestration-template-candidate") - @Consumes(MediaType.MULTIPART_FORM_DATA) - @Operation(description = "Uploads a HEAT package to translate",responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UploadFileResponseDto.class)))) - Response uploadOrchestrationTemplateCandidate(@PathParam("vspId") String vspId, - @PathParam("versionId") String versionId, - @FormDataParam("upload") - InputStream heatFileToUpload, - @NotNull(message = USER_MISSING_ERROR_MSG) - @HeaderParam(USER_ID_HEADER_PARAM) String user); - - } + @POST + @Path("/{vspId}/versions/{versionId}/orchestration-template-candidate") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Operation(description = "Uploads a HEAT package to translate", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UploadFileResponseDto.class)))) + Response uploadOrchestrationTemplateCandidate(@PathParam("vspId") String vspId, @PathParam("versionId") String versionId, + @FormDataParam("upload") InputStream heatFileToUpload, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user); +} 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/VspEntities.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/VspEntities.java index 4514af649b..92b0dec6e3 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/VspEntities.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/VspEntities.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest; public interface VspEntities { 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/mapping/MapComponentDataToComponentDto.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/mapping/MapComponentDataToComponentDto.java index eae59cf103..ac6b3a887f 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/mapping/MapComponentDataToComponentDto.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/mapping/MapComponentDataToComponentDto.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; @@ -21,11 +20,11 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDto; public class MapComponentDataToComponentDto extends MappingBase { - @Override - public void doMapping(ComponentData source, ComponentDto target) { - target.setName(source.getName()); - target.setDisplayName( - source.getDisplayName() == null ? source.getName() : source.getDisplayName()); - target.setDescription(source.getDescription()); - } + + @Override + public void doMapping(ComponentData source, ComponentDto target) { + target.setName(source.getName()); + target.setDisplayName(source.getDisplayName() == null ? source.getName() : source.getDisplayName()); + target.setDescription(source.getDescription()); + } } 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/mapping/MapComponentDependencyEntityToCreationDto.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/mapping/MapComponentDependencyEntityToCreationDto.java index a82902bd84..e69d6a9380 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/mapping/MapComponentDependencyEntityToCreationDto.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/mapping/MapComponentDependencyEntityToCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; - import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyCreationDto; -public class MapComponentDependencyEntityToCreationDto extends MappingBase - { +public class MapComponentDependencyEntityToCreationDto extends MappingBase { - @Override - public void doMapping(ComponentDependencyModelEntity source, - ComponentDependencyCreationDto target) { - target.setId(source.getId()); - } + @Override + public void doMapping(ComponentDependencyModelEntity source, ComponentDependencyCreationDto target) { + target.setId(source.getId()); + } } 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/mapping/MapComponentDependencyEntityToDto.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/mapping/MapComponentDependencyEntityToDto.java index 1fdadcbc88..aedd06be69 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/mapping/MapComponentDependencyEntityToDto.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/mapping/MapComponentDependencyEntityToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyResponseDto; -public class MapComponentDependencyEntityToDto extends - MappingBase { +public class MapComponentDependencyEntityToDto extends MappingBase { - @Override - public void doMapping(ComponentDependencyModelEntity source, - ComponentDependencyResponseDto target) { - target.setSourceId(source.getSourceComponentId()); - target.setTargetId(source.getTargetComponentId()); - target.setRelationType(source.getRelation()); - target.setId(source.getId()); - } + @Override + public void doMapping(ComponentDependencyModelEntity source, ComponentDependencyResponseDto target) { + target.setSourceId(source.getSourceComponentId()); + target.setTargetId(source.getTargetComponentId()); + target.setRelationType(source.getRelation()); + target.setId(source.getId()); + } } 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/mapping/MapComponentDependencyModelEntityToDto.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/mapping/MapComponentDependencyModelEntityToDto.java index c4c54d4ed8..bcfe05da83 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/mapping/MapComponentDependencyModelEntityToDto.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/mapping/MapComponentDependencyModelEntityToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyModel; -public class MapComponentDependencyModelEntityToDto extends - MappingBase { +public class MapComponentDependencyModelEntityToDto extends MappingBase { - @Override - public void doMapping(ComponentDependencyModelEntity source, - ComponentDependencyModel target) { - target.setSourceId(source.getSourceComponentId()); - target.setTargetId(source.getTargetComponentId()); - target.setRelationType(source.getRelation()); - } + @Override + public void doMapping(ComponentDependencyModelEntity source, ComponentDependencyModel target) { + target.setSourceId(source.getSourceComponentId()); + target.setTargetId(source.getTargetComponentId()); + target.setRelationType(source.getRelation()); + } } 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/mapping/MapComponentDependencyModelRequestToEntity.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/mapping/MapComponentDependencyModelRequestToEntity.java index 4988ab43ab..73ef053455 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/mapping/MapComponentDependencyModelRequestToEntity.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/mapping/MapComponentDependencyModelRequestToEntity.java @@ -12,11 +12,9 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdcrests.vsp.rest.mapping; - import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; @@ -25,21 +23,18 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDependencyModel; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentRelationType; -public class MapComponentDependencyModelRequestToEntity extends - MappingBase { +public class MapComponentDependencyModelRequestToEntity extends MappingBase { - @Override - public void doMapping(ComponentDependencyModel source, - ComponentDependencyModelEntity target) { - target.setSourceComponentId(source.getSourceId()); - target.setTargetComponentId(source.getTargetId()); - try { - ComponentRelationType.valueOf(source.getRelationType()); - target.setRelation(source.getRelationType()); - } catch (IllegalArgumentException exception) { - ErrorCode errorCode = - ComponentDependencyModelErrorBuilder.getInvalidRelationTypeErrorBuilder(); - throw new CoreException(errorCode, exception); + @Override + public void doMapping(ComponentDependencyModel source, ComponentDependencyModelEntity target) { + target.setSourceComponentId(source.getSourceId()); + target.setTargetComponentId(source.getTargetId()); + try { + ComponentRelationType.valueOf(source.getRelationType()); + target.setRelation(source.getRelationType()); + } catch (IllegalArgumentException exception) { + ErrorCode errorCode = ComponentDependencyModelErrorBuilder.getInvalidRelationTypeErrorBuilder(); + throw new CoreException(errorCode, exception); + } } - } } 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/mapping/MapComponentEntityToComponentCreationDto.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/mapping/MapComponentEntityToComponentCreationDto.java index f2f346891f..089a91694e 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/mapping/MapComponentEntityToComponentCreationDto.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/mapping/MapComponentEntityToComponentCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentCreationDto; -public class MapComponentEntityToComponentCreationDto extends MappingBase { - @Override - public void doMapping(ComponentEntity source, ComponentCreationDto target) { - target.setVfcId(source.getId()); - } +public class MapComponentEntityToComponentCreationDto extends MappingBase { + + @Override + public void doMapping(ComponentEntity source, ComponentCreationDto target) { + target.setVfcId(source.getId()); + } } 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/mapping/MapComponentEntityToComponentDto.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/mapping/MapComponentEntityToComponentDto.java index 8878581d1c..e82363eae9 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/mapping/MapComponentEntityToComponentDto.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/mapping/MapComponentEntityToComponentDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -26,12 +25,13 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDto; public class MapComponentEntityToComponentDto extends MappingBase { - @Override - public void doMapping(ComponentEntity source, ComponentDto target) { - target.setId(source.getId()); - ComponentData component = source.getComponentCompositionData(); - if (component != null) { - new MapComponentDataToComponentDto().doMapping(component, target); + + @Override + public void doMapping(ComponentEntity source, ComponentDto target) { + target.setId(source.getId()); + ComponentData component = source.getComponentCompositionData(); + if (component != null) { + new MapComponentDataToComponentDto().doMapping(component, target); + } } - } } 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/mapping/MapComponentRequestDtoToComponentEntity.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/mapping/MapComponentRequestDtoToComponentEntity.java index 53a4482820..a890d0d737 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/mapping/MapComponentRequestDtoToComponentEntity.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/mapping/MapComponentRequestDtoToComponentEntity.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -21,14 +20,14 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentRequestDto; -public class MapComponentRequestDtoToComponentEntity - extends MappingBase { - @Override - public void doMapping(ComponentRequestDto source, ComponentEntity target) { - ComponentData component = new ComponentData(); - component.setName(source.getName()); - component.setDisplayName(source.getDisplayName()); - component.setDescription(source.getDescription()); - target.setComponentCompositionData(component); - } +public class MapComponentRequestDtoToComponentEntity extends MappingBase { + + @Override + public void doMapping(ComponentRequestDto source, ComponentEntity target) { + ComponentData component = new ComponentData(); + component.setName(source.getName()); + component.setDisplayName(source.getDisplayName()); + component.setDescription(source.getDescription()); + target.setComponentCompositionData(component); + } } 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/mapping/MapCompositionEntityResponseToDto.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/mapping/MapCompositionEntityResponseToDto.java index f7ecc243f1..743723771d 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/mapping/MapCompositionEntityResponseToDto.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/mapping/MapCompositionEntityResponseToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; @@ -26,22 +25,21 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionDataEntityDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityResponseDto; -public class MapCompositionEntityResponseToDto> - extends MappingBase, CompositionEntityResponseDto> { - private M dataMapper; - private Class targetDataClass; +public class MapCompositionEntityResponseToDto> extends + MappingBase, CompositionEntityResponseDto> { + + private M dataMapper; + private Class targetDataClass; - public MapCompositionEntityResponseToDto(M dataMapper, Class targetDataClass) { - this.dataMapper = dataMapper; - this.targetDataClass = targetDataClass; - } + public MapCompositionEntityResponseToDto(M dataMapper, Class targetDataClass) { + this.dataMapper = dataMapper; + this.targetDataClass = targetDataClass; + } - @Override - public void doMapping(CompositionEntityResponse source, - CompositionEntityResponseDto target) { - target.setId(source.getId()); - target.setSchema(source.getSchema()); - target.setData(dataMapper.applyMapping(source.getData(), targetDataClass)); - } + @Override + public void doMapping(CompositionEntityResponse source, CompositionEntityResponseDto target) { + target.setId(source.getId()); + target.setSchema(source.getSchema()); + target.setData(dataMapper.applyMapping(source.getData(), targetDataClass)); + } } 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/mapping/MapCompositionEntityValidationDataToDto.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/mapping/MapCompositionEntityValidationDataToDto.java index ee7a9f446e..00c5c2f266 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/mapping/MapCompositionEntityValidationDataToDto.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/mapping/MapCompositionEntityValidationDataToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; -import java.util.stream.Collectors; +public class MapCompositionEntityValidationDataToDto extends MappingBase { -public class MapCompositionEntityValidationDataToDto - extends MappingBase { - @Override - public void doMapping(CompositionEntityValidationData source, - CompositionEntityValidationDataDto target) { - target.setEntityType(source.getEntityType()); - target.setEntityId(source.getEntityId()); - target.setEntityName(source.getEntityName()); - target.setErrors(source.getErrors()); - if (CollectionUtils.isNotEmpty(source.getSubEntitiesValidationData())) { - target.setSubEntitiesValidationData(source.getSubEntitiesValidationData().stream() - .map(sub -> applyMapping(sub, CompositionEntityValidationDataDto.class)) - .collect(Collectors.toList())); + @Override + public void doMapping(CompositionEntityValidationData source, CompositionEntityValidationDataDto target) { + target.setEntityType(source.getEntityType()); + target.setEntityId(source.getEntityId()); + target.setEntityName(source.getEntityName()); + target.setErrors(source.getErrors()); + if (CollectionUtils.isNotEmpty(source.getSubEntitiesValidationData())) { + target.setSubEntitiesValidationData( + source.getSubEntitiesValidationData().stream().map(sub -> applyMapping(sub, CompositionEntityValidationDataDto.class)) + .collect(Collectors.toList())); + } } - } } 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/mapping/MapComputeDataToComputeDetailsDto.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/mapping/MapComputeDataToComputeDetailsDto.java index 3bfecb93f5..a32f4fb076 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/mapping/MapComputeDataToComputeDetailsDto.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/mapping/MapComputeDataToComputeDetailsDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; @@ -26,10 +25,9 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDetailsDto; public class MapComputeDataToComputeDetailsDto extends MappingBase { - @Override - public void doMapping(ComputeData source, ComputeDetailsDto target) { - - target.setName(source.getName()); - target.setDescription(source.getDescription()); - } + @Override + public void doMapping(ComputeData source, ComputeDetailsDto target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + } } 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/mapping/MapComputeDetailsDtoToComputeEntity.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/mapping/MapComputeDetailsDtoToComputeEntity.java index 93db7e3e76..835f5dd05d 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/mapping/MapComputeDetailsDtoToComputeEntity.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/mapping/MapComputeDetailsDtoToComputeEntity.java @@ -21,13 +21,11 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDescription; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDetailsDto; -public class MapComputeDetailsDtoToComputeEntity extends MappingBase { +public class MapComputeDetailsDtoToComputeEntity extends MappingBase { - @Override - public void doMapping(ComputeDetailsDto source, ComputeEntity target) { - ComputeDescription computeDesc = new ComputeDescription(source.getName(), source - .getDescription()); - target.setCompositionData(JsonUtil.object2Json(computeDesc)); - } + @Override + public void doMapping(ComputeDetailsDto source, ComputeEntity target) { + ComputeDescription computeDesc = new ComputeDescription(source.getName(), source.getDescription()); + target.setCompositionData(JsonUtil.object2Json(computeDesc)); + } } 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/mapping/MapComputeEntityToComputeCreationDto.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/mapping/MapComputeEntityToComputeCreationDto.java index 4e1599d058..531c28b48a 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/mapping/MapComputeEntityToComputeCreationDto.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/mapping/MapComputeEntityToComputeCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeCreationDto; -public class MapComputeEntityToComputeCreationDto extends - MappingBase { - @Override - public void doMapping(ComputeEntity source, ComputeCreationDto target) { - target.setId(source.getId()); - } +public class MapComputeEntityToComputeCreationDto extends MappingBase { + + @Override + public void doMapping(ComputeEntity source, ComputeCreationDto target) { + target.setId(source.getId()); + } } 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/mapping/MapComputeEntityToComputeDto.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/mapping/MapComputeEntityToComputeDto.java index cd67d2444b..a2cdceb060 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/mapping/MapComputeEntityToComputeDto.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/mapping/MapComputeEntityToComputeDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.core.utilities.json.JsonUtil; @@ -27,15 +26,15 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDescription; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDto; public class MapComputeEntityToComputeDto extends MappingBase { - @Override - public void doMapping(ListComputeResponse source, ComputeDto target) { - target.setId(source.getComputeEntity().getId()); - if (source.getComputeEntity().getCompositionData() != null) { - ComputeDescription desc = JsonUtil.json2Object(source.getComputeEntity().getCompositionData - (), ComputeDescription.class); - target.setName(desc.getName()); - target.setDescription(desc.getDescription()); - target.setAssociatedToDeploymentFlavor(source.isAssociatedWithDeploymentFlavor()); + + @Override + public void doMapping(ListComputeResponse source, ComputeDto target) { + target.setId(source.getComputeEntity().getId()); + if (source.getComputeEntity().getCompositionData() != null) { + ComputeDescription desc = JsonUtil.json2Object(source.getComputeEntity().getCompositionData(), ComputeDescription.class); + target.setName(desc.getName()); + target.setDescription(desc.getDescription()); + target.setAssociatedToDeploymentFlavor(source.isAssociatedWithDeploymentFlavor()); + } } - } } 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/mapping/MapComputeEntityToVspComputeDto.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/mapping/MapComputeEntityToVspComputeDto.java index c75266f756..108d6438b5 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/mapping/MapComputeEntityToVspComputeDto.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/mapping/MapComputeEntityToVspComputeDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.core.utilities.json.JsonUtil; @@ -27,14 +26,14 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDescription; import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspComputeDto; public class MapComputeEntityToVspComputeDto extends MappingBase { - @Override - public void doMapping(ComputeEntity source, VspComputeDto target) { - target.setComputeFlavorId(source.getId()); - if (source.getCompositionData() != null) { - ComputeDescription desc = JsonUtil.json2Object(source.getCompositionData(), ComputeDescription - .class); - target.setName(desc.getName()); - target.setComponentId(source.getComponentId()); + + @Override + public void doMapping(ComputeEntity source, VspComputeDto target) { + target.setComputeFlavorId(source.getId()); + if (source.getCompositionData() != null) { + ComputeDescription desc = JsonUtil.json2Object(source.getCompositionData(), ComputeDescription.class); + target.setName(desc.getName()); + target.setComponentId(source.getComponentId()); + } } - } } 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/mapping/MapDeploymentFlavorEntityDeploymentFlavorToListResponse.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/mapping/MapDeploymentFlavorEntityDeploymentFlavorToListResponse.java index 42ff7c9058..292ee88ef9 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/mapping/MapDeploymentFlavorEntityDeploymentFlavorToListResponse.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/mapping/MapDeploymentFlavorEntityDeploymentFlavorToListResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; @@ -25,18 +24,15 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavo import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorListResponseDto; -public class MapDeploymentFlavorEntityDeploymentFlavorToListResponse extends - MappingBase { - - @Override - public void doMapping(DeploymentFlavorEntity source, - DeploymentFlavorListResponseDto target) { - target.setId(source.getId()); - DeploymentFlavor deploymentFlavor = source.getDeploymentFlavorCompositionData(); +public class MapDeploymentFlavorEntityDeploymentFlavorToListResponse extends MappingBase { - if (deploymentFlavor != null) { - target.setModel(deploymentFlavor.getModel()); - target.setDescription(deploymentFlavor.getDescription()); + @Override + public void doMapping(DeploymentFlavorEntity source, DeploymentFlavorListResponseDto target) { + target.setId(source.getId()); + DeploymentFlavor deploymentFlavor = source.getDeploymentFlavorCompositionData(); + if (deploymentFlavor != null) { + target.setModel(deploymentFlavor.getModel()); + target.setDescription(deploymentFlavor.getDescription()); + } } - } } 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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorCreationDto.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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorCreationDto.java index 05fa35d0ba..80b6649005 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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorCreationDto.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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorCreationDto; +public class MapDeploymentFlavorEntityToDeploymentFlavorCreationDto extends MappingBase { -public class MapDeploymentFlavorEntityToDeploymentFlavorCreationDto extends MappingBase { - - @Override - public void doMapping(DeploymentFlavorEntity source, - DeploymentFlavorCreationDto target) { - target.setDeploymentFlavorId(source.getId()); - } + @Override + public void doMapping(DeploymentFlavorEntity source, DeploymentFlavorCreationDto target) { + target.setDeploymentFlavorId(source.getId()); + } } 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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorDto.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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorDto.java index 188ff82636..dbf9b2adf9 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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorDto.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/mapping/MapDeploymentFlavorEntityToDeploymentFlavorDto.java @@ -13,19 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.mapping; - import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; -public class MapDeploymentFlavorEntityToDeploymentFlavorDto extends - MappingBase { - @Override - public void doMapping(DeploymentFlavorEntity source, DeploymentFlavorDto target) { - target.setId(source.getId()); +public class MapDeploymentFlavorEntityToDeploymentFlavorDto extends MappingBase { - } + @Override + public void doMapping(DeploymentFlavorEntity source, DeploymentFlavorDto target) { + target.setId(source.getId()); + } } 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/mapping/MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity.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/mapping/MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity.java index 97ccf28def..6bd60b81a2 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/mapping/MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity.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/mapping/MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; @@ -25,16 +24,15 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavo import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorRequestDto; -public class MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity - extends MappingBase { +public class MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity extends MappingBase { - @Override - public void doMapping(DeploymentFlavorRequestDto source, DeploymentFlavorEntity target) { - DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); - deploymentFlavor.setModel(source.getModel()); - deploymentFlavor.setDescription(source.getDescription()); - deploymentFlavor.setFeatureGroupId(source.getFeatureGroupId()); - deploymentFlavor.setComponentComputeAssociations(source.getComponentComputeAssociations()); - target.setDeploymentFlavorCompositionData(deploymentFlavor); - } + @Override + public void doMapping(DeploymentFlavorRequestDto source, DeploymentFlavorEntity target) { + DeploymentFlavor deploymentFlavor = new DeploymentFlavor(); + deploymentFlavor.setModel(source.getModel()); + deploymentFlavor.setDescription(source.getDescription()); + deploymentFlavor.setFeatureGroupId(source.getFeatureGroupId()); + deploymentFlavor.setComponentComputeAssociations(source.getComponentComputeAssociations()); + target.setDeploymentFlavorCompositionData(deploymentFlavor); + } } 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/mapping/MapDeploymentFlavorToDeploymentDto.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/mapping/MapDeploymentFlavorToDeploymentDto.java index 06d299c805..b26669e511 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/mapping/MapDeploymentFlavorToDeploymentDto.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/mapping/MapDeploymentFlavorToDeploymentDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; - public class MapDeploymentFlavorToDeploymentDto extends MappingBase { - @Override - public void doMapping(DeploymentFlavor source, DeploymentFlavorDto target) { - target.setModel(source.getModel()); - target.setDescription(source.getDescription()); - target.setFeatureGroupId(source.getFeatureGroupId()); - target.setComponentComputeAssociations(source.getComponentComputeAssociations()); - } + + @Override + public void doMapping(DeploymentFlavor source, DeploymentFlavorDto target) { + target.setModel(source.getModel()); + target.setDescription(source.getDescription()); + target.setFeatureGroupId(source.getFeatureGroupId()); + target.setComponentComputeAssociations(source.getComponentComputeAssociations()); + } } 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/mapping/MapFilesDataStructureToDto.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/mapping/MapFilesDataStructureToDto.java index c8734ff8ee..a769a4ed1b 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/mapping/MapFilesDataStructureToDto.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/mapping/MapFilesDataStructureToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto; -public class MapFilesDataStructureToDto - extends MappingBase { +public class MapFilesDataStructureToDto extends MappingBase { - @Override - public void doMapping(FilesDataStructure source, FileDataStructureDto target) { - target.setModules(source.getModules()); - target.setArtifacts(source.getArtifacts()); - target.setNested(source.getNested()); - target.setUnassigned(source.getUnassigned()); - } + @Override + public void doMapping(FilesDataStructure source, FileDataStructureDto target) { + target.setModules(source.getModules()); + target.setArtifacts(source.getArtifacts()); + target.setNested(source.getNested()); + target.setUnassigned(source.getUnassigned()); + } } 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/mapping/MapImageDataToImageDto.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/mapping/MapImageDataToImageDto.java index 4df6eb3de9..005de5fe9c 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/mapping/MapImageDataToImageDto.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/mapping/MapImageDataToImageDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ImageData; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageDto; - public class MapImageDataToImageDto extends MappingBase { - @Override - public void doMapping(ImageData source, ImageDto target) { - target.setFileName(source.getFileName()); - target.setDescription(source.getDescription()); - } + @Override + public void doMapping(ImageData source, ImageDto target) { + target.setFileName(source.getFileName()); + target.setDescription(source.getDescription()); + } } - - - - - - 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/mapping/MapImageEntityToImageCreationDto.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/mapping/MapImageEntityToImageCreationDto.java index cc15ef0898..5a811b2228 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/mapping/MapImageEntityToImageCreationDto.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/mapping/MapImageEntityToImageCreationDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageCreationDto; -public class MapImageEntityToImageCreationDto extends MappingBase { +public class MapImageEntityToImageCreationDto extends MappingBase { - @Override - public void doMapping(ImageEntity source, ImageCreationDto target) { - target.setId(source.getId()); - } + @Override + public void doMapping(ImageEntity source, ImageCreationDto target) { + target.setId(source.getId()); + } } 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/mapping/MapImageEntityToImageDto.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/mapping/MapImageEntityToImageDto.java index b35a0f2a38..d17735483f 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/mapping/MapImageEntityToImageDto.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/mapping/MapImageEntityToImageDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; @@ -27,14 +26,14 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageDto; public class MapImageEntityToImageDto extends MappingBase { - @Override - public void doMapping(ImageEntity source, ImageDto target) { - target.setId(source.getId()); - Image image = source.getImageCompositionData(); - if (image != null) { - ImageData imageData = new ImageData(image.getFileName(), image.getDescription()); - new MapImageDataToImageDto().doMapping(imageData, target); + @Override + public void doMapping(ImageEntity source, ImageDto target) { + target.setId(source.getId()); + Image image = source.getImageCompositionData(); + if (image != null) { + ImageData imageData = new ImageData(image.getFileName(), image.getDescription()); + new MapImageDataToImageDto().doMapping(imageData, target); + } } - } } 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/mapping/MapImageRequestDtoToImageEntity.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/mapping/MapImageRequestDtoToImageEntity.java index 3e1c126226..fa2f432e89 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/mapping/MapImageRequestDtoToImageEntity.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/mapping/MapImageRequestDtoToImageEntity.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; @@ -23,12 +22,11 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageRequestDto; public class MapImageRequestDtoToImageEntity extends MappingBase { - @Override - public void doMapping(ImageRequestDto source, ImageEntity target) { - Image image = new Image(); - image.setFileName(source.getFileName()); - image.setDescription(source.getDescription()); - target.setImageCompositionData(image); - } - + @Override + public void doMapping(ImageRequestDto source, ImageEntity target) { + Image image = new Image(); + image.setFileName(source.getFileName()); + image.setDescription(source.getDescription()); + target.setImageCompositionData(image); + } } 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/mapping/MapItemToVspDetailsDto.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/mapping/MapItemToVspDetailsDto.java index 926f1f0b25..e0966e8350 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/mapping/MapItemToVspDetailsDto.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/mapping/MapItemToVspDetailsDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.versioning.types.Item; @@ -26,15 +25,16 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto; import org.openecomp.sdcrests.vsp.rest.services.VspItemProperty; public class MapItemToVspDetailsDto extends MappingBase { - @Override - public void doMapping(Item source, VspDetailsDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setVendorId((String) source.getProperties().get(VspItemProperty.VENDOR_ID)); - target.setVendorName((String) source.getProperties().get(VspItemProperty.VENDOR_NAME)); - target.setOnboardingMethod((String) source.getProperties().get(VspItemProperty.ONBOARDING_METHOD)); - target.setOwner(source.getOwner()); - target.setStatus(source.getStatus().name()); - } + + @Override + public void doMapping(Item source, VspDetailsDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setVendorId((String) source.getProperties().get(VspItemProperty.VENDOR_ID)); + target.setVendorName((String) source.getProperties().get(VspItemProperty.VENDOR_NAME)); + target.setOnboardingMethod((String) source.getProperties().get(VspItemProperty.ONBOARDING_METHOD)); + target.setOwner(source.getOwner()); + target.setStatus(source.getStatus().name()); + } } 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/mapping/MapMonitoringUploadStatusToDto.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/mapping/MapMonitoringUploadStatusToDto.java index 08d322dad0..08add59679 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/mapping/MapMonitoringUploadStatusToDto.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/mapping/MapMonitoringUploadStatusToDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.MonitoringUploadStatusDto; -public class MapMonitoringUploadStatusToDto - extends MappingBase { - @Override - public void doMapping(MonitoringUploadStatus source, MonitoringUploadStatusDto target) { - target.setSnmpPoll(source.getSnmpPoll()); - target.setSnmpTrap(source.getSnmpTrap()); - target.setVesEvent(source.getVesEvent()); - } +public class MapMonitoringUploadStatusToDto extends MappingBase { + + @Override + public void doMapping(MonitoringUploadStatus source, MonitoringUploadStatusDto target) { + target.setSnmpPoll(source.getSnmpPoll()); + target.setSnmpTrap(source.getSnmpTrap()); + target.setVesEvent(source.getVesEvent()); + } } 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/mapping/MapNetworkEntityToNetworkDto.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/mapping/MapNetworkEntityToNetworkDto.java index 1d79f35769..cf2ced753e 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/mapping/MapNetworkEntityToNetworkDto.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/mapping/MapNetworkEntityToNetworkDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; @@ -26,12 +25,13 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; public class MapNetworkEntityToNetworkDto extends MappingBase { - @Override - public void doMapping(NetworkEntity source, NetworkDto target) { - target.setId(source.getId()); - Network network = source.getNetworkCompositionData(); - if (network != null) { - new MapNetworkToNetworkDto().doMapping(network, target); + + @Override + public void doMapping(NetworkEntity source, NetworkDto target) { + target.setId(source.getId()); + Network network = source.getNetworkCompositionData(); + if (network != null) { + new MapNetworkToNetworkDto().doMapping(network, target); + } } - } } 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/mapping/MapNetworkRequestDtoToNetworkEntity.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/mapping/MapNetworkRequestDtoToNetworkEntity.java index 00395c4b99..4db9209c53 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/mapping/MapNetworkRequestDtoToNetworkEntity.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/mapping/MapNetworkRequestDtoToNetworkEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; @@ -25,13 +24,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkRequestDto; -public class MapNetworkRequestDtoToNetworkEntity - extends MappingBase { - @Override - public void doMapping(NetworkRequestDto source, NetworkEntity target) { - Network network = new Network(); - network.setName(source.getName()); - network.setDhcp(source.isDhcp()); - target.setNetworkCompositionData(network); - } +public class MapNetworkRequestDtoToNetworkEntity extends MappingBase { + + @Override + public void doMapping(NetworkRequestDto source, NetworkEntity target) { + Network network = new Network(); + network.setName(source.getName()); + network.setDhcp(source.isDhcp()); + target.setNetworkCompositionData(network); + } } 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/mapping/MapNetworkToNetworkDto.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/mapping/MapNetworkToNetworkDto.java index dd819de1a6..6cede067f1 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/mapping/MapNetworkToNetworkDto.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/mapping/MapNetworkToNetworkDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; @@ -25,9 +24,10 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; public class MapNetworkToNetworkDto extends MappingBase { - @Override - public void doMapping(Network source, NetworkDto target) { - target.setName(source.getName()); - target.setDhcp(source.isDhcp()); - } + + @Override + public void doMapping(Network source, NetworkDto target) { + target.setName(source.getName()); + target.setDhcp(source.isDhcp()); + } } 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/mapping/MapNicEntityToNicCreationResponseDto.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/mapping/MapNicEntityToNicCreationResponseDto.java index 835ff0b7b9..a3be49e684 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/mapping/MapNicEntityToNicCreationResponseDto.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/mapping/MapNicEntityToNicCreationResponseDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; - import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicCreationResponseDto; -public class MapNicEntityToNicCreationResponseDto extends MappingBase { - +public class MapNicEntityToNicCreationResponseDto extends MappingBase { - @Override - public void doMapping(NicEntity source, NicCreationResponseDto target) { - target.setNicId(source.getId()); - } + @Override + public void doMapping(NicEntity source, NicCreationResponseDto target) { + target.setNicId(source.getId()); + } } 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/mapping/MapNicEntityToNicDto.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/mapping/MapNicEntityToNicDto.java index 2af7e2ff6b..ea56e73237 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/mapping/MapNicEntityToNicDto.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/mapping/MapNicEntityToNicDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; @@ -26,12 +25,13 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicDto; public class MapNicEntityToNicDto extends MappingBase { - @Override - public void doMapping(NicEntity source, NicDto target) { - target.setId(source.getId()); - Nic nic = source.getNicCompositionData(); - if (nic != null) { - new MapNicToNicDto().doMapping(nic, target); + + @Override + public void doMapping(NicEntity source, NicDto target) { + target.setId(source.getId()); + Nic nic = source.getNicCompositionData(); + if (nic != null) { + new MapNicToNicDto().doMapping(nic, target); + } } - } } 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/mapping/MapNicRequestDtoToNicEntity.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/mapping/MapNicRequestDtoToNicEntity.java index 7fd0253556..da2d7c8814 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/mapping/MapNicRequestDtoToNicEntity.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/mapping/MapNicRequestDtoToNicEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; @@ -27,14 +26,15 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicRequestDto; public class MapNicRequestDtoToNicEntity extends MappingBase { - @Override - public void doMapping(NicRequestDto source, NicEntity target) { - Nic nic = new Nic(); - nic.setName(source.getName()); - nic.setDescription(source.getDescription()); - nic.setNetworkId(source.getNetworkId()); - nic.setNetworkType(NetworkType.valueOf(source.getNetworkType())); - nic.setNetworkDescription(source.getNetworkDescription()); - target.setNicCompositionData(nic); - } + + @Override + public void doMapping(NicRequestDto source, NicEntity target) { + Nic nic = new Nic(); + nic.setName(source.getName()); + nic.setDescription(source.getDescription()); + nic.setNetworkId(source.getNetworkId()); + nic.setNetworkType(NetworkType.valueOf(source.getNetworkType())); + nic.setNetworkDescription(source.getNetworkDescription()); + target.setNicCompositionData(nic); + } } 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/mapping/MapNicToNicDto.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/mapping/MapNicToNicDto.java index 8c48f18b3d..4a22fb5f19 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/mapping/MapNicToNicDto.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/mapping/MapNicToNicDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; @@ -25,15 +24,16 @@ import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicDto; public class MapNicToNicDto extends MappingBase { - @Override - public void doMapping(Nic source, NicDto target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setNetworkId(source.getNetworkId()); - target.setNetworkName(source.getNetworkName()); - if (source.getNetworkType() != null) { - target.setNetworkType(source.getNetworkType().name()); + + @Override + public void doMapping(Nic source, NicDto target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setNetworkId(source.getNetworkId()); + target.setNetworkName(source.getNetworkName()); + if (source.getNetworkType() != null) { + target.setNetworkType(source.getNetworkType().name()); + } + target.setNetworkDescription(source.getNetworkDescription()); } - target.setNetworkDescription(source.getNetworkDescription()); - } } 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/mapping/MapPackageInfoToPackageInfoDto.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/mapping/MapPackageInfoToPackageInfoDto.java index 1bf13f8c3f..c6faa0361b 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/mapping/MapPackageInfoToPackageInfoDto.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/mapping/MapPackageInfoToPackageInfoDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; @@ -28,18 +27,19 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.PackageInfoDto; * Created by TALIO on 4/25/2016. */ public class MapPackageInfoToPackageInfoDto extends MappingBase { - @Override - public void doMapping(PackageInfo source, PackageInfoDto target) { - target.setVspName(source.getVspName()); - target.setPackageId(source.getVspId()); - target.setDescription(source.getVspDescription()); - target.setVersion(source.getVersion()); - target.setPackageType(source.getPackageType()); - target.setCategory(source.getCategory()); - target.setSubCategory(source.getSubCategory()); - target.setPackageChecksum(source.getPackageChecksum()); - target.setVendorRelease(source.getVendorRelease()); - target.setVendorName(source.getVendorName()); - target.setResourceType(source.getResourceType()); - } + + @Override + public void doMapping(PackageInfo source, PackageInfoDto target) { + target.setVspName(source.getVspName()); + target.setPackageId(source.getVspId()); + target.setDescription(source.getVspDescription()); + target.setVersion(source.getVersion()); + target.setPackageType(source.getPackageType()); + target.setCategory(source.getCategory()); + target.setSubCategory(source.getSubCategory()); + target.setPackageChecksum(source.getPackageChecksum()); + target.setVendorRelease(source.getVendorRelease()); + target.setVendorName(source.getVendorName()); + target.setResourceType(source.getResourceType()); + } } 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/mapping/MapProcessEntityToProcessEntityDto.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/mapping/MapProcessEntityToProcessEntityDto.java index 96a67a9d87..6d6a6d29de 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/mapping/MapProcessEntityToProcessEntityDto.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/mapping/MapProcessEntityToProcessEntityDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessEntityDto; -public class MapProcessEntityToProcessEntityDto - extends MappingBase { - @Override - public void doMapping(ProcessEntity source, ProcessEntityDto target) { - target.setId(source.getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - target.setArtifactName(source.getArtifactName()); - } +public class MapProcessEntityToProcessEntityDto extends MappingBase { + + @Override + public void doMapping(ProcessEntity source, ProcessEntityDto target) { + target.setId(source.getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + target.setArtifactName(source.getArtifactName()); + } } 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/mapping/MapProcessRequestDtoToProcessEntity.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/mapping/MapProcessRequestDtoToProcessEntity.java index d1a28d7145..2f53b24d25 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/mapping/MapProcessRequestDtoToProcessEntity.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/mapping/MapProcessRequestDtoToProcessEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessRequestDto; -public class MapProcessRequestDtoToProcessEntity - extends MappingBase { - @Override - public void doMapping(ProcessRequestDto source, ProcessEntity target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setType(source.getType()); - } +public class MapProcessRequestDtoToProcessEntity extends MappingBase { + + @Override + public void doMapping(ProcessRequestDto source, ProcessEntity target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setType(source.getType()); + } } 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/mapping/MapQuestionnaireResponseToQuestionnaireResponseDto.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/mapping/MapQuestionnaireResponseToQuestionnaireResponseDto.java index 52252c0425..598596b030 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/mapping/MapQuestionnaireResponseToQuestionnaireResponseDto.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/mapping/MapQuestionnaireResponseToQuestionnaireResponseDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; -public class MapQuestionnaireResponseToQuestionnaireResponseDto - extends MappingBase { +public class MapQuestionnaireResponseToQuestionnaireResponseDto extends MappingBase { - @Override - public void doMapping(QuestionnaireResponse source, QuestionnaireResponseDto target) { - target.setData(source.getData()); - target.setSchema(source.getSchema()); - target.setErrorMessage(source.getErrorMessage()); - } + @Override + public void doMapping(QuestionnaireResponse source, QuestionnaireResponseDto target) { + target.setData(source.getData()); + target.setSchema(source.getSchema()); + target.setErrorMessage(source.getErrorMessage()); + } } 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/mapping/MapQuestionnaireToQuestionnaireDto.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/mapping/MapQuestionnaireToQuestionnaireDto.java index fe8e3c5ea4..e846f0e047 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/mapping/MapQuestionnaireToQuestionnaireDto.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/mapping/MapQuestionnaireToQuestionnaireDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; +import java.util.HashMap; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireDto; -import java.util.HashMap; - /** * Created by ayalaben on 9/26/2017 */ -public class MapQuestionnaireToQuestionnaireDto extends - MappingBase { +public class MapQuestionnaireToQuestionnaireDto extends MappingBase { - @Override - public void doMapping(CompositionEntity source, QuestionnaireDto target) { - target.setId(source.getId()); - target.setQuestionareData(JsonUtil.json2Object(source.getQuestionnaireData(), HashMap.class)); - } + @Override + public void doMapping(CompositionEntity source, QuestionnaireDto target) { + target.setId(source.getId()); + target.setQuestionareData(JsonUtil.json2Object(source.getQuestionnaireData(), HashMap.class)); + } } 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/mapping/MapUploadFileResponseToUploadFileResponseDto.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/mapping/MapUploadFileResponseToUploadFileResponseDto.java index 48053d053d..f78e2e0dee 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/mapping/MapUploadFileResponseToUploadFileResponseDto.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/mapping/MapUploadFileResponseToUploadFileResponseDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; - import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdcrests.mapping.MappingBase; import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; @@ -28,13 +26,13 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto /** * Created by TALIO on 4/27/2016. */ -public class MapUploadFileResponseToUploadFileResponseDto - extends MappingBase { - @Override - public void doMapping(UploadFileResponse source, UploadFileResponseDto target) { - target.setStatus(source.getStatus()); - target.setErrors(source.getErrors()); - target.setOnboardingOrigin(source.getOnboardingType().toString()); - target.setNetworkPackageName(source.getNetworkPackageName()); - } +public class MapUploadFileResponseToUploadFileResponseDto extends MappingBase { + + @Override + public void doMapping(UploadFileResponse source, UploadFileResponseDto target) { + target.setStatus(source.getStatus()); + target.setErrors(source.getErrors()); + target.setOnboardingOrigin(source.getOnboardingType().toString()); + target.setNetworkPackageName(source.getNetworkPackageName()); + } } 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/mapping/MapValidationResponseToDto.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/mapping/MapValidationResponseToDto.java index b3fbe1e7c9..8048786f69 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/mapping/MapValidationResponseToDto.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/mapping/MapValidationResponseToDto.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.mapping; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.common.errors.ErrorCode; @@ -32,61 +38,47 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityVali import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireValidationResultDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto; -import java.util.*; -import java.util.stream.Collectors; +public class MapValidationResponseToDto extends MappingBase { -public class MapValidationResponseToDto - extends MappingBase { - private static Map> mapUploadDataErrors( - Map> uploadDataErrors) { - if (MapUtils.isEmpty(uploadDataErrors)) { - return null; + private static Map> mapUploadDataErrors(Map> uploadDataErrors) { + if (MapUtils.isEmpty(uploadDataErrors)) { + return null; + } + return uploadDataErrors.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> mapErrorMessages(entry.getValue()))); } - return uploadDataErrors.entrySet().stream().collect( - Collectors.toMap(Map.Entry::getKey, entry -> mapErrorMessages(entry.getValue()))); - } - private static QuestionnaireValidationResultDto mapQuestionnaireValidationResult( - QuestionnaireValidationResult questionnaireValidationResult) { - if (Objects.isNull(questionnaireValidationResult) - || Objects.isNull(questionnaireValidationResult.getValidationData())) { - return null; + private static QuestionnaireValidationResultDto mapQuestionnaireValidationResult(QuestionnaireValidationResult questionnaireValidationResult) { + if (Objects.isNull(questionnaireValidationResult) || Objects.isNull(questionnaireValidationResult.getValidationData())) { + return null; + } + QuestionnaireValidationResultDto questionnaireValidationResultDto = new QuestionnaireValidationResultDto(); + questionnaireValidationResultDto.setValid(questionnaireValidationResult.isValid()); + Set validationDataDto = new HashSet<>(); + for (CompositionEntityValidationData validationData : questionnaireValidationResult.getValidationData()) { + validationDataDto + .add(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)); + } + questionnaireValidationResultDto.setValidationData(validationDataDto); + return questionnaireValidationResultDto; } - QuestionnaireValidationResultDto questionnaireValidationResultDto = - new QuestionnaireValidationResultDto(); - questionnaireValidationResultDto.setValid(questionnaireValidationResult.isValid()); - Set validationDataDto = new HashSet<>(); - for (CompositionEntityValidationData validationData : questionnaireValidationResult - .getValidationData()) { - validationDataDto.add(new MapCompositionEntityValidationDataToDto().applyMapping( - validationData, CompositionEntityValidationDataDto.class)); + private static List mapErrorMessages(List errorMessages) { + return errorMessages == null ? null + : errorMessages.stream().map(errorMessage -> new MapErrorMessageToDto().applyMapping(errorMessage, ErrorMessageDto.class)) + .collect(Collectors.toList()); } - questionnaireValidationResultDto.setValidationData(validationDataDto); - return questionnaireValidationResultDto; - } - - - private static List mapErrorMessages(List errorMessages) { - return errorMessages == null ? null : errorMessages.stream().map( - errorMessage -> new MapErrorMessageToDto() - .applyMapping(errorMessage, ErrorMessageDto.class)).collect(Collectors.toList()); - } - - private static Collection mapErrorCodes(Collection errorCodes) { - return CollectionUtils.isEmpty(errorCodes) ? null : errorCodes.stream() - .map(errorCode -> new MapErrorCodeToDto().applyMapping(errorCode, ErrorCodeDto.class)) - .collect(Collectors.toList()); - } + private static Collection mapErrorCodes(Collection errorCodes) { + return CollectionUtils.isEmpty(errorCodes) ? null + : errorCodes.stream().map(errorCode -> new MapErrorCodeToDto().applyMapping(errorCode, ErrorCodeDto.class)).collect(Collectors.toList()); + } - @Override - public void doMapping(ValidationResponse source, ValidationResponseDto target) { - target.setValid(source.isValid()); - target.setVspErrors(mapErrorCodes(source.getVspErrors())); - target.setLicensingDataErrors(mapErrorCodes(source.getLicensingDataErrors())); - target.setUploadDataErrors(mapUploadDataErrors(source.getUploadDataErrors())); - target.setQuestionnaireValidationResult( - mapQuestionnaireValidationResult(source.getQuestionnaireValidationResult())); - } + @Override + public void doMapping(ValidationResponse source, ValidationResponseDto target) { + target.setValid(source.isValid()); + target.setVspErrors(mapErrorCodes(source.getVspErrors())); + target.setLicensingDataErrors(mapErrorCodes(source.getLicensingDataErrors())); + target.setUploadDataErrors(mapUploadDataErrors(source.getUploadDataErrors())); + target.setQuestionnaireValidationResult(mapQuestionnaireValidationResult(source.getQuestionnaireValidationResult())); + } } 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/mapping/MapVspDescriptionDtoToItem.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/mapping/MapVspDescriptionDtoToItem.java index 484b7c80bb..0543c20298 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/mapping/MapVspDescriptionDtoToItem.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/mapping/MapVspDescriptionDtoToItem.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.versioning.types.Item; @@ -26,11 +25,12 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto; import org.openecomp.sdcrests.vsp.rest.services.VspItemProperty; public class MapVspDescriptionDtoToItem extends MappingBase { - @Override - public void doMapping(VspDescriptionDto source, Item target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.addProperty(VspItemProperty.VENDOR_ID, source.getVendorId()); - target.addProperty(VspItemProperty.VENDOR_NAME, source.getVendorName()); - } + + @Override + public void doMapping(VspDescriptionDto source, Item target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.addProperty(VspItemProperty.VENDOR_ID, source.getVendorId()); + target.addProperty(VspItemProperty.VENDOR_NAME, source.getVendorName()); + } } 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/mapping/MapVspDescriptionDtoToVspDetails.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/mapping/MapVspDescriptionDtoToVspDetails.java index 3ab2667821..4c9c16df89 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/mapping/MapVspDescriptionDtoToVspDetails.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/mapping/MapVspDescriptionDtoToVspDetails.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.LicenseType; @@ -29,27 +28,25 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDescriptionDto; public class MapVspDescriptionDtoToVspDetails extends MappingBase { - @Override - public void doMapping(VspDescriptionDto source, VspDetails target) { - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setCategory(source.getCategory()); - target.setSubCategory(source.getSubCategory()); - target.setIcon(source.getIcon()); - target.setVendorName(source.getVendorName()); - target.setVendorId(source.getVendorId()); - - if (source.getLicensingVersion() != null && source.getLicenseType() != LicenseType.EXTERNAL) { - target.setVlmVersion(new Version(source.getLicensingVersion())); - } - if (source.getLicenseType() != null) { - target.setLicenseType(source.getLicenseType().name()); - } - - LicensingData licensingData = source.getLicensingData(); - if (licensingData != null && source.getLicenseType() != LicenseType.EXTERNAL) { - target.setLicenseAgreement(licensingData.getLicenseAgreement()); - target.setFeatureGroups(licensingData.getFeatureGroups()); + @Override + public void doMapping(VspDescriptionDto source, VspDetails target) { + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setCategory(source.getCategory()); + target.setSubCategory(source.getSubCategory()); + target.setIcon(source.getIcon()); + target.setVendorName(source.getVendorName()); + target.setVendorId(source.getVendorId()); + if (source.getLicensingVersion() != null && source.getLicenseType() != LicenseType.EXTERNAL) { + target.setVlmVersion(new Version(source.getLicensingVersion())); + } + if (source.getLicenseType() != null) { + target.setLicenseType(source.getLicenseType().name()); + } + LicensingData licensingData = source.getLicensingData(); + if (licensingData != null && source.getLicenseType() != LicenseType.EXTERNAL) { + target.setLicenseAgreement(licensingData.getLicenseAgreement()); + target.setFeatureGroups(licensingData.getFeatureGroups()); + } } - } } 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/mapping/MapVspDetailsToDto.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/mapping/MapVspDetailsToDto.java index 1ba5d1355c..1605ab7218 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/mapping/MapVspDetailsToDto.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/mapping/MapVspDetailsToDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.mapping; import org.apache.commons.lang3.StringUtils; @@ -29,31 +28,29 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.VspDetailsDto; public class MapVspDetailsToDto extends MappingBase { - @Override - public void doMapping(VspDetails source, VspDetailsDto target) { - target.setId(source.getId()); - target.setVersion(source.getVersion() == null ? null : source.getVersion().getId()); - target.setName(source.getName()); - target.setDescription(source.getDescription()); - target.setIcon(source.getIcon()); - target.setCategory(source.getCategory()); - target.setSubCategory(source.getSubCategory()); - target.setVendorId(source.getVendorId()); - target.setVendorName(source.getVendorName()); - target.setLicensingVersion( - source.getVlmVersion() == null ? null : source.getVlmVersion().getId()); - if (StringUtils.isNotBlank(source.getLicenseType())) { - target.setLicenseType(LicenseType.valueOf(source.getLicenseType())); - } else if (StringUtils.isNotBlank(target.getLicensingVersion())){ - target.setLicenseType(LicenseType.INTERNAL); - } - if (source.getLicenseAgreement() != null || source.getFeatureGroups() != null) { - LicensingData licensingData = new LicensingData(); - licensingData.setLicenseAgreement(source.getLicenseAgreement()); - licensingData.setFeatureGroups(source.getFeatureGroups()); - target.setLicensingData(licensingData); + @Override + public void doMapping(VspDetails source, VspDetailsDto target) { + target.setId(source.getId()); + target.setVersion(source.getVersion() == null ? null : source.getVersion().getId()); + target.setName(source.getName()); + target.setDescription(source.getDescription()); + target.setIcon(source.getIcon()); + target.setCategory(source.getCategory()); + target.setSubCategory(source.getSubCategory()); + target.setVendorId(source.getVendorId()); + target.setVendorName(source.getVendorName()); + target.setLicensingVersion(source.getVlmVersion() == null ? null : source.getVlmVersion().getId()); + if (StringUtils.isNotBlank(source.getLicenseType())) { + target.setLicenseType(LicenseType.valueOf(source.getLicenseType())); + } else if (StringUtils.isNotBlank(target.getLicensingVersion())) { + target.setLicenseType(LicenseType.INTERNAL); + } + if (source.getLicenseAgreement() != null || source.getFeatureGroups() != null) { + LicensingData licensingData = new LicensingData(); + licensingData.setLicenseAgreement(source.getLicenseAgreement()); + licensingData.setFeatureGroups(source.getFeatureGroups()); + target.setLicensingData(licensingData); + } + target.setOnboardingMethod(source.getOnboardingMethod()); } - - target.setOnboardingMethod(source.getOnboardingMethod()); - } } 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/ComponentDependenciesImpl.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/ComponentDependenciesImpl.java index becfac97b6..2357e94a95 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/ComponentDependenciesImpl.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/ComponentDependenciesImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; @@ -31,103 +33,73 @@ import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("componentDependencies") @Scope(value = "prototype") public class ComponentDependenciesImpl implements ComponentDependencies { - private final ComponentDependencyModelManager componentDependencyModelManager; - - public ComponentDependenciesImpl() { - this.componentDependencyModelManager = - ComponentDependencyModelManagerFactory.getInstance().createInterface(); - } - - public ComponentDependenciesImpl(ComponentDependencyModelManager componentDependencyModelManager) { - this.componentDependencyModelManager = componentDependencyModelManager; - } - - @Override - public Response create(ComponentDependencyModel request, String vspId, String versionId, - String user) { - final Version version = new Version(versionId); - - ComponentDependencyModelEntity modelEntity = - new MapComponentDependencyModelRequestToEntity().applyMapping(request, - ComponentDependencyModelEntity.class); - - modelEntity.setVspId(vspId); - modelEntity.setVersion(version); - - ComponentDependencyModelEntity componentDependency = - componentDependencyModelManager.createComponentDependency(modelEntity, vspId, version); - - MapComponentDependencyEntityToCreationDto mapping = - new MapComponentDependencyEntityToCreationDto(); - ComponentDependencyCreationDto createdComponentDependencyDto = mapping.applyMapping( - componentDependency, ComponentDependencyCreationDto.class); - return Response.ok(componentDependency != null ? createdComponentDependencyDto : null) - .build(); - } + private final ComponentDependencyModelManager componentDependencyModelManager; - @Override - public Response list(String vspId, String versionId, String user) { - - Version vspVersion = new Version(versionId); - - Collection componentDependencies = - componentDependencyModelManager.list(vspId, vspVersion); - - MapComponentDependencyEntityToDto mapper = new MapComponentDependencyEntityToDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper - <>(); - for (ComponentDependencyModelEntity entity : componentDependencies) { - results.add(mapper.applyMapping(entity, ComponentDependencyResponseDto.class)); + public ComponentDependenciesImpl() { + this.componentDependencyModelManager = ComponentDependencyModelManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } - - @Override - public Response delete(String vspId, String versionId, String dependencyId, String user) { - - Version vspVersion = new Version(versionId); - componentDependencyModelManager.delete(vspId, vspVersion, dependencyId); - return Response.ok().build(); - } - - @Override - public Response update(ComponentDependencyModel request, String vspId, String versionId, String - dependencyId, String user) { - - final Version version = new Version(versionId); - ComponentDependencyModelEntity modelEntity = - new MapComponentDependencyModelRequestToEntity().applyMapping(request, - ComponentDependencyModelEntity.class); - - modelEntity.setId(dependencyId); - modelEntity.setVspId(vspId); - modelEntity.setVersion(version); - componentDependencyModelManager.update(modelEntity); - return Response.ok().build(); - } + public ComponentDependenciesImpl(ComponentDependencyModelManager componentDependencyModelManager) { + this.componentDependencyModelManager = componentDependencyModelManager; + } - @Override - public Response get(String vspId, String version, String dependencyId, String user) { + @Override + public Response create(ComponentDependencyModel request, String vspId, String versionId, String user) { + final Version version = new Version(versionId); + ComponentDependencyModelEntity modelEntity = new MapComponentDependencyModelRequestToEntity() + .applyMapping(request, ComponentDependencyModelEntity.class); + modelEntity.setVspId(vspId); + modelEntity.setVersion(version); + ComponentDependencyModelEntity componentDependency = componentDependencyModelManager.createComponentDependency(modelEntity, vspId, version); + MapComponentDependencyEntityToCreationDto mapping = new MapComponentDependencyEntityToCreationDto(); + ComponentDependencyCreationDto createdComponentDependencyDto = mapping + .applyMapping(componentDependency, ComponentDependencyCreationDto.class); + return Response.ok(componentDependency != null ? createdComponentDependencyDto : null).build(); + } - ComponentDependencyModelEntity componentDependencyModelEntity = componentDependencyModelManager - .get(vspId, new Version(version), dependencyId); + @Override + public Response list(String vspId, String versionId, String user) { + Version vspVersion = new Version(versionId); + Collection componentDependencies = componentDependencyModelManager.list(vspId, vspVersion); + MapComponentDependencyEntityToDto mapper = new MapComponentDependencyEntityToDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (ComponentDependencyModelEntity entity : componentDependencies) { + results.add(mapper.applyMapping(entity, ComponentDependencyResponseDto.class)); + } + return Response.ok(results).build(); + } - MapComponentDependencyEntityToDto mapper = new MapComponentDependencyEntityToDto(); - ComponentDependencyResponseDto componentDependencyResponseDto = - mapper.applyMapping(componentDependencyModelEntity, ComponentDependencyResponseDto.class); + @Override + public Response delete(String vspId, String versionId, String dependencyId, String user) { + Version vspVersion = new Version(versionId); + componentDependencyModelManager.delete(vspId, vspVersion, dependencyId); + return Response.ok().build(); + } - return Response.ok(componentDependencyModelEntity != null ? componentDependencyResponseDto : - null).build(); - } + @Override + public Response update(ComponentDependencyModel request, String vspId, String versionId, String dependencyId, String user) { + final Version version = new Version(versionId); + ComponentDependencyModelEntity modelEntity = new MapComponentDependencyModelRequestToEntity() + .applyMapping(request, ComponentDependencyModelEntity.class); + modelEntity.setId(dependencyId); + modelEntity.setVspId(vspId); + modelEntity.setVersion(version); + componentDependencyModelManager.update(modelEntity); + return Response.ok().build(); + } + @Override + public Response get(String vspId, String version, String dependencyId, String user) { + ComponentDependencyModelEntity componentDependencyModelEntity = componentDependencyModelManager + .get(vspId, new Version(version), dependencyId); + MapComponentDependencyEntityToDto mapper = new MapComponentDependencyEntityToDto(); + ComponentDependencyResponseDto componentDependencyResponseDto = mapper + .applyMapping(componentDependencyModelEntity, ComponentDependencyResponseDto.class); + return Response.ok(componentDependencyModelEntity != null ? componentDependencyResponseDto : null).build(); + } } 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/ComponentMonitoringUploadsImpl.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/ComponentMonitoringUploadsImpl.java index 25c99b294b..64d36b95e0 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/ComponentMonitoringUploadsImpl.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/ComponentMonitoringUploadsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.io.InputStream; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -36,88 +38,67 @@ import org.openecomp.sdcrests.vsp.rest.mapping.MapMonitoringUploadStatusToDto; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.io.InputStream; - /** * @author katyr * @since June 26, 2017 */ - @Named @Service("componentMonitoringUploads") @Scope(value = "prototype") //@Validated public class ComponentMonitoringUploadsImpl implements ComponentMonitoringUploads { - private final MonitoringUploadsManager monitoringUploadsManager; - private final ComponentManager componentManager; - - public ComponentMonitoringUploadsImpl() { - this.monitoringUploadsManager = MonitoringUploadsManagerFactory.getInstance().createInterface(); - this.componentManager = ComponentManagerFactory.getInstance().createInterface(); - } - public ComponentMonitoringUploadsImpl(MonitoringUploadsManager monitoringUploadsManager, - ComponentManager componentManager) { - this.monitoringUploadsManager = monitoringUploadsManager; - this.componentManager = componentManager; - } + private final MonitoringUploadsManager monitoringUploadsManager; + private final ComponentManager componentManager; - @Override - public Response upload(Attachment attachment, - String vspId, String versionId, String componentId, String type, - String user) throws Exception { - - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - - MonitoringUploadType monitoringUploadType = getMonitoringUploadType(vspId, componentId, type); - monitoringUploadsManager.upload(attachment.getObject(InputStream.class), - attachment.getContentDisposition().getParameter("filename"), vspId, version, componentId, - monitoringUploadType); - return Response.ok().build(); - } - - private MonitoringUploadType getMonitoringUploadType(String vspId, String componentId, - String type) throws Exception { - MonitoringUploadType monitoringUploadType; - try { - monitoringUploadType = MonitoringUploadType.valueOf(type); - } catch (IllegalArgumentException exception) { - String errorWithParameters = ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.ILLEGAL_MONITORING_ARTIFACT_TYPE.getErrorMessage(), - componentId, vspId); - throw new Exception(errorWithParameters, exception); + public ComponentMonitoringUploadsImpl() { + this.monitoringUploadsManager = MonitoringUploadsManagerFactory.getInstance().createInterface(); + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); } - return monitoringUploadType; - } - - @Override - public Response delete(String vspId, String versionId, String componentId, - String type, String user) throws Exception { - - MonitoringUploadType monitoringUploadType = getMonitoringUploadType(vspId, componentId, type); - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - monitoringUploadsManager.delete(vspId, version, componentId, monitoringUploadType); - return Response.ok().build(); - } + public ComponentMonitoringUploadsImpl(MonitoringUploadsManager monitoringUploadsManager, ComponentManager componentManager) { + this.monitoringUploadsManager = monitoringUploadsManager; + this.componentManager = componentManager; + } - @Override - public Response list(String vspId, String versionId, String componentId, - String user) { + @Override + public Response upload(Attachment attachment, String vspId, String versionId, String componentId, String type, String user) throws Exception { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + MonitoringUploadType monitoringUploadType = getMonitoringUploadType(vspId, componentId, type); + monitoringUploadsManager + .upload(attachment.getObject(InputStream.class), attachment.getContentDisposition().getParameter("filename"), vspId, version, componentId, + monitoringUploadType); + return Response.ok().build(); + } - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); + private MonitoringUploadType getMonitoringUploadType(String vspId, String componentId, String type) throws Exception { + MonitoringUploadType monitoringUploadType; + try { + monitoringUploadType = MonitoringUploadType.valueOf(type); + } catch (IllegalArgumentException exception) { + String errorWithParameters = ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.ILLEGAL_MONITORING_ARTIFACT_TYPE.getErrorMessage(), componentId, vspId); + throw new Exception(errorWithParameters, exception); + } + return monitoringUploadType; + } - MonitoringUploadStatus response = - monitoringUploadsManager.listFilenames(vspId, version, componentId); + @Override + public Response delete(String vspId, String versionId, String componentId, String type, String user) throws Exception { + MonitoringUploadType monitoringUploadType = getMonitoringUploadType(vspId, componentId, type); + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + monitoringUploadsManager.delete(vspId, version, componentId, monitoringUploadType); + return Response.ok().build(); + } - MonitoringUploadStatusDto returnEntity = - new MapMonitoringUploadStatusToDto() - .applyMapping(response, MonitoringUploadStatusDto.class); - return Response.status(Response.Status.OK).entity(returnEntity).build(); - } + @Override + public Response list(String vspId, String versionId, String componentId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + MonitoringUploadStatus response = monitoringUploadsManager.listFilenames(vspId, version, componentId); + MonitoringUploadStatusDto returnEntity = new MapMonitoringUploadStatusToDto().applyMapping(response, MonitoringUploadStatusDto.class); + return Response.status(Response.Status.OK).entity(returnEntity).build(); + } } 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/ComponentProcessesImpl.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/ComponentProcessesImpl.java index 4e4d7d5d9e..ab0ad04075 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/ComponentProcessesImpl.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/ComponentProcessesImpl.java @@ -13,9 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.io.File; +import java.io.InputStream; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.openecomp.sdc.activitylog.ActivityLogManager; import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; @@ -37,165 +41,124 @@ import org.openecomp.sdcrests.wrappers.StringWrapperResponse; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.io.File; -import java.io.InputStream; -import java.util.Collection; - @Named @Service("componentProcesses") @Scope(value = "prototype") public class ComponentProcessesImpl implements ComponentProcesses { - private final ProcessManager processManager; - private final ComponentManager componentManager; - private final ActivityLogManager activityLogManager; - - public ComponentProcessesImpl() { - this.processManager = ProcessManagerFactory.getInstance().createInterface(); - this.componentManager = ComponentManagerFactory.getInstance().createInterface(); - this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); - } - - public ComponentProcessesImpl(ProcessManager processManager, - ComponentManager componentManager, ActivityLogManager activityLogManager) { - this.processManager = processManager; - this.componentManager = componentManager; - this.activityLogManager = activityLogManager; - } - - @Override - public Response list(String vspId, String versionId, String componentId, String user) { + private final ProcessManager processManager; + private final ComponentManager componentManager; + private final ActivityLogManager activityLogManager; - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - Collection processes = processManager.listProcesses(vspId, version, componentId); - - MapProcessEntityToProcessEntityDto mapper = new MapProcessEntityToProcessEntityDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (ProcessEntity process : processes) { - results.add(mapper.applyMapping(process, ProcessEntityDto.class)); + public ComponentProcessesImpl() { + this.processManager = ProcessManagerFactory.getInstance().createInterface(); + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); + this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } - - @Override - public Response deleteList(String vspId, String versionId, String componentId, String user) { - - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - processManager.deleteProcesses(vspId, version, componentId); - - return Response.ok().build(); - } - - @Override - public Response create(ProcessRequestDto request, String vspId, String versionId, - String componentId, String user) { - - ProcessEntity process = - new MapProcessRequestDtoToProcessEntity().applyMapping(request, ProcessEntity.class); - process.setVspId(vspId); - process.setVersion(new Version(versionId)); - process.setComponentId(componentId); - - validateComponentExistence(vspId, process.getVersion(), componentId, user); - ProcessEntity createdProcess = processManager.createProcess(process); - - return Response - .ok(createdProcess != null ? new StringWrapperResponse(createdProcess.getId()) : null) - .build(); - } - - @Override - public Response get(String vspId, String versionId, String componentId, String processId, - String user) { - - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - ProcessEntity process = processManager.getProcess(vspId, version, componentId, processId); - ProcessEntityDto result = - new MapProcessEntityToProcessEntityDto().applyMapping(process, ProcessEntityDto.class); - return Response.ok(result).build(); - } - - @Override - public Response delete(String vspId, String versionId, String componentId, String processId, - String user) { - - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - processManager.deleteProcess(vspId, version, componentId, processId); - return Response.ok().build(); - } - - @Override - public Response update(ProcessRequestDto request, String vspId, String versionId, - String componentId, - String processId, String user) { - - ProcessEntity process = - new MapProcessRequestDtoToProcessEntity().applyMapping(request, ProcessEntity.class); - process.setVspId(vspId); - process.setVersion(new Version(versionId)); - process.setComponentId(componentId); - process.setId(processId); - validateComponentExistence(vspId, process.getVersion(), componentId, user); - processManager.updateProcess(process); - return Response.ok().build(); - } + public ComponentProcessesImpl(ProcessManager processManager, ComponentManager componentManager, ActivityLogManager activityLogManager) { + this.processManager = processManager; + this.componentManager = componentManager; + this.activityLogManager = activityLogManager; + } - @Override - public Response getUploadedFile(String vspId, String versionId, String componentId, - String processId, String user) { + @Override + public Response list(String vspId, String versionId, String componentId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + Collection processes = processManager.listProcesses(vspId, version, componentId); + MapProcessEntityToProcessEntityDto mapper = new MapProcessEntityToProcessEntityDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (ProcessEntity process : processes) { + results.add(mapper.applyMapping(process, ProcessEntityDto.class)); + } + return Response.ok(results).build(); + } - Version vspVersion = new Version(versionId); - validateComponentExistence(vspId, vspVersion, componentId, user); - File file = processManager.getProcessArtifact(vspId, vspVersion, componentId, processId); + @Override + public Response deleteList(String vspId, String versionId, String componentId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + processManager.deleteProcesses(vspId, version, componentId); + return Response.ok().build(); + } - Response.ResponseBuilder response = Response.ok(file); - if (file == null) { - return Response.status(Response.Status.NOT_FOUND).build(); + @Override + public Response create(ProcessRequestDto request, String vspId, String versionId, String componentId, String user) { + ProcessEntity process = new MapProcessRequestDtoToProcessEntity().applyMapping(request, ProcessEntity.class); + process.setVspId(vspId); + process.setVersion(new Version(versionId)); + process.setComponentId(componentId); + validateComponentExistence(vspId, process.getVersion(), componentId, user); + ProcessEntity createdProcess = processManager.createProcess(process); + return Response.ok(createdProcess != null ? new StringWrapperResponse(createdProcess.getId()) : null).build(); } - response.header("Content-Disposition", "attachment; filename=" + file.getName()); - return response.build(); - } - @Override - public Response deleteUploadedFile(String vspId, String versionId, String componentId, - String processId, - String user) { + @Override + public Response get(String vspId, String versionId, String componentId, String processId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + ProcessEntity process = processManager.getProcess(vspId, version, componentId, processId); + ProcessEntityDto result = new MapProcessEntityToProcessEntityDto().applyMapping(process, ProcessEntityDto.class); + return Response.ok(result).build(); + } - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - processManager.deleteProcessArtifact(vspId, version, componentId, processId); - return Response.ok().build(); - } + @Override + public Response delete(String vspId, String versionId, String componentId, String processId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + processManager.deleteProcess(vspId, version, componentId, processId); + return Response.ok().build(); + } - @Override - public Response uploadFile(Attachment attachment, String vspId, String versionId, - String componentId, - String processId, String user) { + @Override + public Response update(ProcessRequestDto request, String vspId, String versionId, String componentId, String processId, String user) { + ProcessEntity process = new MapProcessRequestDtoToProcessEntity().applyMapping(request, ProcessEntity.class); + process.setVspId(vspId); + process.setVersion(new Version(versionId)); + process.setComponentId(componentId); + process.setId(processId); + validateComponentExistence(vspId, process.getVersion(), componentId, user); + processManager.updateProcess(process); + return Response.ok().build(); + } - Version version = new Version(versionId); - validateComponentExistence(vspId, version, componentId, user); - processManager.uploadProcessArtifact(attachment.getObject(InputStream.class), - attachment.getContentDisposition().getParameter("filename"), vspId, version, componentId, - processId); - activityLogManager.logActivity(new ActivityLogEntity(vspId, version, - ActivityType.Upload_Artifact, user, true, "", "")); + @Override + public Response getUploadedFile(String vspId, String versionId, String componentId, String processId, String user) { + Version vspVersion = new Version(versionId); + validateComponentExistence(vspId, vspVersion, componentId, user); + File file = processManager.getProcessArtifact(vspId, vspVersion, componentId, processId); + Response.ResponseBuilder response = Response.ok(file); + if (file == null) { + return Response.status(Response.Status.NOT_FOUND).build(); + } + response.header("Content-Disposition", "attachment; filename=" + file.getName()); + return response.build(); + } - return Response.ok().build(); - } + @Override + public Response deleteUploadedFile(String vspId, String versionId, String componentId, String processId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + processManager.deleteProcessArtifact(vspId, version, componentId, processId); + return Response.ok().build(); + } + @Override + public Response uploadFile(Attachment attachment, String vspId, String versionId, String componentId, String processId, String user) { + Version version = new Version(versionId); + validateComponentExistence(vspId, version, componentId, user); + processManager + .uploadProcessArtifact(attachment.getObject(InputStream.class), attachment.getContentDisposition().getParameter("filename"), vspId, + version, componentId, processId); + activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Upload_Artifact, user, true, "", "")); + return Response.ok().build(); + } - private void validateComponentExistence(String vspId, Version version, String componentId, - String user) { - if (componentId == null) { - return; + private void validateComponentExistence(String vspId, Version version, String componentId, String user) { + if (componentId == null) { + return; + } + componentManager.validateComponentExistence(vspId, version, componentId); } - componentManager.validateComponentExistence(vspId, version, componentId); - } } 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/ComponentsImpl.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/ComponentsImpl.java index fefa52842e..9f2cbd36b7 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/ComponentsImpl.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/ComponentsImpl.java @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; @@ -29,122 +31,104 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComponentRequestDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vsp.rest.Components; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentDataToComponentDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentEntityToComponentCreationDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentEntityToComponentDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComponentRequestDtoToComponentEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("components") @Scope(value = "prototype") public class ComponentsImpl implements Components { - private final ComponentManager componentManager; - - public ComponentsImpl() { - this.componentManager = ComponentManagerFactory.getInstance().createInterface(); - } - - public ComponentsImpl(ComponentManager componentManager) { - this.componentManager = componentManager; - } - @Override - public Response list(String vspId, String versionId, String user) { + private final ComponentManager componentManager; - Collection components = - componentManager.listComponents(vspId, new Version(versionId)); - - MapComponentEntityToComponentDto mapper = new MapComponentEntityToComponentDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (ComponentEntity component : components) { - results.add(mapper.applyMapping(component, ComponentDto.class)); + public ComponentsImpl() { + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } - - @Override - public Response deleteList(String vspId, String versionId, String user) { - componentManager.deleteComponents(vspId, new Version(versionId)); - return Response.ok().build(); - } - - @Override - public Response create(ComponentRequestDto request, String vspId, String versionId, String user) { - - ComponentEntity component = - new MapComponentRequestDtoToComponentEntity().applyMapping(request, ComponentEntity.class); - component.setVspId(vspId); - component.setVersion(new Version(versionId)); - - ComponentEntity createdComponent = componentManager.createComponent(component); - MapComponentEntityToComponentCreationDto mapping = - new MapComponentEntityToComponentCreationDto(); - ComponentCreationDto createdComponentDto = mapping.applyMapping(createdComponent, - ComponentCreationDto.class); - return Response - .ok(createdComponent != null ? createdComponentDto : null) - .build(); - } - - @Override - public Response get(String vspId, String versionId, String componentId, String user) { + public ComponentsImpl(ComponentManager componentManager) { + this.componentManager = componentManager; + } - CompositionEntityResponse response = - componentManager.getComponent(vspId, new Version(versionId), componentId); + @Override + public Response list(String vspId, String versionId, String user) { + Collection components = componentManager.listComponents(vspId, new Version(versionId)); + MapComponentEntityToComponentDto mapper = new MapComponentEntityToComponentDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (ComponentEntity component : components) { + results.add(mapper.applyMapping(component, ComponentDto.class)); + } + return Response.ok(results).build(); + } - CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); - new MapCompositionEntityResponseToDto<>(new MapComponentDataToComponentDto(), - ComponentDto.class).doMapping(response, responseDto); - return Response.ok(responseDto).build(); - } + @Override + public Response deleteList(String vspId, String versionId, String user) { + componentManager.deleteComponents(vspId, new Version(versionId)); + return Response.ok().build(); + } - @Override - public Response delete(String vspId, String versionId, String componentId, String user) { - componentManager.deleteComponent(vspId, new Version(versionId), componentId); - return Response.ok().build(); - } + @Override + public Response create(ComponentRequestDto request, String vspId, String versionId, String user) { + ComponentEntity component = new MapComponentRequestDtoToComponentEntity().applyMapping(request, ComponentEntity.class); + component.setVspId(vspId); + component.setVersion(new Version(versionId)); + ComponentEntity createdComponent = componentManager.createComponent(component); + MapComponentEntityToComponentCreationDto mapping = new MapComponentEntityToComponentCreationDto(); + ComponentCreationDto createdComponentDto = mapping.applyMapping(createdComponent, ComponentCreationDto.class); + return Response.ok(createdComponent != null ? createdComponentDto : null).build(); + } - @Override - public Response update(ComponentRequestDto request, String vspId, String versionId, - String componentId, - String user) { - ComponentEntity componentEntity = - new MapComponentRequestDtoToComponentEntity().applyMapping(request, ComponentEntity.class); - componentEntity.setVspId(vspId); - componentEntity.setVersion(new Version(versionId)); - componentEntity.setId(componentId); + @Override + public Response get(String vspId, String versionId, String componentId, String user) { + CompositionEntityResponse response = componentManager.getComponent(vspId, new Version(versionId), componentId); + CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); + new MapCompositionEntityResponseToDto<>(new MapComponentDataToComponentDto(), ComponentDto.class).doMapping(response, responseDto); + return Response.ok(responseDto).build(); + } - CompositionEntityValidationData validationData = - componentManager.updateComponent(componentEntity); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto().applyMapping(validationData, - CompositionEntityValidationDataDto.class)).build() : Response.ok().build(); - } + @Override + public Response delete(String vspId, String versionId, String componentId, String user) { + componentManager.deleteComponent(vspId, new Version(versionId), componentId); + return Response.ok().build(); + } - @Override - public Response getQuestionnaire(String vspId, String versionId, String componentId, - String user) { - QuestionnaireResponse questionnaireResponse = - componentManager.getQuestionnaire(vspId, new Version(versionId), componentId); + @Override + public Response update(ComponentRequestDto request, String vspId, String versionId, String componentId, String user) { + ComponentEntity componentEntity = new MapComponentRequestDtoToComponentEntity().applyMapping(request, ComponentEntity.class); + componentEntity.setVspId(vspId); + componentEntity.setVersion(new Version(versionId)); + componentEntity.setId(componentId); + CompositionEntityValidationData validationData = componentManager.updateComponent(componentEntity); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); - return Response.ok(result).build(); - } + @Override + public Response getQuestionnaire(String vspId, String versionId, String componentId, String user) { + QuestionnaireResponse questionnaireResponse = componentManager.getQuestionnaire(vspId, new Version(versionId), componentId); + QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + return Response.ok(result).build(); + } - @Override - public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, - String componentId, String user) { - componentManager - .updateQuestionnaire(vspId, new Version(versionId), componentId, questionnaireData); - return Response.ok().build(); - } + @Override + public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String componentId, String user) { + componentManager.updateQuestionnaire(vspId, new Version(versionId), componentId, questionnaireData); + return Response.ok().build(); + } } 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/ComputeImpl.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/ComputeImpl.java index 1eea42803b..8c06629849 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/ComputeImpl.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/ComputeImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; @@ -32,137 +34,116 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDetailsDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ComputeDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vsp.rest.Compute; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeDataToComputeDetailsDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeDetailsDtoToComputeEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToComputeCreationDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapComputeEntityToComputeDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("computes") @Scope(value = "prototype") public class ComputeImpl implements Compute { - private final ComputeManager computetManager; - private final ComponentManager componentManager; - public ComputeImpl() { - this.computetManager = ComputeManagerFactory.getInstance().createInterface(); - this.componentManager = ComponentManagerFactory.getInstance().createInterface(); - } + private final ComputeManager computetManager; + private final ComponentManager componentManager; - public ComputeImpl(ComputeManager computetManager, ComponentManager componentManager) { - this.computetManager = computetManager; - this.componentManager = componentManager; - } - - @Override - public Response list(String vspId, String versionId, String componentId, String user) { - - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - Collection computes = - computetManager.listComputes(vspId, version, componentId); - - MapComputeEntityToComputeDto mapper = new MapComputeEntityToComputeDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (ListComputeResponse compute : computes) { - results.add(mapper.applyMapping(compute, ComputeDto.class)); + public ComputeImpl() { + this.computetManager = ComputeManagerFactory.getInstance().createInterface(); + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } - - @Override - public Response get(String vspId, String versionId, String componentId, String computeId, - String user) { - - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - CompositionEntityResponse response = - computetManager.getCompute(vspId, version, componentId, computeId); - - CompositionEntityResponseDto responseDto = new - CompositionEntityResponseDto<>(); - new MapCompositionEntityResponseToDto<>(new MapComputeDataToComputeDetailsDto(), - ComputeDetailsDto.class).doMapping(response, responseDto); - return Response.ok(responseDto).build(); - } - - @Override - public Response create(ComputeDetailsDto request, String vspId, String versionId, - String componentId, String user) { - - ComputeEntity compute = new MapComputeDetailsDtoToComputeEntity().applyMapping(request, - ComputeEntity.class); - compute.setVspId(vspId); - compute.setVersion(new Version(versionId)); - compute.setComponentId(componentId); - componentManager.validateComponentExistence(vspId, compute.getVersion(), componentId); - - ComputeEntity createdCompute = computetManager.createCompute(compute); - - MapComputeEntityToComputeCreationDto mapper = new MapComputeEntityToComputeCreationDto(); - ComputeCreationDto createdComputeDto = - mapper.applyMapping(createdCompute, ComputeCreationDto.class); - return Response.ok(createdComputeDto != null ? createdComputeDto : null).build(); - } - - @Override - public Response update(ComputeDetailsDto request, String vspId, String versionId, - String componentId, String computeFlavorId, String user) { - - ComputeEntity compute = - new MapComputeDetailsDtoToComputeEntity().applyMapping(request, ComputeEntity.class); - compute.setVspId(vspId); - compute.setVersion(new Version(versionId)); - compute.setComponentId(componentId); - compute.setId(computeFlavorId); - - componentManager.validateComponentExistence(vspId, compute.getVersion(), componentId); - CompositionEntityValidationData validationData = computetManager.updateCompute(compute); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto().applyMapping(validationData, - CompositionEntityValidationDataDto.class)).build() : Response.ok().build(); - } + public ComputeImpl(ComputeManager computetManager, ComponentManager componentManager) { + this.computetManager = computetManager; + this.componentManager = componentManager; + } - @Override - public Response delete(String vspId, String versionId, String componentId, String computeFlavorId, - String user) { + @Override + public Response list(String vspId, String versionId, String componentId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + Collection computes = computetManager.listComputes(vspId, version, componentId); + MapComputeEntityToComputeDto mapper = new MapComputeEntityToComputeDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (ListComputeResponse compute : computes) { + results.add(mapper.applyMapping(compute, ComputeDto.class)); + } + return Response.ok(results).build(); + } - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - computetManager.deleteCompute(vspId, version, componentId, computeFlavorId); - return Response.ok().build(); - } + @Override + public Response get(String vspId, String versionId, String componentId, String computeId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + CompositionEntityResponse response = computetManager.getCompute(vspId, version, componentId, computeId); + CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); + new MapCompositionEntityResponseToDto<>(new MapComputeDataToComputeDetailsDto(), ComputeDetailsDto.class).doMapping(response, responseDto); + return Response.ok(responseDto).build(); + } - @Override - public Response getQuestionnaire(String vspId, String versionId, String componentId, - String computeFlavorId, String user) { + @Override + public Response create(ComputeDetailsDto request, String vspId, String versionId, String componentId, String user) { + ComputeEntity compute = new MapComputeDetailsDtoToComputeEntity().applyMapping(request, ComputeEntity.class); + compute.setVspId(vspId); + compute.setVersion(new Version(versionId)); + compute.setComponentId(componentId); + componentManager.validateComponentExistence(vspId, compute.getVersion(), componentId); + ComputeEntity createdCompute = computetManager.createCompute(compute); + MapComputeEntityToComputeCreationDto mapper = new MapComputeEntityToComputeCreationDto(); + ComputeCreationDto createdComputeDto = mapper.applyMapping(createdCompute, ComputeCreationDto.class); + return Response.ok(createdComputeDto != null ? createdComputeDto : null).build(); + } - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - QuestionnaireResponse questionnaireResponse = - computetManager.getComputeQuestionnaire(vspId, version, componentId, computeFlavorId); + @Override + public Response update(ComputeDetailsDto request, String vspId, String versionId, String componentId, String computeFlavorId, String user) { + ComputeEntity compute = new MapComputeDetailsDtoToComputeEntity().applyMapping(request, ComputeEntity.class); + compute.setVspId(vspId); + compute.setVersion(new Version(versionId)); + compute.setComponentId(componentId); + compute.setId(computeFlavorId); + componentManager.validateComponentExistence(vspId, compute.getVersion(), componentId); + CompositionEntityValidationData validationData = computetManager.updateCompute(compute); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); - return Response.ok(result).build(); - } + @Override + public Response delete(String vspId, String versionId, String componentId, String computeFlavorId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + computetManager.deleteCompute(vspId, version, componentId, computeFlavorId); + return Response.ok().build(); + } - @Override - public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, - String componentId, String computeFlavorId, String user) { + @Override + public Response getQuestionnaire(String vspId, String versionId, String componentId, String computeFlavorId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + QuestionnaireResponse questionnaireResponse = computetManager.getComputeQuestionnaire(vspId, version, componentId, computeFlavorId); + QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + return Response.ok(result).build(); + } - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - computetManager.updateComputeQuestionnaire(vspId, version, componentId, computeFlavorId, - questionnaireData); - return Response.ok().build(); - } + @Override + public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String componentId, String computeFlavorId, + String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + computetManager.updateComputeQuestionnaire(vspId, version, componentId, computeFlavorId, questionnaireData); + return Response.ok().build(); + } } 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/DeploymentFlavorsImpl.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/DeploymentFlavorsImpl.java index 13851e72e1..1f022aee18 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/DeploymentFlavorsImpl.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/DeploymentFlavorsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.DeploymentFlavorManager; import org.openecomp.sdc.vendorsoftwareproduct.DeploymentFlavorManagerFactory; @@ -28,108 +30,93 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorListResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.DeploymentFlavorRequestDto; import org.openecomp.sdcrests.vsp.rest.DeploymentFlavors; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapDeploymentFlavorEntityDeploymentFlavorToListResponse; +import org.openecomp.sdcrests.vsp.rest.mapping.MapDeploymentFlavorEntityToDeploymentFlavorCreationDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapDeploymentFlavorToDeploymentDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("deploymentFlavors") @Scope(value = "prototype") public class DeploymentFlavorsImpl implements DeploymentFlavors { - private final DeploymentFlavorManager deploymentFlavorManager; - - public DeploymentFlavorsImpl() { - this.deploymentFlavorManager = - DeploymentFlavorManagerFactory.getInstance().createInterface(); - } - - public DeploymentFlavorsImpl(DeploymentFlavorManager deploymentFlavorManager) { - this.deploymentFlavorManager = deploymentFlavorManager; - } - @Override - public Response create(DeploymentFlavorRequestDto request, String vspId, String versionId, - String user) { - DeploymentFlavorEntity deploymentFlavorEntity = - new MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity() - .applyMapping(request, DeploymentFlavorEntity.class); - deploymentFlavorEntity.setVspId(vspId); - deploymentFlavorEntity.setVersion(new Version(versionId)); - DeploymentFlavorEntity createdDeploymentFlavor = - deploymentFlavorManager.createDeploymentFlavor(deploymentFlavorEntity); - MapDeploymentFlavorEntityToDeploymentFlavorCreationDto mapping = - new MapDeploymentFlavorEntityToDeploymentFlavorCreationDto(); - DeploymentFlavorCreationDto deploymentFlavorCreatedDto = mapping.applyMapping - (createdDeploymentFlavor, DeploymentFlavorCreationDto.class); - return Response - .ok(createdDeploymentFlavor != null ? deploymentFlavorCreatedDto : null) - .build(); - } + private final DeploymentFlavorManager deploymentFlavorManager; - @Override - public Response list(String vspId, String versionId, String user) { - Collection deploymentFlavors = - deploymentFlavorManager.listDeploymentFlavors(vspId, new Version(versionId)); + public DeploymentFlavorsImpl() { + this.deploymentFlavorManager = DeploymentFlavorManagerFactory.getInstance().createInterface(); + } - MapDeploymentFlavorEntityDeploymentFlavorToListResponse mapper = new - MapDeploymentFlavorEntityDeploymentFlavorToListResponse(); - GenericCollectionWrapper results = - new GenericCollectionWrapper<>(); - for (DeploymentFlavorEntity deploymentFlavor : deploymentFlavors) { - results.add(mapper.applyMapping(deploymentFlavor, DeploymentFlavorListResponseDto.class)); + public DeploymentFlavorsImpl(DeploymentFlavorManager deploymentFlavorManager) { + this.deploymentFlavorManager = deploymentFlavorManager; } - return Response.ok(results).build(); - } - @Override - public Response get(String vspId, String versionId, String deploymentFlavorId, String user) { - CompositionEntityResponse response = deploymentFlavorManager - .getDeploymentFlavor(vspId, new Version(versionId), deploymentFlavorId); + @Override + public Response create(DeploymentFlavorRequestDto request, String vspId, String versionId, String user) { + DeploymentFlavorEntity deploymentFlavorEntity = new MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity() + .applyMapping(request, DeploymentFlavorEntity.class); + deploymentFlavorEntity.setVspId(vspId); + deploymentFlavorEntity.setVersion(new Version(versionId)); + DeploymentFlavorEntity createdDeploymentFlavor = deploymentFlavorManager.createDeploymentFlavor(deploymentFlavorEntity); + MapDeploymentFlavorEntityToDeploymentFlavorCreationDto mapping = new MapDeploymentFlavorEntityToDeploymentFlavorCreationDto(); + DeploymentFlavorCreationDto deploymentFlavorCreatedDto = mapping.applyMapping(createdDeploymentFlavor, DeploymentFlavorCreationDto.class); + return Response.ok(createdDeploymentFlavor != null ? deploymentFlavorCreatedDto : null).build(); + } - CompositionEntityResponseDto responseDto = new - CompositionEntityResponseDto<>(); - new MapCompositionEntityResponseToDto<>(new MapDeploymentFlavorToDeploymentDto(), - DeploymentFlavorDto.class) - .doMapping(response, responseDto); - return Response.ok(responseDto).build(); - } + @Override + public Response list(String vspId, String versionId, String user) { + Collection deploymentFlavors = deploymentFlavorManager.listDeploymentFlavors(vspId, new Version(versionId)); + MapDeploymentFlavorEntityDeploymentFlavorToListResponse mapper = new MapDeploymentFlavorEntityDeploymentFlavorToListResponse(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (DeploymentFlavorEntity deploymentFlavor : deploymentFlavors) { + results.add(mapper.applyMapping(deploymentFlavor, DeploymentFlavorListResponseDto.class)); + } + return Response.ok(results).build(); + } - @Override - public Response getSchema(String vspId, String versionId, String user) { - CompositionEntityResponse response = deploymentFlavorManager - .getDeploymentFlavorSchema(vspId, new Version(versionId)); - return Response.ok(response).build(); - } + @Override + public Response get(String vspId, String versionId, String deploymentFlavorId, String user) { + CompositionEntityResponse response = deploymentFlavorManager + .getDeploymentFlavor(vspId, new Version(versionId), deploymentFlavorId); + CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); + new MapCompositionEntityResponseToDto<>(new MapDeploymentFlavorToDeploymentDto(), DeploymentFlavorDto.class).doMapping(response, responseDto); + return Response.ok(responseDto).build(); + } - @Override - public Response delete(String vspId, String versionId, String deploymentFlavorId, String user) { - Version version = new Version(versionId); - deploymentFlavorManager.deleteDeploymentFlavor(vspId, version, deploymentFlavorId); - return Response.ok().build(); - } + @Override + public Response getSchema(String vspId, String versionId, String user) { + CompositionEntityResponse response = deploymentFlavorManager.getDeploymentFlavorSchema(vspId, new Version(versionId)); + return Response.ok(response).build(); + } - @Override - public Response update(DeploymentFlavorRequestDto request, String vspId, String versionId, - String deploymentFlavorId, String user) { - DeploymentFlavorEntity deploymentFlavorEntity = - new MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity().applyMapping(request, - DeploymentFlavorEntity.class); - deploymentFlavorEntity.setVspId(vspId); - deploymentFlavorEntity.setVersion(new Version(versionId)); - deploymentFlavorEntity.setId(deploymentFlavorId); + @Override + public Response delete(String vspId, String versionId, String deploymentFlavorId, String user) { + Version version = new Version(versionId); + deploymentFlavorManager.deleteDeploymentFlavor(vspId, version, deploymentFlavorId); + return Response.ok().build(); + } - CompositionEntityValidationData validationData = - deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto().applyMapping(validationData, - CompositionEntityValidationDataDto.class)).build() : Response.ok().build(); - } + @Override + public Response update(DeploymentFlavorRequestDto request, String vspId, String versionId, String deploymentFlavorId, String user) { + DeploymentFlavorEntity deploymentFlavorEntity = new MapDeploymentFlavorRequestDtoToDeploymentFlavorEntity() + .applyMapping(request, DeploymentFlavorEntity.class); + deploymentFlavorEntity.setVspId(vspId); + deploymentFlavorEntity.setVersion(new Version(versionId)); + deploymentFlavorEntity.setId(deploymentFlavorId); + CompositionEntityValidationData validationData = deploymentFlavorManager.updateDeploymentFlavor(deploymentFlavorEntity); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } } 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/ImagesImpl.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/ImagesImpl.java index 7971b48427..350630c0aa 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/ImagesImpl.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/ImagesImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; - +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; @@ -32,135 +33,116 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Image; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageCreationDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.ImageRequestDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vsp.rest.Images; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapImageEntityToImageCreationDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapImageEntityToImageDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapImageRequestDtoToImageEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - - @Named @Service("images") @Scope(value = "prototype") public class ImagesImpl implements Images { - private final ImageManager imageManager; - private final ComponentManager componentManager; - - public ImagesImpl() { - this.imageManager = ImageManagerFactory.getInstance().createInterface(); - this.componentManager = - ComponentManagerFactory.getInstance().createInterface(); - } - - public ImagesImpl(ImageManager imageManager, ComponentManager componentManager) { - this.imageManager = imageManager; - this.componentManager = componentManager; - } - - @Override - public Response create(ImageRequestDto request, String vspId, String versionId, - String componentId, String user) { - ImageEntity image = - new MapImageRequestDtoToImageEntity().applyMapping(request, ImageEntity.class); - image.setVspId(vspId); - image.setComponentId(componentId); - image.setVersion(new Version(versionId)); - componentManager.validateComponentExistence(vspId, image.getVersion(), componentId); - ImageEntity createdImage = imageManager.createImage(image); - MapImageEntityToImageCreationDto mapping = new MapImageEntityToImageCreationDto(); - ImageCreationDto createdImageDto = mapping.applyMapping(createdImage, ImageCreationDto.class); - return Response - .ok(createdImage != null ? createdImageDto : null) - .build(); - } + private final ImageManager imageManager; + private final ComponentManager componentManager; - @Override - public Response getImageSchema(String vspId, String versionId, String componentId, String user) { - CompositionEntityResponse response = imageManager.getImageSchema(vspId); - return Response.ok(response).build(); - } - - @Override - public Response get(String vspId, String versionId, String componentId, String imageId, - String user) { - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - CompositionEntityResponse response = - imageManager.getImage(vspId, version, componentId, imageId); - - return Response.ok(response).build(); - } - - @Override - public Response list(String vspId, String versionId, String componentId, String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - Collection images = imageManager.listImages(vspId, vspVersion, componentId); - - MapImageEntityToImageDto mapper = new MapImageEntityToImageDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (ImageEntity image : images) { - results.add(mapper.applyMapping(image, ImageDto.class)); + public ImagesImpl() { + this.imageManager = ImageManagerFactory.getInstance().createInterface(); + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } + public ImagesImpl(ImageManager imageManager, ComponentManager componentManager) { + this.imageManager = imageManager; + this.componentManager = componentManager; + } - @Override - public Response delete(String vspId, String versionId, String componentId, String imageId, - String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - imageManager.deleteImage(vspId, vspVersion, componentId, imageId); - return Response.ok().build(); - } + @Override + public Response create(ImageRequestDto request, String vspId, String versionId, String componentId, String user) { + ImageEntity image = new MapImageRequestDtoToImageEntity().applyMapping(request, ImageEntity.class); + image.setVspId(vspId); + image.setComponentId(componentId); + image.setVersion(new Version(versionId)); + componentManager.validateComponentExistence(vspId, image.getVersion(), componentId); + ImageEntity createdImage = imageManager.createImage(image); + MapImageEntityToImageCreationDto mapping = new MapImageEntityToImageCreationDto(); + ImageCreationDto createdImageDto = mapping.applyMapping(createdImage, ImageCreationDto.class); + return Response.ok(createdImage != null ? createdImageDto : null).build(); + } - @Override - public Response update(ImageRequestDto request, String vspId, String versionId, - String componentId, String imageId, String user) { - ImageEntity imageEntity = new MapImageRequestDtoToImageEntity().applyMapping(request, - ImageEntity.class); - imageEntity.setVspId(vspId); - imageEntity.setVersion(new Version(versionId)); - imageEntity.setComponentId(componentId); - imageEntity.setId(imageId); - componentManager.validateComponentExistence(vspId, imageEntity.getVersion(), componentId); + @Override + public Response getImageSchema(String vspId, String versionId, String componentId, String user) { + CompositionEntityResponse response = imageManager.getImageSchema(vspId); + return Response.ok(response).build(); + } - CompositionEntityValidationData validationData = imageManager.updateImage(imageEntity); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto() - .applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() : - Response.ok().build(); - } + @Override + public Response get(String vspId, String versionId, String componentId, String imageId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + CompositionEntityResponse response = imageManager.getImage(vspId, version, componentId, imageId); + return Response.ok(response).build(); + } - @Override - public Response getQuestionnaire(String vspId, String versionId, String componentId, - String imageId, String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - QuestionnaireResponse questionnaireResponse = - imageManager.getImageQuestionnaire(vspId, vspVersion, componentId, imageId); + @Override + public Response list(String vspId, String versionId, String componentId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + Collection images = imageManager.listImages(vspId, vspVersion, componentId); + MapImageEntityToImageDto mapper = new MapImageEntityToImageDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (ImageEntity image : images) { + results.add(mapper.applyMapping(image, ImageDto.class)); + } + return Response.ok(results).build(); + } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); - return Response.ok(result).build(); + @Override + public Response delete(String vspId, String versionId, String componentId, String imageId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + imageManager.deleteImage(vspId, vspVersion, componentId, imageId); + return Response.ok().build(); + } - } + @Override + public Response update(ImageRequestDto request, String vspId, String versionId, String componentId, String imageId, String user) { + ImageEntity imageEntity = new MapImageRequestDtoToImageEntity().applyMapping(request, ImageEntity.class); + imageEntity.setVspId(vspId); + imageEntity.setVersion(new Version(versionId)); + imageEntity.setComponentId(componentId); + imageEntity.setId(imageId); + componentManager.validateComponentExistence(vspId, imageEntity.getVersion(), componentId); + CompositionEntityValidationData validationData = imageManager.updateImage(imageEntity); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } - @Override - public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, - String componentId, String imageId, String user) { - Version version = new Version(versionId); - componentManager.validateComponentExistence(vspId, version, componentId); - imageManager.updateImageQuestionnaire(vspId, version, componentId, imageId, questionnaireData); - return Response.ok().build(); - } + @Override + public Response getQuestionnaire(String vspId, String versionId, String componentId, String imageId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + QuestionnaireResponse questionnaireResponse = imageManager.getImageQuestionnaire(vspId, vspVersion, componentId, imageId); + QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + return Response.ok(result).build(); + } + @Override + public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String componentId, String imageId, String user) { + Version version = new Version(versionId); + componentManager.validateComponentExistence(vspId, version, componentId); + imageManager.updateImageQuestionnaire(vspId, version, componentId, imageId, questionnaireData); + return Response.ok().build(); + } } 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/NetworksImpl.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/NetworksImpl.java index 6a6cbd0e60..e25ef8e324 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/NetworksImpl.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/NetworksImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.NetworkManager; import org.openecomp.sdc.vendorsoftwareproduct.NetworkManagerFactory; @@ -33,93 +35,74 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityVali import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.NetworkRequestDto; import org.openecomp.sdcrests.vsp.rest.Networks; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNetworkEntityToNetworkDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNetworkRequestDtoToNetworkEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNetworkToNetworkDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.openecomp.sdcrests.wrappers.StringWrapperResponse; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("networks") @Scope(value = "prototype") public class NetworksImpl implements Networks { - private final NetworkManager networkManager; - - public NetworksImpl(NetworkManager networkManager) { - this.networkManager = networkManager; - } + private final NetworkManager networkManager; - public NetworksImpl() { - this(NetworkManagerFactory.getInstance().createInterface()); - } - - @Override - public Response list(String vspId, String versionId, String user) { - Collection networks = - networkManager.listNetworks(vspId, new Version(versionId)); - - MapNetworkEntityToNetworkDto mapper = new MapNetworkEntityToNetworkDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (NetworkEntity network : networks) { - results.add(mapper.applyMapping(network, NetworkDto.class)); + public NetworksImpl(NetworkManager networkManager) { + this.networkManager = networkManager; } - return Response.ok(results).build(); - } - - @Override - public Response create(NetworkRequestDto request, String vspId, String versionId, String user) { - NetworkEntity network = - new MapNetworkRequestDtoToNetworkEntity().applyMapping(request, NetworkEntity.class); - network.setVspId(vspId); - network.setVersion(new Version(versionId)); - NetworkEntity createdNetwork = networkManager.createNetwork(network); - return Response - .ok(createdNetwork != null ? new StringWrapperResponse(createdNetwork.getId()) : null) - .build(); - } + public NetworksImpl() { + this(NetworkManagerFactory.getInstance().createInterface()); + } - @Override - public Response get(String vspId, String versionId, String networkId, String user) { - CompositionEntityResponse response = - networkManager.getNetwork(vspId, - new Version(versionId), networkId - ); + @Override + public Response list(String vspId, String versionId, String user) { + Collection networks = networkManager.listNetworks(vspId, new Version(versionId)); + MapNetworkEntityToNetworkDto mapper = new MapNetworkEntityToNetworkDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (NetworkEntity network : networks) { + results.add(mapper.applyMapping(network, NetworkDto.class)); + } + return Response.ok(results).build(); + } - CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); - new MapCompositionEntityResponseToDto<>(new MapNetworkToNetworkDto(), NetworkDto.class) - .doMapping(response, responseDto); - return Response.ok(responseDto).build(); - } + @Override + public Response create(NetworkRequestDto request, String vspId, String versionId, String user) { + NetworkEntity network = new MapNetworkRequestDtoToNetworkEntity().applyMapping(request, NetworkEntity.class); + network.setVspId(vspId); + network.setVersion(new Version(versionId)); + NetworkEntity createdNetwork = networkManager.createNetwork(network); + return Response.ok(createdNetwork != null ? new StringWrapperResponse(createdNetwork.getId()) : null).build(); + } - @Override - public Response delete(String vspId, String versionId, String networkId, String user) { - networkManager - .deleteNetwork(vspId, new Version(versionId), - networkId); - return Response.ok().build(); - } + @Override + public Response get(String vspId, String versionId, String networkId, String user) { + CompositionEntityResponse response = networkManager.getNetwork(vspId, new Version(versionId), networkId); + CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); + new MapCompositionEntityResponseToDto<>(new MapNetworkToNetworkDto(), NetworkDto.class).doMapping(response, responseDto); + return Response.ok(responseDto).build(); + } - @Override - public Response update(NetworkRequestDto request, String vspId, String versionId, - String networkId, String user) { - NetworkEntity networkEntity = - new MapNetworkRequestDtoToNetworkEntity().applyMapping(request, NetworkEntity.class); - networkEntity.setVspId(vspId); - networkEntity.setVersion(new Version(versionId)); - networkEntity.setId(networkId); + @Override + public Response delete(String vspId, String versionId, String networkId, String user) { + networkManager.deleteNetwork(vspId, new Version(versionId), networkId); + return Response.ok().build(); + } - CompositionEntityValidationData validationData = - networkManager.updateNetwork(networkEntity); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto() - .applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() : - Response.ok().build(); - } + @Override + public Response update(NetworkRequestDto request, String vspId, String versionId, String networkId, String user) { + NetworkEntity networkEntity = new MapNetworkRequestDtoToNetworkEntity().applyMapping(request, NetworkEntity.class); + networkEntity.setVspId(vspId); + networkEntity.setVersion(new Version(versionId)); + networkEntity.setId(networkId); + CompositionEntityValidationData validationData = networkManager.updateNetwork(networkEntity); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } } 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/NicsImpl.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/NicsImpl.java index 11ed508286..9784015089 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/NicsImpl.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/NicsImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vsp.rest.services; +import java.util.Collection; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; @@ -31,131 +33,115 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.*; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.CompositionEntityValidationDataDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicCreationResponseDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.NicRequestDto; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.QuestionnaireResponseDto; import org.openecomp.sdcrests.vsp.rest.Nics; -import org.openecomp.sdcrests.vsp.rest.mapping.*; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityResponseToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapCompositionEntityValidationDataToDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNicEntityToNicCreationResponseDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNicEntityToNicDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNicRequestDtoToNicEntity; +import org.openecomp.sdcrests.vsp.rest.mapping.MapNicToNicDto; +import org.openecomp.sdcrests.vsp.rest.mapping.MapQuestionnaireResponseToQuestionnaireResponseDto; import org.openecomp.sdcrests.wrappers.GenericCollectionWrapper; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.util.Collection; - @Named @Service("nics") @Scope(value = "prototype") public class NicsImpl implements Nics { - private final NicManager nicManager; - private final ComponentManager componentManager; - - public NicsImpl() { - this.nicManager = NicManagerFactory.getInstance().createInterface(); - this.componentManager = ComponentManagerFactory.getInstance().createInterface(); - } - public NicsImpl(NicManager nicManager, ComponentManager componentManager) { - this.nicManager = nicManager; - this.componentManager = componentManager; - } + private final NicManager nicManager; + private final ComponentManager componentManager; - @Override - public Response list(String vspId, String versionId, String componentId, String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - Collection nics = nicManager.listNics(vspId, vspVersion, componentId); - - MapNicEntityToNicDto mapper = new MapNicEntityToNicDto(); - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); - for (NicEntity nic : nics) { - results.add(mapper.applyMapping(nic, NicDto.class)); + public NicsImpl() { + this.nicManager = NicManagerFactory.getInstance().createInterface(); + this.componentManager = ComponentManagerFactory.getInstance().createInterface(); } - return Response.ok(results).build(); - } - - @Override - public Response create(NicRequestDto request, String vspId, String versionId, String componentId, - String user) { - NicEntity nic = new MapNicRequestDtoToNicEntity().applyMapping(request, NicEntity.class); - nic.setVspId(vspId); - nic.setVersion(new Version(versionId)); - nic.setComponentId(componentId); - componentManager.validateComponentExistence(vspId, nic.getVersion(), componentId); - - NicEntity createdNic = nicManager.createNic(nic); - MapNicEntityToNicCreationResponseDto mapping = - new MapNicEntityToNicCreationResponseDto(); - NicCreationResponseDto createdNicDto = mapping.applyMapping(createdNic, - NicCreationResponseDto.class); - return Response.ok(createdNic != null ? createdNicDto : null) - .build(); - } - - @Override - public Response get(String vspId, String versionId, String componentId, String nicId, - String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - CompositionEntityResponse response = - nicManager.getNic(vspId, vspVersion, componentId, nicId); + public NicsImpl(NicManager nicManager, ComponentManager componentManager) { + this.nicManager = nicManager; + this.componentManager = componentManager; + } - CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); - new MapCompositionEntityResponseToDto<>(new MapNicToNicDto(), NicDto.class) - .doMapping(response, responseDto); - return Response.ok(responseDto).build(); - } + @Override + public Response list(String vspId, String versionId, String componentId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + Collection nics = nicManager.listNics(vspId, vspVersion, componentId); + MapNicEntityToNicDto mapper = new MapNicEntityToNicDto(); + GenericCollectionWrapper results = new GenericCollectionWrapper<>(); + for (NicEntity nic : nics) { + results.add(mapper.applyMapping(nic, NicDto.class)); + } + return Response.ok(results).build(); + } - @Override - public Response delete(String vspId, String versionId, String componentId, String nicId, - String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - nicManager.deleteNic(vspId, vspVersion, componentId, nicId); - return Response.ok().build(); - } + @Override + public Response create(NicRequestDto request, String vspId, String versionId, String componentId, String user) { + NicEntity nic = new MapNicRequestDtoToNicEntity().applyMapping(request, NicEntity.class); + nic.setVspId(vspId); + nic.setVersion(new Version(versionId)); + nic.setComponentId(componentId); + componentManager.validateComponentExistence(vspId, nic.getVersion(), componentId); + NicEntity createdNic = nicManager.createNic(nic); + MapNicEntityToNicCreationResponseDto mapping = new MapNicEntityToNicCreationResponseDto(); + NicCreationResponseDto createdNicDto = mapping.applyMapping(createdNic, NicCreationResponseDto.class); + return Response.ok(createdNic != null ? createdNicDto : null).build(); + } - @Override - public Response update(NicRequestDto request, String vspId, String versionId, String componentId, - String nicId, - String user) { - NicEntity nicEntity = new MapNicRequestDtoToNicEntity().applyMapping(request, NicEntity.class); - nicEntity.setVspId(vspId); - nicEntity.setVersion(new Version(versionId)); - nicEntity.setComponentId(componentId); - nicEntity.setId(nicId); + @Override + public Response get(String vspId, String versionId, String componentId, String nicId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + CompositionEntityResponse response = nicManager.getNic(vspId, vspVersion, componentId, nicId); + CompositionEntityResponseDto responseDto = new CompositionEntityResponseDto<>(); + new MapCompositionEntityResponseToDto<>(new MapNicToNicDto(), NicDto.class).doMapping(response, responseDto); + return Response.ok(responseDto).build(); + } - componentManager.validateComponentExistence(vspId, nicEntity.getVersion(), componentId); - CompositionEntityValidationData validationData = - nicManager.updateNic(nicEntity); - return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) - ? Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapCompositionEntityValidationDataToDto() - .applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() : - Response.ok().build(); - } + @Override + public Response delete(String vspId, String versionId, String componentId, String nicId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + nicManager.deleteNic(vspId, vspVersion, componentId, nicId); + return Response.ok().build(); + } - @Override - public Response getQuestionnaire(String vspId, String versionId, String componentId, String nicId, - String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - QuestionnaireResponse questionnaireResponse = - nicManager.getNicQuestionnaire(vspId, vspVersion, componentId, nicId); + @Override + public Response update(NicRequestDto request, String vspId, String versionId, String componentId, String nicId, String user) { + NicEntity nicEntity = new MapNicRequestDtoToNicEntity().applyMapping(request, NicEntity.class); + nicEntity.setVspId(vspId); + nicEntity.setVersion(new Version(versionId)); + nicEntity.setComponentId(componentId); + nicEntity.setId(nicId); + componentManager.validateComponentExistence(vspId, nicEntity.getVersion(), componentId); + CompositionEntityValidationData validationData = nicManager.updateNic(nicEntity); + return validationData != null && CollectionUtils.isNotEmpty(validationData.getErrors()) ? Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapCompositionEntityValidationDataToDto().applyMapping(validationData, CompositionEntityValidationDataDto.class)).build() + : Response.ok().build(); + } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); - return Response.ok(result).build(); - } + @Override + public Response getQuestionnaire(String vspId, String versionId, String componentId, String nicId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + QuestionnaireResponse questionnaireResponse = nicManager.getNicQuestionnaire(vspId, vspVersion, componentId, nicId); + QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + return Response.ok(result).build(); + } - @Override - public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, - String componentId, - String nicId, String user) { - Version vspVersion = new Version(versionId); - componentManager.validateComponentExistence(vspId, vspVersion, componentId); - nicManager - .updateNicQuestionnaire(vspId, vspVersion, componentId, nicId, questionnaireData); - return Response.ok().build(); - } + @Override + public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String componentId, String nicId, String user) { + Version vspVersion = new Version(versionId); + componentManager.validateComponentExistence(vspId, vspVersion, componentId); + nicManager.updateNicQuestionnaire(vspId, vspVersion, componentId, nicId, questionnaireData); + return Response.ok().build(); + } } 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/OrchestrationTemplateCandidateException.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/OrchestrationTemplateCandidateException.java index a7e65a7e6f..1e20d1ced7 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/OrchestrationTemplateCandidateException.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/OrchestrationTemplateCandidateException.java @@ -19,9 +19,9 @@ */ package org.openecomp.sdcrests.vsp.rest.services; -public class OrchestrationTemplateCandidateException extends Exception{ +public class OrchestrationTemplateCandidateException extends Exception { - public OrchestrationTemplateCandidateException(String message, Throwable t){ + public OrchestrationTemplateCandidateException(String message, Throwable t) { super(message, t); } } 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/OrchestrationTemplateCandidateImpl.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/OrchestrationTemplateCandidateImpl.java index b393153ece..48ad75d09c 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/OrchestrationTemplateCandidateImpl.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/OrchestrationTemplateCandidateImpl.java @@ -18,7 +18,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdcrests.vsp.rest.services; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; @@ -74,56 +73,47 @@ import org.springframework.stereotype.Service; @Service("orchestrationTemplateCandidate") @Scope(value = "prototype") public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate { - private static final Logger LOGGER = - LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class); - private final OrchestrationTemplateCandidateManager candidateManager; - - private final VendorSoftwareProductManager vendorSoftwareProductManager; - private final ActivityLogManager activityLogManager; - - - public OrchestrationTemplateCandidateImpl() { - this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface(); - this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface(); - this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); - } - - // Constructor used in test to avoid mock static - public OrchestrationTemplateCandidateImpl( - OrchestrationTemplateCandidateManager candidateManager, - VendorSoftwareProductManager vendorSoftwareProductManager, - ActivityLogManager activityLogManager) { - this.candidateManager = candidateManager; - this.vendorSoftwareProductManager = vendorSoftwareProductManager; - this.activityLogManager = activityLogManager; - } - - @Override - public Response upload(final String vspId, final String versionId, - final Attachment fileToUpload, final String user) { - final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class); - final DataHandler dataHandler = fileToUpload.getDataHandler(); - final String filename = ValidationUtils.sanitizeInputString(dataHandler.getName()); - - final OnboardingPackageProcessor onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes); - if (onboardingPackageProcessor.hasErrors()) { - final UploadFileResponseDto uploadFileResponseDto = - buildUploadResponseWithError(onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0])); - return Response.status(Status.NOT_ACCEPTABLE).entity(uploadFileResponseDto).build(); - } - final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null); + private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class); + private final OrchestrationTemplateCandidateManager candidateManager; + private final VendorSoftwareProductManager vendorSoftwareProductManager; + private final ActivityLogManager activityLogManager; - if (onboardPackageInfo == null) { - final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError( - new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename))); - return Response.ok(uploadFileResponseDto).build(); + public OrchestrationTemplateCandidateImpl() { + this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface(); + this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface(); + this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); } - final VspDetails vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId), - new Version(ValidationUtils.sanitizeInputString(versionId))); - return processOnboardPackage(onboardPackageInfo, vspDetails); - } + // Constructor used in test to avoid mock static + public OrchestrationTemplateCandidateImpl(OrchestrationTemplateCandidateManager candidateManager, + VendorSoftwareProductManager vendorSoftwareProductManager, ActivityLogManager activityLogManager) { + this.candidateManager = candidateManager; + this.vendorSoftwareProductManager = vendorSoftwareProductManager; + this.activityLogManager = activityLogManager; + } + + @Override + public Response upload(final String vspId, final String versionId, final Attachment fileToUpload, final String user) { + final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class); + final DataHandler dataHandler = fileToUpload.getDataHandler(); + final String filename = ValidationUtils.sanitizeInputString(dataHandler.getName()); + final OnboardingPackageProcessor onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes); + if (onboardingPackageProcessor.hasErrors()) { + final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError( + onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0])); + return Response.status(Status.NOT_ACCEPTABLE).entity(uploadFileResponseDto).build(); + } + final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null); + if (onboardPackageInfo == null) { + final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError( + new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename))); + return Response.ok(uploadFileResponseDto).build(); + } + final VspDetails vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId), + new Version(ValidationUtils.sanitizeInputString(versionId))); + return processOnboardPackage(onboardPackageInfo, vspDetails); + } private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails) { final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo); @@ -132,108 +122,89 @@ public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplate return Response.ok(uploadFileResponseDto).build(); } - private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) { - final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto(); - final Map> errorMap = new HashMap<>(); - final List errorMessageList = new ArrayList<>(); - Collections.addAll(errorMessageList, errorMessages); - errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList); - uploadFileResponseDto.setErrors(errorMap); - return uploadFileResponseDto; - } - - @Override - public Response get(String vspId, String versionId, String user) throws IOException { - Optional> zipFile = candidateManager.get(vspId, new Version(versionId)); - String fileName; - if (zipFile.isPresent()) { - fileName = "Candidate." + zipFile.get().getLeft(); - } else { - zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId))); - - if (!zipFile.isPresent()) { - ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters( - Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), - "")); - LOGGER.error(errorMessage.getMessage()); - return Response.status(Response.Status.NOT_FOUND).build(); - } - fileName = "Processed." + zipFile.get().getLeft(); + private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) { + final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto(); + final Map> errorMap = new HashMap<>(); + final List errorMessageList = new ArrayList<>(); + Collections.addAll(errorMessageList, errorMessages); + errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList); + uploadFileResponseDto.setErrors(errorMap); + return uploadFileResponseDto; } - Response.ResponseBuilder response = Response.ok(zipFile.get().getRight()); - response.header("Content-Disposition", "attachment; filename=" + fileName); - return response.build(); - } - - @Override - public Response abort(String vspId, String versionId) { - candidateManager.abort(vspId, new Version(versionId)); - return Response.ok().build(); - } - - @Override - public Response process(String vspId, String versionId, String user) { - - Version version = new Version(versionId); - OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version); - - activityLogManager.logActivity(new ActivityLogEntity(vspId, version, - ActivityType.Upload_Network_Package, user, true, "", "")); - - OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response); - return Response.ok(responseDto).build(); - } - - @Override - public Response updateFilesDataStructure( - String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) { - - FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto); + @Override + public Response get(String vspId, String versionId, String user) throws IOException { + Optional> zipFile = candidateManager.get(vspId, new Version(versionId)); + String fileName; + if (zipFile.isPresent()) { + fileName = "Candidate." + zipFile.get().getLeft(); + } else { + zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId))); + if (!zipFile.isPresent()) { + ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), "")); + LOGGER.error(errorMessage.getMessage()); + return Response.status(Response.Status.NOT_FOUND).build(); + } + fileName = "Processed." + zipFile.get().getLeft(); + } + Response.ResponseBuilder response = Response.ok(zipFile.get().getRight()); + response.header("Content-Disposition", "attachment; filename=" + fileName); + return response.build(); + } - ValidationResponse response = candidateManager - .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure); + @Override + public Response abort(String vspId, String versionId) { + candidateManager.abort(vspId, new Version(versionId)); + return Response.ok().build(); + } - if (!response.isValid()) { - return Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapValidationResponseToDto() - .applyMapping(response, ValidationResponseDto.class)).build(); + @Override + public Response process(String vspId, String versionId, String user) { + Version version = new Version(versionId); + OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version); + activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Upload_Network_Package, user, true, "", "")); + OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response); + return Response.ok(responseDto).build(); } - return Response.ok(fileDataStructureDto).build(); - } - - @Override - public Response getFilesDataStructure(String vspId, String versionId, String user) { - Optional filesDataStructure = - candidateManager.getFilesDataStructure(vspId, new Version(versionId)); - if (!filesDataStructure.isPresent()) { - filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, - new Version(versionId)); + + @Override + public Response updateFilesDataStructure(String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) { + FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto); + ValidationResponse response = candidateManager.updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure); + if (!response.isValid()) { + return Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapValidationResponseToDto().applyMapping(response, ValidationResponseDto.class)).build(); + } + return Response.ok(fileDataStructureDto).build(); } - FileDataStructureDto fileDataStructureDto = - filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto() - .applyMapping(dataStructure, FileDataStructureDto.class)) + @Override + public Response getFilesDataStructure(String vspId, String versionId, String user) { + Optional filesDataStructure = candidateManager.getFilesDataStructure(vspId, new Version(versionId)); + if (!filesDataStructure.isPresent()) { + filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, new Version(versionId)); + } + FileDataStructureDto fileDataStructureDto = filesDataStructure + .map(dataStructure -> new MapFilesDataStructureToDto().applyMapping(dataStructure, FileDataStructureDto.class)) .orElse(new FileDataStructureDto()); - return Response.ok(fileDataStructureDto).build(); - } - - private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response){ - OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto(); - result.setErrors(response.getErrors()); - result.setFileNames(response.getFileNames()); - result.setStatus(response.getStatus()); - return result; - } - - private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto){ - FilesDataStructure filesDataStructure = new FilesDataStructure(); - filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts()); - filesDataStructure.setModules(fileDataStructureDto.getModules()); - filesDataStructure.setNested(fileDataStructureDto.getNested()); - filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned()); - return filesDataStructure; - } + return Response.ok(fileDataStructureDto).build(); + } + + private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response) { + OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto(); + result.setErrors(response.getErrors()); + result.setFileNames(response.getFileNames()); + result.setStatus(response.getStatus()); + return result; + } + private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto) { + FilesDataStructure filesDataStructure = new FilesDataStructure(); + filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts()); + filesDataStructure.setModules(fileDataStructureDto.getModules()); + filesDataStructure.setNested(fileDataStructureDto.getNested()); + filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned()); + return filesDataStructure; + } } 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/ProcessesImpl.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/ProcessesImpl.java index 3a03b1f73b..2d6efcda88 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/ProcessesImpl.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/ProcessesImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,9 +19,10 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdcrests.vsp.rest.services; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ProcessRequestDto; import org.openecomp.sdcrests.vsp.rest.ComponentProcesses; @@ -30,66 +31,60 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; - @Named @Service("processes") @Scope(value = "prototype") public class ProcessesImpl implements Processes { - private final ComponentProcesses componentProcesses; + private final ComponentProcesses componentProcesses; - @Autowired - public ProcessesImpl(ComponentProcesses componentProcesses) { - this.componentProcesses = componentProcesses; - } + @Autowired + public ProcessesImpl(ComponentProcesses componentProcesses) { + this.componentProcesses = componentProcesses; + } - @Override - public Response list(String vspId, String versionId, String user) { - return componentProcesses.list(vspId, versionId, null, user); - } + @Override + public Response list(String vspId, String versionId, String user) { + return componentProcesses.list(vspId, versionId, null, user); + } - @Override - public Response deleteList(String vspId, String versionId, String user) { - return componentProcesses.deleteList(vspId, versionId, null, user); - } + @Override + public Response deleteList(String vspId, String versionId, String user) { + return componentProcesses.deleteList(vspId, versionId, null, user); + } - @Override - public Response create(ProcessRequestDto request, String vspId, String versionId, String user) { - return componentProcesses.create(request, vspId, versionId, null, user); - } + @Override + public Response create(ProcessRequestDto request, String vspId, String versionId, String user) { + return componentProcesses.create(request, vspId, versionId, null, user); + } - @Override - public Response get(String vspId, String versionId, String processId, String user) { - return componentProcesses.get(vspId, versionId, null, processId, user); - } + @Override + public Response get(String vspId, String versionId, String processId, String user) { + return componentProcesses.get(vspId, versionId, null, processId, user); + } - @Override - public Response delete(String vspId, String versionId, String processId, String user) { - return componentProcesses.delete(vspId, versionId, null, processId, user); - } + @Override + public Response delete(String vspId, String versionId, String processId, String user) { + return componentProcesses.delete(vspId, versionId, null, processId, user); + } - @Override - public Response update(ProcessRequestDto request, String vspId, String versionId, - String processId, String user) { - return componentProcesses.update(request, vspId, versionId, null, processId, user); - } + @Override + public Response update(ProcessRequestDto request, String vspId, String versionId, String processId, String user) { + return componentProcesses.update(request, vspId, versionId, null, processId, user); + } - @Override - public Response getUploadedFile(String vspId, String versionId, String processId, String user) { - return componentProcesses.getUploadedFile(vspId, versionId, null, processId, user); - } + @Override + public Response getUploadedFile(String vspId, String versionId, String processId, String user) { + return componentProcesses.getUploadedFile(vspId, versionId, null, processId, user); + } - @Override - public Response deleteUploadedFile(String vspId, String versionId, String processId, - String user) { - return componentProcesses.deleteUploadedFile(vspId, versionId, null, processId, user); - } + @Override + public Response deleteUploadedFile(String vspId, String versionId, String processId, String user) { + return componentProcesses.deleteUploadedFile(vspId, versionId, null, processId, user); + } - @Override - public Response uploadFile(Attachment attachment, String vspId, String versionId, - String processId, String user) { - return componentProcesses.uploadFile(attachment, vspId, versionId, null, processId, user); - } + @Override + public Response uploadFile(Attachment attachment, String vspId, String versionId, String processId, String user) { + return componentProcesses.uploadFile(attachment, vspId, versionId, null, processId, user); + } } 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 91c1959c86..74d2fde097 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 @@ -13,9 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.services; +import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod.NetworkPackage; +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; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.Comparator; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.inject.Named; +import javax.ws.rs.core.Response; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.dao.UniqueValueDaoFactory; import org.openecomp.core.util.UniqueValueUtil; @@ -40,7 +63,12 @@ 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.*; +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; @@ -59,27 +87,28 @@ 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.*; +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.VendorSoftwareProductAction; +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.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import javax.inject.Named; -import javax.ws.rs.core.Response; -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; -import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; -import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME; -import static org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod.NetworkPackage; -import static org.openecomp.sdc.versioning.VersioningNotificationConstansts.*; - @Named @Service("vendorSoftwareProducts") @Scope(value = "prototype") @@ -89,28 +118,17 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { private static final String VALIDATION_VSP_USER = "validationOnlyVspUser"; private static final String SUBMIT_ITEM_ACTION = "Submit_Item"; private static final String ATTACHMENT_FILENAME = "attachment; filename="; - 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."; + 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."; private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductsImpl.class); private static final Object VALIDATION_VSP_CACHE_LOCK = new Object(); - private static ItemCreationDto cachedValidationVsp; - - private final AsdcItemManager itemManager = AsdcItemManagerFactory.getInstance() - .createInterface(); - private final PermissionsManager permissionsManager = - PermissionsManagerFactory.getInstance().createInterface(); - private final VersioningManager versioningManager = - VersioningManagerFactory.getInstance().createInterface(); - private final VendorSoftwareProductManager vendorSoftwareProductManager = - VspManagerFactory.getInstance().createInterface(); - private final ActivityLogManager activityLogManager = - ActivityLogManagerFactory.getInstance().createInterface(); - private final NotificationPropagationManager notifier = - NotificationPropagationManagerFactory.getInstance().createInterface(); - private final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory - .getInstance().createInterface()); - + private final AsdcItemManager itemManager = AsdcItemManagerFactory.getInstance().createInterface(); + private final PermissionsManager permissionsManager = PermissionsManagerFactory.getInstance().createInterface(); + private final VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); + private final VendorSoftwareProductManager vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface(); + private final ActivityLogManager activityLogManager = ActivityLogManagerFactory.getInstance().createInterface(); + private final NotificationPropagationManager notifier = NotificationPropagationManagerFactory.getInstance().createInterface(); + private final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); @Override public Response createVsp(VspRequestDto vspRequestDto, String user) { @@ -119,74 +137,55 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { } private ItemCreationDto createVspItem(VspRequestDto vspRequestDto, String user) { - OnboardingMethod onboardingMethod = null; - try { onboardingMethod = OnboardingMethod.valueOf(vspRequestDto.getOnboardingMethod()); } catch (IllegalArgumentException e) { LOGGER.error("Error while creating VSP. Message: " + e.getMessage()); throwUnknownOnboardingMethodException(e); } - ItemCreationDto itemCreationDto = null; - if (onboardingMethod == NetworkPackage - || onboardingMethod == OnboardingMethod.Manual) { + if (onboardingMethod == NetworkPackage || onboardingMethod == OnboardingMethod.Manual) { itemCreationDto = createItem(vspRequestDto, user, onboardingMethod); - } else { - throwUnknownOnboardingMethodException( - new IllegalArgumentException("Wrong parameter Onboarding Method")); + throwUnknownOnboardingMethodException(new IllegalArgumentException("Wrong parameter Onboarding Method")); } - return itemCreationDto; } private ItemCreationDto createItem(VspRequestDto vspRequestDto, String user, OnboardingMethod onboardingMethod) { - Item item = new MapVspDescriptionDtoToItem().applyMapping(vspRequestDto, Item.class); item.setType(ItemType.vsp.name()); item.setOwner(user); item.setStatus(ItemStatus.ACTIVE); 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 vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspRequestDto, VspDetails.class); vspDetails.setId(item.getId()); vspDetails.setVersion(version); vspDetails.setOnboardingMethod(vspRequestDto.getOnboardingMethod()); - vendorSoftwareProductManager.createVsp(vspDetails); versioningManager.publish(item.getId(), version, "Initial vsp:" + vspDetails.getName()); ItemCreationDto 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, "", "")); + activityLogManager.logActivity(new ActivityLogEntity(vspDetails.getId(), version, ActivityType.Create, user, true, "", "")); return itemCreationDto; } private void throwUnknownOnboardingMethodException(IllegalArgumentException e) { - ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder - .getInvalidOnboardingMethodErrorBuilder(); + ErrorCode onboardingMethodUpdateErrorCode = OnboardingMethodErrorBuilder.getInvalidOnboardingMethodErrorBuilder(); throw new CoreException(onboardingMethodUpdateErrorCode, e); } @Override public Response listVsps(String versionStatus, String itemStatus, String user) { - GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapItemToVspDetailsDto mapper = new MapItemToVspDetailsDto(); - - getVspList(versionStatus, itemStatus, user) - .forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class))); - + getVspList(versionStatus, itemStatus, user).forEach(vspItem -> results.add(mapper.applyMapping(vspItem, VspDetailsDto.class))); return Response.ok(results).build(); } @@ -194,23 +193,18 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { public Response getVsp(String vspId, String versionId, String user) { Version version = versioningManager.get(vspId, new Version(versionId)); VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version); - try { - HealingManagerFactory.getInstance().createInterface() - .healItemVersion(vspId, version, ItemType.vsp, false) - .ifPresent(healedVersion -> { - vspDetails.setVersion(healedVersion); - if (version.getStatus() == VersionStatus.Certified) { - submitHealedVersion(vspDetails, versionId, user); - } - }); + HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, version, ItemType.vsp, false).ifPresent(healedVersion -> { + vspDetails.setVersion(healedVersion); + if (version.getStatus() == VersionStatus.Certified) { + submitHealedVersion(vspDetails, versionId, user); + } + }); } catch (Exception e) { LOGGER.error(String.format("Error while auto healing VSP with Id %s and version %s", vspId, versionId), e); } - VspDetailsDto vspDetailsDto = new MapVspDetailsToDto().applyMapping(vspDetails, VspDetailsDto.class); addNetworkPackageInfo(vspId, vspDetails.getVersion(), vspDetailsDto); - return Response.ok(vspDetailsDto).build(); } @@ -220,88 +214,63 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { // sync vlm if not exists on user space versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion()); } - - submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user) - .ifPresent(validationResponse -> { - throw new IllegalStateException("Certified vsp after healing failed on validation"); - }); + submit(vspDetails.getId(), vspDetails.getVersion(), "Submit healed Vsp", user).ifPresent(validationResponse -> { + throw new IllegalStateException("Certified vsp after healing failed on validation"); + }); vendorSoftwareProductManager.createPackage(vspDetails.getId(), vspDetails.getVersion()); } catch (Exception ex) { - LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), - baseVersionId), ex); + LOGGER.error(String.format(SUBMIT_HEALED_VERSION_ERROR, vspDetails.getId(), vspDetails.getVersion().getId(), baseVersionId), ex); } } @Override - public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, - String user) { - VspDetails vspDetails = - new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class); + public Response updateVsp(String vspId, String versionId, VspDescriptionDto vspDescriptionDto, String user) { + VspDetails vspDetails = new MapVspDescriptionDtoToVspDetails().applyMapping(vspDescriptionDto, VspDetails.class); vspDetails.setId(vspId); vspDetails.setVersion(new Version(versionId)); - vendorSoftwareProductManager.updateVsp(vspDetails); - - updateVspItem(vspId,vspDescriptionDto); - + updateVspItem(vspId, vspDescriptionDto); return Response.ok().build(); } @Override public Response deleteVsp(String vspId, String user) { Item vsp = itemManager.get(vspId); - if (!vsp.getType().equals(ItemType.vsp.name())) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder() - .withMessage(String.format("Vsp with id %s does not exist.", - vspId)).build())); + throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String.format("Vsp with id %s does not exist.", vspId)).build())); } - Integer certifiedVersionsCounter = vsp.getVersionStatusCounters().get(VersionStatus.Certified); if (Objects.isNull(certifiedVersionsCounter) || certifiedVersionsCounter == 0) { - versioningManager.list(vspId) - .forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version)); + versioningManager.list(vspId).forEach(version -> vendorSoftwareProductManager.deleteVsp(vspId, version)); itemManager.delete(vsp); permissionsManager.deleteItemPermissions(vspId); uniqueValueUtil.deleteUniqueValue(VENDOR_SOFTWARE_PRODUCT_NAME, vsp.getName()); - notifyUsers(vspId, vsp.getName(), null, null, user, - NotificationEventTypes.DELETE); - + notifyUsers(vspId, vsp.getName(), null, null, user, NotificationEventTypes.DELETE); return Response.ok().build(); } else { - return Response.status(Response.Status.FORBIDDEN) - .entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build(); + return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.DELETE_VSP_ERROR.getErrorMessage())).build(); } } @Override - public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, - String vspId, String versionId, - String user) throws IOException { + public Response actOnVendorSoftwareProduct(VersionSoftwareProductActionRequestDto request, String vspId, String versionId, String user) + throws IOException { Version version = new Version(versionId); - if (request.getAction() == VendorSoftwareProductAction.Submit) { if (!permissionsManager.isAllowed(vspId, user, SUBMIT_ITEM_ACTION)) { - return Response.status(Response.Status.FORBIDDEN) - .entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); + return Response.status(Response.Status.FORBIDDEN).entity(new Exception(Messages.PERMISSIONS_ERROR.getErrorMessage())).build(); } - String message = request.getSubmitRequest() == null ? "Submit" - : request.getSubmitRequest().getMessage(); + String message = request.getSubmitRequest() == null ? "Submit" : 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(); + .applyMapping(validationResponse.get(), ValidationResponseDto.class); + return Response.status(Response.Status.EXPECTATION_FAILED).entity(validationResponseDto).build(); } - notifyUsers(vspId, null, version, message, user, NotificationEventTypes.SUBMIT); - } else if (request.getAction() == VendorSoftwareProductAction.Create_Package) { return createPackage(vspId, version); } - return Response.ok().build(); } @@ -312,35 +281,24 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { } private ItemCreationDto retrieveValidationVsp() { - synchronized (VALIDATION_VSP_CACHE_LOCK) { - if (cachedValidationVsp != null) { return cachedValidationVsp; } - VspRequestDto validationVspRequest = new VspRequestDto(); validationVspRequest.setOnboardingMethod(NetworkPackage.toString()); validationVspRequest.setName(VALIDATION_VSP_NAME); - try { - cachedValidationVsp = createVspItem(validationVspRequest, VALIDATION_VSP_USER); return cachedValidationVsp; - } catch (CoreException vspCreateException) { LOGGER.debug("Failed to create validation VSP", vspCreateException); - Predicate validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) - && VALIDATION_VSP_NAME.equals(item.getName()); - String validationVspId = itemManager.list(validationVspFilter).stream().findFirst() - .orElseThrow(() -> new IllegalStateException( - "Vsp with name " + VALIDATION_VSP_NAME + - " does not exist even though the name exists according to " + - "unique value util")) - .getId(); - + Predicate validationVspFilter = item -> ItemType.vsp.name().equals(item.getType()) && VALIDATION_VSP_NAME + .equals(item.getName()); + String validationVspId = itemManager.list(validationVspFilter).stream().findFirst().orElseThrow(() -> new IllegalStateException( + "Vsp with name " + VALIDATION_VSP_NAME + " does not exist even though the name exists according to " + "unique value util")) + .getId(); Version validationVspVersion = versioningManager.list(validationVspId).iterator().next(); - cachedValidationVsp = new ItemCreationDto(); cachedValidationVsp.setItemId(validationVspId); cachedValidationVsp.setVersion(new MapVersionToDto().applyMapping(validationVspVersion, VersionDto.class)); @@ -351,9 +309,7 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { @Override public Response getOrchestrationTemplate(String vspId, String versionId, String user) { - byte[] orchestrationTemplateFile = - vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId)); - + byte[] orchestrationTemplateFile = vendorSoftwareProductManager.getOrchestrationTemplateFile(vspId, new Version(versionId)); if (orchestrationTemplateFile == null || orchestrationTemplateFile.length == 0) { return Response.status(Response.Status.NOT_FOUND).build(); } @@ -364,21 +320,12 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { @Override public Response listPackages(String status, String category, String subCategory, String user) { - - List vspsIds = - getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user) - .stream().map(Item::getId).collect(Collectors.toList()); - - List packageInfoList = - vendorSoftwareProductManager.listPackages(category, subCategory); - - packageInfoList = packageInfoList.stream(). - filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())) - .collect(Collectors.toList()); - + List vspsIds = getVspList(null, status != null ? ItemStatus.valueOf(status).name() : null, user).stream().map(Item::getId) + .collect(Collectors.toList()); + List packageInfoList = vendorSoftwareProductManager.listPackages(category, subCategory); + packageInfoList = packageInfoList.stream().filter(packageInfo -> vspsIds.contains(packageInfo.getVspId())).collect(Collectors.toList()); GenericCollectionWrapper results = new GenericCollectionWrapper<>(); MapPackageInfoToPackageInfoDto mapper = new MapPackageInfoToPackageInfoDto(); - if (packageInfoList != null) { for (PackageInfo packageInfo : packageInfoList) { results.add(mapper.applyMapping(packageInfo, PackageInfoDto.class)); @@ -393,90 +340,71 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { Version version; if (versionName == null) { version = versions.stream().filter(ver -> VersionStatus.Certified == ver.getStatus()) - .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName()))) - .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build())); + .max(Comparator.comparingDouble(o -> Double.parseDouble(o.getName()))) + .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build())); } else { - version = versions.stream().filter(ver -> versionName.equals(ver.getName())) - .findFirst() - .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build())); - + version = versions.stream().filter(ver -> versionName.equals(ver.getName())).findFirst() + .orElseThrow(() -> new CoreException(new PackageNotFoundErrorBuilder(vspId).build())); if (version.getStatus() != VersionStatus.Certified) { throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); } } - File zipFile = vendorSoftwareProductManager.getTranslatedFile(vspId, version); - Response.ResponseBuilder response = Response.ok(zipFile); if (zipFile == null) { return Response.status(Response.Status.NOT_FOUND).build(); } response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + zipFile.getName()); - return response.build(); } @Override public Response getQuestionnaire(String vspId, String versionId, String user) { - QuestionnaireResponse questionnaireResponse = - vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId)); - + QuestionnaireResponse questionnaireResponse = vendorSoftwareProductManager.getVspQuestionnaire(vspId, new Version(versionId)); if (questionnaireResponse.getErrorMessage() != null) { - return Response.status(Response.Status.EXPECTATION_FAILED).entity( - new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)).build(); + return Response.status(Response.Status.EXPECTATION_FAILED) + .entity(new MapQuestionnaireResponseToQuestionnaireResponseDto().applyMapping(questionnaireResponse, QuestionnaireResponseDto.class)) + .build(); } - QuestionnaireResponseDto result = new MapQuestionnaireResponseToQuestionnaireResponseDto() - .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); + .applyMapping(questionnaireResponse, QuestionnaireResponseDto.class); return Response.ok(result).build(); } @Override - public Response updateQuestionnaire(String questionnaireData, String vspId, String - versionId, String user) { - vendorSoftwareProductManager - .updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData); + public Response updateQuestionnaire(String questionnaireData, String vspId, String versionId, String user) { + vendorSoftwareProductManager.updateVspQuestionnaire(vspId, new Version(versionId), questionnaireData); return Response.ok().build(); } @Override public Response heal(String vspId, String versionId, String user) { - HealingManagerFactory.getInstance().createInterface() - .healItemVersion(vspId, new Version(versionId), ItemType.vsp, true); + HealingManagerFactory.getInstance().createInterface().healItemVersion(vspId, new Version(versionId), ItemType.vsp, true); return Response.ok().build(); } @Override public Response getVspInformationArtifact(String vspId, String versionId, String user) { - File textInformationArtifact = - vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId)); - + File textInformationArtifact = vendorSoftwareProductManager.getInformationArtifact(vspId, new Version(versionId)); Response.ResponseBuilder response = Response.ok(textInformationArtifact); if (textInformationArtifact == null) { return Response.status(Response.Status.NOT_FOUND).build(); } - response - .header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName()); + response.header(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + textInformationArtifact.getName()); return response.build(); } @Override public Response listComputes(String vspId, String version, String user) { - - Collection computes = - vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version)); - + Collection computes = vendorSoftwareProductManager.getComputeByVsp(vspId, new Version(version)); MapComputeEntityToVspComputeDto mapper = new MapComputeEntityToVspComputeDto(); GenericCollectionWrapper results = new GenericCollectionWrapper<>(); for (ComputeEntity compute : computes) { results.add(mapper.applyMapping(compute, VspComputeDto.class)); } - return Response.ok(results).build(); } - private void updateVspItem(String vspId, VspDescriptionDto vspDescriptionDto) { Item retrievedItem = itemManager.get(vspId); Item item = new MapVspDescriptionDtoToItem().applyMapping(vspDescriptionDto, Item.class); @@ -487,52 +415,37 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { item.setVersionStatusCounters(retrievedItem.getVersionStatusCounters()); item.setCreationTime(retrievedItem.getCreationTime()); item.setModificationTime(new Date()); - item.addProperty(VspItemProperty.ONBOARDING_METHOD, - retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD)); - + item.addProperty(VspItemProperty.ONBOARDING_METHOD, retrievedItem.getProperties().get(VspItemProperty.ONBOARDING_METHOD)); itemManager.update(item); } - private Optional submit(String vspId, Version version, String message, - String user) throws IOException { - + private Optional submit(String vspId, Version version, String message, String user) throws IOException { VspDetails vspDetails = vendorSoftwareProductManager.getVsp(vspId, version); if (vspDetails.getVlmVersion() != null) { vspDetails.setVlmVersion(versioningManager.get(vspDetails.getVendorId(), vspDetails.getVlmVersion())); } ValidationResponse validationResponse = vendorSoftwareProductManager.validate(vspDetails); - Map> compilationErrors = - vendorSoftwareProductManager.compile(vspId, version); + Map> compilationErrors = vendorSoftwareProductManager.compile(vspId, version); if (!validationResponse.isValid() || MapUtils.isNotEmpty(compilationErrors)) { - activityLogManager.logActivity( - new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, - "Failed on validation before submit", "")); + activityLogManager + .logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, false, "Failed on validation before submit", "")); return Optional.of(validationResponse); } - versioningManager.submit(vspId, version, message); - activityLogManager.logActivity( - new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message)); + activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Submit, user, true, "", message)); return Optional.empty(); } - private void notifyUsers(String itemId, String itemName, Version version, String message, - String userName, NotificationEventTypes eventType) { + private void notifyUsers(String itemId, String itemName, Version version, String message, String userName, NotificationEventTypes eventType) { Map eventProperties = new HashMap<>(); - eventProperties - .put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName); + eventProperties.put(ITEM_NAME, itemName == null ? itemManager.get(itemId).getName() : itemName); eventProperties.put(ITEM_ID, itemId); - if (version != null) { - eventProperties.put(VERSION_NAME, version.getName() == null - ? versioningManager.get(itemId, version).getName() - : version.getName()); + eventProperties.put(VERSION_NAME, version.getName() == null ? versioningManager.get(itemId, version).getName() : version.getName()); eventProperties.put(VERSION_ID, version.getId()); } - eventProperties.put(SUBMIT_DESCRIPTION, message); eventProperties.put(PERMISSION_USER, userName); - Event syncEvent = new SyncEvent(eventType.getEventName(), itemId, eventProperties, itemId); try { notifier.notifySubscribers(syncEvent, userName); @@ -544,91 +457,68 @@ public class VendorSoftwareProductsImpl implements VendorSoftwareProducts { private Response createPackage(String vspId, Version version) throws IOException { Version retrievedVersion = versioningManager.get(vspId, version); if (retrievedVersion.getStatus() != VersionStatus.Certified) { - throw new CoreException( - new CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(vspId, version) - .build()); + 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(); + 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) { - Optional candidateInfo = - OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface() + private void addNetworkPackageInfo(String vspId, Version version, VspDetailsDto vspDetailsDto) { + Optional candidateInfo = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface() .getInfo(vspId, version); - if (candidateInfo.isPresent()) { - if (candidateInfo.get().getValidationDataStructure() != null) { - vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure()); - } - vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName()); - vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix()); - } else { - OrchestrationTemplateEntity orchestrationTemplateInfo = - vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version); - if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo - .getFileSuffix())) { - if (orchestrationTemplateInfo.getValidationDataStructure() != null) { - vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure()); + if (candidateInfo.isPresent()) { + if (candidateInfo.get().getValidationDataStructure() != null) { + vspDetailsDto.setValidationData(candidateInfo.get().getValidationDataStructure()); + } + vspDetailsDto.setNetworkPackageName(candidateInfo.get().getFileName()); + vspDetailsDto.setCandidateOnboardingOrigin(candidateInfo.get().getFileSuffix()); + } else { + OrchestrationTemplateEntity orchestrationTemplateInfo = vendorSoftwareProductManager.getOrchestrationTemplateInfo(vspId, version); + if (Objects.nonNull(orchestrationTemplateInfo) && Objects.nonNull(orchestrationTemplateInfo.getFileSuffix())) { + if (orchestrationTemplateInfo.getValidationDataStructure() != null) { + vspDetailsDto.setValidationData(orchestrationTemplateInfo.getValidationDataStructure()); + } + vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName()); + vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix()); + } } - vspDetailsDto.setNetworkPackageName(orchestrationTemplateInfo.getFileName()); - vspDetailsDto.setOnboardingOrigin(orchestrationTemplateInfo.getFileSuffix()); - } } - } - - private boolean userHasPermission(String itemId, String userId) { - return permissionsManager.getUserItemPermission(itemId, userId) - .map(permission -> permission - .matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())) - .orElse(false); - } - - private Predicate createItemPredicate(String versionStatus, - String itemStatus, - String user) { - Predicate itemPredicate = item -> ItemType.vsp.name().equals(item.getType()); + private boolean userHasPermission(String itemId, String userId) { + return permissionsManager.getUserItemPermission(itemId, userId) + .map(permission -> permission.matches(PermissionTypes.Contributor.name() + "|" + PermissionTypes.Owner.name())).orElse(false); + } + + private Predicate createItemPredicate(String versionStatus, String itemStatus, String user) { + Predicate itemPredicate = item -> ItemType.vsp.name().equals(item.getType()); if (ItemStatus.ARCHIVED.name().equals(itemStatus)) { itemPredicate = itemPredicate.and(item -> ItemStatus.ARCHIVED.equals(item.getStatus())); } else { itemPredicate = itemPredicate.and(item -> ItemStatus.ACTIVE.equals(item.getStatus())); - if (VersionStatus.Certified.name().equals(versionStatus)) { - itemPredicate = itemPredicate - .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified)); - + itemPredicate = itemPredicate.and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Certified)); } else if (VersionStatus.Draft.name().equals(versionStatus)) { - itemPredicate = itemPredicate.and( - item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) - && userHasPermission(item.getId(), user)); + itemPredicate = itemPredicate + .and(item -> item.getVersionStatusCounters().containsKey(VersionStatus.Draft) && userHasPermission(item.getId(), user)); } } return itemPredicate; } private List getVspList(String versionStatus, String itemStatus, String user) { - Predicate itemPredicate = createItemPredicate(versionStatus, itemStatus, user); - - return itemManager.list(itemPredicate).stream() - .sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())). - collect(Collectors.toList()); + return itemManager.list(itemPredicate).stream().sorted((o1, o2) -> o2.getModificationTime().compareTo(o1.getModificationTime())) + .collect(Collectors.toList()); } private class SyncEvent implements Event { private final String eventType; - private final String originatorId; private final Map attributes; private final String entityId; - SyncEvent(String eventType, String originatorId, - Map attributes, String entityId) { + SyncEvent(String eventType, String originatorId, Map attributes, String entityId) { this.eventType = eventType; this.originatorId = originatorId; this.attributes = attributes; 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/VspItemProperty.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/VspItemProperty.java index c958ea7c79..87ac7d8fd2 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/VspItemProperty.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/VspItemProperty.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.services; public final class VspItemProperty { - public static final String VENDOR_ID = "vendorId"; - public static final String VENDOR_NAME = "vendorName"; - public static final String ONBOARDING_METHOD = "onboardingMethod"; - private VspItemProperty() { + public static final String VENDOR_ID = "vendorId"; + public static final String VENDOR_NAME = "vendorName"; + public static final String ONBOARDING_METHOD = "onboardingMethod"; - } + private VspItemProperty() { + } } 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/VspUniqueTypeProvider.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/VspUniqueTypeProvider.java index cb7c136969..b06f4cc383 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/VspUniqueTypeProvider.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/VspUniqueTypeProvider.java @@ -15,20 +15,18 @@ */ package org.openecomp.sdcrests.vsp.rest.services; -import org.openecomp.sdcrests.uniquevalue.types.UniqueTypesProvider; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME; import java.util.Collections; import java.util.Map; - -import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME; +import org.openecomp.sdcrests.uniquevalue.types.UniqueTypesProvider; public class VspUniqueTypeProvider implements UniqueTypesProvider { - private static final Map uniqueTypes = - Collections.singletonMap("VspName", VENDOR_SOFTWARE_PRODUCT_NAME); + private static final Map uniqueTypes = Collections.singletonMap("VspName", VENDOR_SOFTWARE_PRODUCT_NAME); - @Override - public Map listUniqueTypes() { - return uniqueTypes; - } + @Override + public Map listUniqueTypes() { + return uniqueTypes; + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentCreationDto.java index f633e2cbbb..3af2c9460a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentCreationDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComponentCreationDto { + private String vfcId; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyCreationDto.java index 50bd66f0a8..148549dda9 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyCreationDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComponentDependencyCreationDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModel.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModel.java index b3a0620cc0..d05c4cde9c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModel.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModel.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModelRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModelRequestDto.java index 7a1d154bc1..66d641fb94 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModelRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyModelRequestDto.java @@ -1,29 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; - -import lombok.Data; - import java.util.List; +import lombok.Data; @Data public class ComponentDependencyModelRequestDto { private List componentDependencyModels; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyResponseDto.java index 4874efb287..e43e73899c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDependencyResponseDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComponentDependencyResponseDto { + private String sourceId; private String targetId; private String relationType; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDto.java index f9651e69e0..432c49cf31 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComponentDto extends ComponentRequestDto implements CompositionDataEntityDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRelationType.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRelationType.java index bf9e3f3b76..f6655aa071 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRelationType.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRelationType.java @@ -1,22 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -public enum ComponentRelationType { - dependsOn, - other -} +public enum ComponentRelationType {dependsOn, other} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRequestDto.java index a14e0825ca..b5fb60c6c3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentRequestDto.java @@ -1,25 +1,23 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; - import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; +import lombok.Data; @Data public class ComponentRequestDto { @@ -29,5 +27,4 @@ public class ComponentRequestDto { @Size(min = 1, max = 30, message = "VFC displayName length should be between 1 and 30.") private String displayName; private String description; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentValidationResultDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentValidationResultDto.java index 1270212e4a..e02d64fb9a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentValidationResultDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComponentValidationResultDto.java @@ -1,28 +1,26 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; - -import lombok.Data; - import java.util.Set; +import lombok.Data; @Data public class ComponentValidationResultDto { + private boolean valid; private Set validationData; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionDataEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionDataEntityDto.java index 3e6607e0ea..1aa5d797c2 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionDataEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionDataEntityDto.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vendorsoftwareproducts.types; public interface CompositionDataEntityDto { + } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityResponseDto.java index 31bbfc2085..1c1f91e962 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityResponseDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class CompositionEntityResponseDto { + private String id; private String schema; private T data; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityValidationDataDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityValidationDataDto.java index 1848276706..5f2b85deb8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityValidationDataDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/CompositionEntityValidationDataDto.java @@ -1,28 +1,27 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import java.util.Collection; import lombok.Data; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; -import java.util.Collection; - @Data public class CompositionEntityValidationDataDto { + private CompositionEntityType entityType; private String entityId; private String entityName; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeCreationDto.java index 3601d54a06..71358b8980 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeCreationDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComputeCreationDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDescription.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDescription.java index 2bc27314fd..3320ab0dbb 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDescription.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDescription.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComputeDescription { + private String name; private String description; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDetailsDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDetailsDto.java index 5e0de75a3a..843c5d5426 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDetailsDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDetailsDto.java @@ -1,32 +1,30 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import javax.validation.constraints.Size; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; -import javax.validation.constraints.Size; - @Data public class ComputeDetailsDto implements CompositionDataEntityDto { + @NotBlank(message = "is mandatory and should not be empty") @Size(min = 0, max = 30, message = "length should not exceed 30 characters.") private String name; @Size(min = 0, max = 300, message = "length should not exceed 300 characters.") private String description; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDto.java index 6f9aaa1571..e2c34dc23e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ComputeDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ComputeDto { + private String name; private String id; private String description; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorCreationDto.java index 1fb65c4e09..e0e97db0f8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorCreationDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class DeploymentFlavorCreationDto { + private String deploymentFlavorId; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorDto.java index e4eb4af3af..8a0d1059c6 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class DeploymentFlavorDto extends DeploymentFlavorRequestDto implements CompositionDataEntityDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorListResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorListResponseDto.java index db6850a6a9..b180ed5759 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorListResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorListResponseDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class DeploymentFlavorListResponseDto { + private String model; private String description; private String id; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorRequestDto.java index 2b34858ec1..3d29deb60b 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorRequestDto.java @@ -1,31 +1,29 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; - +import java.util.List; +import javax.validation.constraints.Size; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; -import javax.validation.constraints.Size; -import java.util.List; - @Data public class DeploymentFlavorRequestDto { + @NotBlank(message = "is mandatory and should not be empty") @Size(min = 0, max = 30, message = "length should not exceed 30 characters.") private String model; @@ -33,5 +31,4 @@ public class DeploymentFlavorRequestDto { private String description; private String featureGroupId; private List componentComputeAssociations; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorValidationResultDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorValidationResultDto.java index 7029bfcd4c..833636cccc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorValidationResultDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/DeploymentFlavorValidationResultDto.java @@ -1,28 +1,26 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; - -import lombok.Data; - import java.util.Set; +import lombok.Data; @Data public class DeploymentFlavorValidationResultDto { + private boolean valid; private Set validationData; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/FileDataStructureDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/FileDataStructureDto.java index 166efec6fa..a98c515815 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/FileDataStructureDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/FileDataStructureDto.java @@ -1,33 +1,31 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import java.util.List; import lombok.Data; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module; -import java.util.List; - /** * @author Avrahamg * @since November 07, 2016 */ - @Data public class FileDataStructureDto { + private List modules; private List unassigned; private List artifacts; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageCreationDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageCreationDto.java index 96775a669b..b0af65c3d5 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageCreationDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageCreationDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ImageCreationDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageDto.java index 40105a6c47..0cfb9249ef 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ImageDto extends ImageRequestDto implements CompositionDataEntityDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageRequestDto.java index 6081a32635..6a4f1a2702 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ImageRequestDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @@ -25,5 +24,4 @@ public class ImageRequestDto implements CompositionDataEntityDto { @NotBlank(message = "is mandatory and should not be empty") private String fileName; private String description; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/MonitoringUploadStatusDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/MonitoringUploadStatusDto.java index a8c1c58a71..b2512fa7b9 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/MonitoringUploadStatusDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/MonitoringUploadStatusDto.java @@ -1,27 +1,26 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class MonitoringUploadStatusDto { + private String snmpTrap; private String snmpPoll; private String vesEvent; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkDto.java index b944970d8b..4495d539d2 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class NetworkDto extends NetworkRequestDto implements CompositionDataEntityDto { + private String id; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkRequestDto.java index 28cfbaa06d..f3e6d780dc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NetworkRequestDto.java @@ -1,24 +1,22 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; - import javax.validation.constraints.NotNull; +import lombok.Data; @Data public class NetworkRequestDto { @@ -27,5 +25,4 @@ public class NetworkRequestDto { private String name; @NotNull private boolean dhcp; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicCreationResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicCreationResponseDto.java index 47b57e8175..874e0dc054 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicCreationResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicCreationResponseDto.java @@ -1,24 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class NicCreationResponseDto { + private String nicId; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicDto.java index 025e494ed0..578b2ec62a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class NicDto extends NicRequestDto implements CompositionDataEntityDto { + private String id; private String networkName; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicRequestDto.java index 73246fd7ec..1bef41df40 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/NicRequestDto.java @@ -1,27 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import javax.validation.constraints.NotNull; import lombok.Data; import org.hibernate.validator.constraints.NotBlank; import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.ValidateString; -import javax.validation.constraints.NotNull; - @Data public class NicRequestDto { @@ -30,9 +28,7 @@ public class NicRequestDto { private String description; private String networkId; @NotNull - @ValidateString(acceptedValues = {"External", "Internal"}, message = "doesn't " - + "meet the expected attribute value.", isCaseSensitive = true) + @ValidateString(acceptedValues = {"External", "Internal"}, message = "doesn't " + "meet the expected attribute value.", isCaseSensitive = true) private String networkType; - private String networkDescription; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateAction.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateAction.java index e883913bb1..0478afecc0 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateAction.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateAction.java @@ -1,24 +1,21 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; /** * Created by Talio on 11/13/2016. */ -public enum OrchestrationTemplateAction { - Process -} +public enum OrchestrationTemplateAction {Process} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateActionResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateActionResponseDto.java index 36588e0f51..75683649e3 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateActionResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/OrchestrationTemplateActionResponseDto.java @@ -1,33 +1,32 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import java.util.List; +import java.util.Map; import lombok.Data; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileStatus; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 4/27/2016. */ @Data public class OrchestrationTemplateActionResponseDto { + private List fileNames; private Map> errors; private UploadFileStatus status; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/PackageInfoDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/PackageInfoDto.java index 12c29888ee..5650ac8670 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/PackageInfoDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/PackageInfoDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @@ -36,5 +35,4 @@ public class PackageInfoDto { private String packageChecksum; private String packageType; private String resourceType; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessEntityDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessEntityDto.java index fcea252fb9..642cbb6c46 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessEntityDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessEntityDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class ProcessEntityDto extends ProcessRequestDto { + private String id; private String artifactName; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessRequestDto.java index 3379dee8ca..d57a293ee4 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ProcessRequestDto.java @@ -1,26 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import javax.validation.constraints.NotNull; import lombok.Data; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; -import javax.validation.constraints.NotNull; - @Data public class ProcessRequestDto { @@ -28,5 +26,4 @@ public class ProcessRequestDto { private String name; private String description; private ProcessType type; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireDto.java index 763ff71388..3fe9461bcc 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireDto.java @@ -1,24 +1,22 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; - import java.util.HashMap; +import lombok.Data; /** * Created by ayalaben on 9/26/2017 @@ -32,6 +30,4 @@ public class QuestionnaireDto { public HashMap getQuestionareData() { return questionareData; } - - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireResponseDto.java index 763737f36f..f40091ea12 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireResponseDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @@ -21,8 +20,8 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; @Data public class QuestionnaireResponseDto { + private String schema; private String data; private ErrorMessage errorMessage; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireValidationResultDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireValidationResultDto.java index f431d18a9f..4c98b6e7a8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireValidationResultDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/QuestionnaireValidationResultDto.java @@ -1,28 +1,26 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; - import java.util.Set; +import lombok.Data; @Data public class QuestionnaireValidationResultDto { + private boolean valid; private Set validationData; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/TranslatedFileDataDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/TranslatedFileDataDto.java index 23c4f75d74..ab9dae40f1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/TranslatedFileDataDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/TranslatedFileDataDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @@ -32,5 +31,4 @@ public class TranslatedFileDataDto { private String vendorRelease; private String packageChecksum; private String packageType; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/UploadFileResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/UploadFileResponseDto.java index 7ff8af341d..f45884e21e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/UploadFileResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/UploadFileResponseDto.java @@ -1,36 +1,34 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import java.util.List; +import java.util.Map; import lombok.Data; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileStatus; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 4/27/2016. */ @Data public class UploadFileResponseDto { + private Map> errors; private UploadFileStatus status; private String onboardingOrigin; private String networkPackageName; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ValidationResponseDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ValidationResponseDto.java index 6122e43ec2..4f548736df 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ValidationResponseDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/ValidationResponseDto.java @@ -1,31 +1,30 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; -import org.openecomp.sdcrests.common.types.ErrorCodeDto; -import org.openecomp.sdcrests.common.types.ErrorMessageDto; - import java.util.Collection; import java.util.List; import java.util.Map; +import lombok.Data; +import org.openecomp.sdcrests.common.types.ErrorCodeDto; +import org.openecomp.sdcrests.common.types.ErrorMessageDto; @Data public class ValidationResponseDto { + private boolean valid; private Collection vspErrors; private Collection licensingDataErrors; @@ -33,5 +32,4 @@ public class ValidationResponseDto { private QuestionnaireValidationResultDto questionnaireValidationResult; private ComponentValidationResultDto componentValidationResult; private DeploymentFlavorValidationResultDto deploymentFlavorValidationResult; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VendorSoftwareProductAction.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VendorSoftwareProductAction.java index eec79aab81..afe1d76309 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VendorSoftwareProductAction.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VendorSoftwareProductAction.java @@ -1,22 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -public enum VendorSoftwareProductAction { - Submit, - Create_Package -} +public enum VendorSoftwareProductAction {Submit, Create_Package} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VersionSoftwareProductActionRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VersionSoftwareProductActionRequestDto.java index 6c5b26ec5a..76f1f9313e 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VersionSoftwareProductActionRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VersionSoftwareProductActionRequestDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @@ -24,7 +23,7 @@ import org.openecomp.sdcrests.item.types.SubmitRequestDto; */ @Data public class VersionSoftwareProductActionRequestDto { + private VendorSoftwareProductAction action; private SubmitRequestDto submitRequest; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VmSizing.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VmSizing.java index a4d923d369..5001828db8 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VmSizing.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VmSizing.java @@ -1,29 +1,28 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; -import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.ValidateString; - import javax.validation.constraints.Max; import javax.validation.constraints.Min; +import lombok.Data; +import org.openecomp.sdcrests.vendorsoftwareproducts.types.validation.ValidateString; @Data public class VmSizing { + @Min(value = 1, message = "should be integer and > 0") @Max(value = 16, message = "should be integer and <= 16") private int numOfCPUs; @@ -33,11 +32,8 @@ public class VmSizing { private int persistentStorageVolumeSize; @Min(value = 1, message = "should be integer and > 0") private int ioOperationsPerSec; - @ValidateString(acceptedValues = {"1:1", "4:1", "16:1"}, message = "doesn't meet the expected " - + "attribute value.") + @ValidateString(acceptedValues = {"1:1", "4:1", "16:1"}, message = "doesn't meet the expected " + "attribute value.") private String cpuOverSubscriptionRatio; - @ValidateString(acceptedValues = {"1", "2", "4", "8"}, message = "doesn't meet the expected " - + "attribute value.") + @ValidateString(acceptedValues = {"1", "2", "4", "8"}, message = "doesn't meet the expected " + "attribute value.") private String memoryRAM; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspComputeDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspComputeDto.java index 467f5e9329..0c8fb1938a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspComputeDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspComputeDto.java @@ -1,25 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import lombok.Data; @Data public class VspComputeDto { + private String name; private String componentId; private String computeFlavorId; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDescriptionDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDescriptionDto.java index 3cddb5d4e3..010e0d3818 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDescriptionDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDescriptionDto.java @@ -1,29 +1,28 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; +import javax.validation.constraints.NotNull; import lombok.Data; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.LicenseType; import org.openecomp.sdc.vendorsoftwareproduct.types.LicensingData; -import javax.validation.constraints.NotNull; - @Data public class VspDescriptionDto { + @NotNull private String name; @NotNull @@ -37,6 +36,7 @@ public class VspDescriptionDto { private String vendorName; @NotNull private String vendorId; // this will be populated with vlm id + private String licensingVersion; // this will be populated with vlm version private LicenseType licenseType; private LicensingData licensingData; diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDetailsDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDetailsDto.java index fbc51a414b..2acc27e95a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDetailsDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspDetailsDto.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; import io.swagger.v3.oas.annotations.media.Schema; @@ -23,17 +22,16 @@ import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; /** * Created by TALIO on 4/25/2016. */ - @Data @Schema(description = "VspDetails") public class VspDetailsDto extends VspRequestDto { - private String id; - private String version; - private ValidationStructureList validationData; - private String candidateOnboardingOrigin; - private String onboardingOrigin; - private String networkPackageName; - private String owner; - private String status; + private String id; + private String version; + private ValidationStructureList validationData; + private String candidateOnboardingOrigin; + private String onboardingOrigin; + private String networkPackageName; + private String owner; + private String status; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspRequestDto.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspRequestDto.java index 59b565a669..13e21ba760 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspRequestDto.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/VspRequestDto.java @@ -1,28 +1,26 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdcrests.vendorsoftwareproducts.types; -import lombok.Data; - import javax.validation.constraints.NotNull; +import lombok.Data; @Data public class VspRequestDto extends VspDescriptionDto { + @NotNull private String onboardingMethod; - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/CustomJsonValidator.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/CustomJsonValidator.java index 9e0b08bd0d..aa17db257c 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/CustomJsonValidator.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/CustomJsonValidator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorsoftwareproducts.types.validation; -import org.openecomp.core.utilities.json.JsonUtil; - import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; - +import org.openecomp.core.utilities.json.JsonUtil; public class CustomJsonValidator implements ConstraintValidator { - @Override - public void initialize(IsValidJson stringEnumeration) { - } - - - @Override - public boolean isValid(String json, ConstraintValidatorContext context) { - return JsonUtil.isValidJson(json); - } + @Override + public void initialize(IsValidJson stringEnumeration) { + } + @Override + public boolean isValid(String json, ConstraintValidatorContext context) { + return JsonUtil.isValidJson(json); + } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/IsValidJson.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/IsValidJson.java index 27c6d65ba5..e775802b9d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/IsValidJson.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/IsValidJson.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorsoftwareproducts.types.validation; - /** * @since July 13, 2016 */ -import org.openecomp.sdcrests.common.RestConstants; +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; -import javax.validation.Constraint; -import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import javax.validation.Constraint; +import javax.validation.Payload; +import org.openecomp.sdcrests.common.RestConstants; /** * The interface Is valid json. @@ -43,31 +44,30 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, CONSTRUCTOR}) @Retention(RUNTIME) public @interface IsValidJson { - /** - * The constant message. - */ - String message = RestConstants.INVALID_JSON_ERROR_MESSAGE; - /** - * Message string. - * - * @return the string - */ - String message() default RestConstants.INVALID_JSON_ERROR_MESSAGE; + /** + * The constant message. + */ + String message = RestConstants.INVALID_JSON_ERROR_MESSAGE; - /** - * Groups class [ ]. - * - * @return the class [ ] - */ - Class[] groups() default {}; - - /** - * Payload class [ ]. - * - * @return the class [ ] - */ - Class[] payload() default {}; -} + /** + * Message string. + * + * @return the string + */ + String message() default RestConstants.INVALID_JSON_ERROR_MESSAGE; + /** + * Groups class [ ]. + * + * @return the class [ ] + */ + Class[] groups() default {}; + /** + * Payload class [ ]. + * + * @return the class [ ] + */ + Class[] payload() default {}; +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/StringValidator.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/StringValidator.java index c163fedec5..919f5df4c1 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/StringValidator.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/StringValidator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,40 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdcrests.vendorsoftwareproducts.types.validation; -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; import java.util.ArrayList; import java.util.List; +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; public class StringValidator implements ConstraintValidator { - private List valueList; - boolean isCaseSensitive; + boolean isCaseSensitive; + private List valueList; - @Override - public void initialize(ValidateString constraintAnnotation) { - valueList = new ArrayList(); - isCaseSensitive = constraintAnnotation.isCaseSensitive(); - for (String val : constraintAnnotation.acceptedValues()) { - if (!isCaseSensitive) { - val = val.toUpperCase(); - } - valueList.add(val); + @Override + public void initialize(ValidateString constraintAnnotation) { + valueList = new ArrayList(); + isCaseSensitive = constraintAnnotation.isCaseSensitive(); + for (String val : constraintAnnotation.acceptedValues()) { + if (!isCaseSensitive) { + val = val.toUpperCase(); + } + valueList.add(val); + } } - } - @Override - public boolean isValid(String value, ConstraintValidatorContext context) { - if (!isCaseSensitive) { - value = value.toUpperCase(); - } - if (value != null && !valueList.contains(value)) { - return false; + @Override + public boolean isValid(String value, ConstraintValidatorContext context) { + if (!isCaseSensitive) { + value = value.toUpperCase(); + } + if (value != null && !valueList.contains(value)) { + return false; + } + return true; } - return true; - } - } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/ValidateString.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/ValidateString.java index 4073463eaf..533fc6897a 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/ValidateString.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-types/src/main/java/org/openecomp/sdcrests/vendorsoftwareproducts/types/validation/ValidateString.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,14 +20,18 @@ package org.openecomp.sdcrests.vendorsoftwareproducts.types.validation; -import javax.validation.Constraint; -import javax.validation.Payload; +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; - -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.RUNTIME; +import javax.validation.Constraint; +import javax.validation.Payload; /** * The interface Validate string. @@ -37,24 +41,25 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, CONSTRUCTOR}) @Retention(RUNTIME) public @interface ValidateString { - /** - * The constant message. - */ - String message = ""; - /** - * Accepted values string [ ]. - * - * @return the string [ ] - */ - String[] acceptedValues(); + /** + * The constant message. + */ + String message = ""; + + /** + * Accepted values string [ ]. + * + * @return the string [ ] + */ + String[] acceptedValues(); - String message() default "{org.openecomp.sdcrests.vendorsoftwareproducts.types.validation" - + ".message}"; + String message() default "{org.openecomp.sdcrests.vendorsoftwareproducts.types.validation" + + ".message}"; - boolean isCaseSensitive() default false; + boolean isCaseSensitive() default false; - Class[] groups() default {}; + Class[] groups() default {}; - Class[] payload() default {}; + Class[] payload() default {}; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VnfPackageRepository.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VnfPackageRepository.java index 9617c61836..1412c332cb 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VnfPackageRepository.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/VnfPackageRepository.java @@ -13,12 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest; import static org.openecomp.sdcrests.common.RestConstants.USER_ID_HEADER_PARAM; import static org.openecomp.sdcrests.common.RestConstants.USER_MISSING_ERROR_MSG; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.tags.Tags; import java.io.File; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; @@ -30,15 +36,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.Parameter; -import io.swagger.v3.oas.annotations.info.Info; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; -import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.tags.Tags; import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; import org.springframework.validation.annotation.Validated; @@ -52,31 +49,23 @@ public interface VnfPackageRepository extends VspEntities { @GET @Path("/vnfpackages") @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Get VNF packages from VNF Repository", - summary = "Call VNF Repository to get VNF package details", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) - Response getVnfPackages(@PathParam("vspId") String vspId, - @Parameter(description= "Version Id") @PathParam("versionId") String versionId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; + @Operation(description = "Get VNF packages from VNF Repository", summary = "Call VNF Repository to get VNF package details", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response getVnfPackages(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; @GET @Path("/vnfpackage/{csarId}/download") @Produces(MediaType.APPLICATION_OCTET_STREAM) - @Operation(description = "Download VNF package from VNF Repository", - summary = "Download VNF package from VNF repository and send to client", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) - Response downloadVnfPackage(@PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @PathParam("csarId") String csarId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; + @Operation(description = "Download VNF package from VNF Repository", summary = "Download VNF package from VNF repository and send to client", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = File.class)))) + Response downloadVnfPackage(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @PathParam("csarId") String csarId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; @POST @Path("/vnfpackage/{csarId}/import") @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Import VNF package from VNF Repository", - summary = "Call VNF Repository to download VNF package, validate it and send the response", - responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UploadFileResponseDto.class)))) - Response importVnfPackage(@PathParam("vspId") String vspId, - @Parameter(description = "Version Id") @PathParam("versionId") String versionId, - @PathParam("csarId") String csarId, - @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; - + @Operation(description = "Import VNF package from VNF Repository", summary = "Call VNF Repository to download VNF package, validate it and send the response", responses = @ApiResponse(content = @Content(schema = @Schema(implementation = UploadFileResponseDto.class)))) + Response importVnfPackage(@PathParam("vspId") String vspId, @Parameter(description = "Version Id") @PathParam("versionId") String versionId, + @PathParam("csarId") String csarId, + @NotNull(message = USER_MISSING_ERROR_MSG) @HeaderParam(USER_ID_HEADER_PARAM) String user) throws Exception; } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java index 9ee86889f5..88ee6fa43d 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java @@ -14,9 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdcrests.vsp.rest.services; +import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; +import static org.openecomp.core.utilities.file.FileUtils.getFileExtension; +import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName; + import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; @@ -54,10 +57,6 @@ import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFile import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; -import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; -import static org.openecomp.core.utilities.file.FileUtils.getFileExtension; -import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName; - /** * Enables integration API interface with VNF Repository (VNFSDK). *
    @@ -80,20 +79,23 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[]{new X509TrustManager() { - public void checkClientTrusted(X509Certificate[] c, String s) {} - public void checkServerTrusted(X509Certificate[] c, String s) {} - public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } - }}, new java.security.SecureRandom()); + public void checkClientTrusted(X509Certificate[] c, String s) { + } + + public void checkServerTrusted(X509Certificate[] c, String s) { + } - return ClientBuilder.newBuilder() - .sslContext(sslcontext) - .hostnameVerifier((a, b) -> true) - .build(); + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + }}, new java.security.SecureRandom()); + return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((a, b) -> true).build(); } catch (NoSuchAlgorithmException | KeyManagementException e) { LOGGER.error("Failed to initialize SSL unsecure context", e); } return ClientBuilder.newClient(); } + private final Configuration config; public VnfPackageRepositoryImpl(Configuration config) { @@ -120,35 +122,28 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { public Response importVnfPackage(String vspId, String versionId, String csarId, String user) { LOGGER.debug("Import VNF Packages from Repository: {}", csarId); final String downloadPackageUri = String.format(config.getDownloadUri(), csarId); - Response remoteResponse = CLIENT.target(downloadPackageUri).request().get(); if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) { return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse); } - LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri); byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1); return uploadVnfPackage(vspId, versionId, csarId, payload); } - private Response uploadVnfPackage(final String vspId, final String versionId, - final String csarId, final byte[] payload) { + private Response uploadVnfPackage(final String vspId, final String versionId, final String csarId, final byte[] payload) { try { - final OrchestrationTemplateCandidateManager candidateManager = - OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface(); + final OrchestrationTemplateCandidateManager candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance() + .createInterface(); final String filename = formatFilename(csarId); final String fileExtension = getFileExtension(filename); - final OnboardPackageInfo onboardPackageInfo = - new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension, ByteBuffer.wrap(payload), - OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension)); + final OnboardPackageInfo onboardPackageInfo = new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension, + ByteBuffer.wrap(payload), OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension)); final VspDetails vspDetails = new VspDetails(vspId, getVersion(vspId, versionId)); final UploadFileResponse response = candidateManager.upload(vspDetails, onboardPackageInfo); - final UploadFileResponseDto uploadFileResponse = - new MapUploadFileResponseToUploadFileResponseDto() - .applyMapping(response, UploadFileResponseDto.class); - + final UploadFileResponseDto uploadFileResponse = new MapUploadFileResponseToUploadFileResponseDto() + .applyMapping(response, UploadFileResponseDto.class); return Response.ok(uploadFileResponse).build(); - } catch (final Exception e) { ErrorCode error = new GeneralErrorBuilder().build(); LOGGER.error("Exception while uploading package received from VNF Repository", new CoreException(error, e)); @@ -160,16 +155,13 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { public Response downloadVnfPackage(String vspId, String versionId, String csarId, String user) { LOGGER.debug("Download VNF package from repository: csarId={}", csarId); final String downloadPackageUri = String.format(config.getDownloadUri(), csarId); - Response remoteResponse = CLIENT.target(downloadPackageUri).request().get(); if (remoteResponse.getStatus() != Response.Status.OK.getStatusCode()) { return handleUnexpectedStatus("downloading VNF package", downloadPackageUri, remoteResponse); } - byte[] payload = remoteResponse.readEntity(String.class).getBytes(StandardCharsets.ISO_8859_1); Response.ResponseBuilder response = Response.ok(payload); response.header(CONTENT_DISPOSITION, "attachment; filename=" + formatFilename(csarId)); - LOGGER.debug("Response from VNF Repository for download package is success. URI={}", downloadPackageUri); return response.build(); } @@ -184,15 +176,12 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { } private static Response handleUnexpectedStatus(String action, String uri, Response response) { - ErrorCode error = new GeneralErrorBuilder().build(); - if (LOGGER.isErrorEnabled()) { String body = response.hasEntity() ? response.readEntity(String.class) : ""; - LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri, - response.getStatus(), body, new CoreException(error)); + LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri, response.getStatus(), body, + new CoreException(error)); } - return generateInternalServerError(error); } @@ -206,7 +195,9 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { } interface Configuration { + String getGetUri(); + String getDownloadUri(); } @@ -225,16 +216,12 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { private static class LazyFileConfiguration implements Configuration { private static final String CONFIG_NAMESPACE = "vnfrepo"; - private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_PORT = "8702"; - private static final String DEFAULT_URI_PREFIX = "/onapapi/vnfsdk-marketplace/v1/PackageResource/csars"; private static final String DEFAULT_LIST_URI = DEFAULT_URI_PREFIX + "/"; private static final String DEFAULT_DOWNLOAD_URI = DEFAULT_URI_PREFIX + "/%s/files"; - private static final LazyFileConfiguration INSTANCE = new LazyFileConfiguration(); - private final String getUri; private final String downloadUri; @@ -253,8 +240,7 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { String value = config.getAsString(CONFIG_NAMESPACE, key); return (value == null) ? defaultValue : value; } catch (Exception e) { - LOGGER.error("Failed to read VNF repository configuration key '{}', default value '{}' will be used", - key, defaultValue, e); + LOGGER.error("Failed to read VNF repository configuration key '{}', default value '{}' will be used", key, defaultValue, e); return defaultValue; } } diff --git a/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/ActionManager.java b/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/ActionManager.java index e5a1b6da43..4d4b02c787 100644 --- a/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/ActionManager.java +++ b/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/ActionManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,50 +17,45 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.action; - +import java.util.List; import org.openecomp.sdc.action.types.Action; import org.openecomp.sdc.action.types.ActionArtifact; import org.openecomp.sdc.action.types.OpenEcompComponent; -import java.util.List; - /** * Created by uttamp on 7/1/2016. */ - public interface ActionManager { - public Action createAction(Action action, String user); - public Action updateAction(Action action, String user); + public Action createAction(Action action, String user); - public void deleteAction(String actionInvariantUuId, String user); + public Action updateAction(Action action, String user); - public List getFilteredActions(String filterType, String filterValue); + public void deleteAction(String actionInvariantUuId, String user); - public List getOpenEcompComponents(); + public List getFilteredActions(String filterType, String filterValue); - public List getActionsByActionInvariantUuId(String invariantId); + public List getOpenEcompComponents(); - public Action getActionsByActionUuId(String actionUuId); + public List getActionsByActionInvariantUuId(String invariantId); - public Action checkout(String invariantUuId, String user); + public Action getActionsByActionUuId(String actionUuId); - public void undoCheckout(String invariantUuId, String user); + public Action checkout(String invariantUuId, String user); - public Action checkin(String invariantUuId, String user); + public void undoCheckout(String invariantUuId, String user); - public Action submit(String invariantUuId, String user); + public Action checkin(String invariantUuId, String user); - public ActionArtifact uploadArtifact(ActionArtifact data, String actionInvariantUuId, - String user); + public Action submit(String invariantUuId, String user); - public ActionArtifact downloadArtifact(String actionUuId, String artifactUuId); + public ActionArtifact uploadArtifact(ActionArtifact data, String actionInvariantUuId, String user); - public void deleteArtifact(String actionInvariantUuId, String artifactUuId, String user); + public ActionArtifact downloadArtifact(String actionUuId, String artifactUuId); - public void updateArtifact(ActionArtifact data, String actionInvariantUuId, String user); -} + public void deleteArtifact(String actionInvariantUuId, String artifactUuId, String user); + public void updateArtifact(ActionArtifact data, String actionInvariantUuId, String user); +} diff --git a/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/impl/ActionManagerImpl.java b/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/impl/ActionManagerImpl.java index bc7a6f4f64..2cc42a85d3 100644 --- a/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/impl/ActionManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-action-manager/src/main/java/org/openecomp/sdc/action/impl/ActionManagerImpl.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.action.impl; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR; import static org.openecomp.sdc.action.ActionConstants.ACTION_VERSIONABLE_TYPE; import static org.openecomp.sdc.action.ActionConstants.ARTIFACT_METADATA_ATTR_NAME; import static org.openecomp.sdc.action.ActionConstants.ARTIFACT_METADATA_ATTR_UUID; @@ -63,6 +64,7 @@ import static org.openecomp.sdc.action.util.ActionUtil.actionLogPostProcessor; import static org.openecomp.sdc.action.util.ActionUtil.actionLogPreProcessor; import static org.openecomp.sdc.action.util.ActionUtil.getCurrentTimeStampUtc; import static org.openecomp.sdc.versioning.dao.types.Version.VERSION_STRING_VIOLATION_MSG; + import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -88,7 +90,12 @@ import org.openecomp.sdc.action.dao.types.ActionArtifactEntity; import org.openecomp.sdc.action.dao.types.ActionEntity; import org.openecomp.sdc.action.errors.ActionErrorConstants; import org.openecomp.sdc.action.errors.ActionException; -import org.openecomp.sdc.action.types.*; +import org.openecomp.sdc.action.types.Action; +import org.openecomp.sdc.action.types.ActionArtifact; +import org.openecomp.sdc.action.types.ActionArtifactProtection; +import org.openecomp.sdc.action.types.ActionStatus; +import org.openecomp.sdc.action.types.ActionSubOperation; +import org.openecomp.sdc.action.types.OpenEcompComponent; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -105,20 +112,10 @@ import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.slf4j.MDC; -import java.util.*; - -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR; -import static org.openecomp.sdc.action.ActionConstants.*; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.*; -import static org.openecomp.sdc.action.util.ActionUtil.*; -import static org.openecomp.sdc.versioning.dao.types.Version.VERSION_STRING_VIOLATION_MSG; - /** * Manager Implementation for {@link ActionManager Action Library Operations} *
    - * Handles Business layer validations and acts as an interface between the REST - * and DAO layers. + * Handles Business layer validations and acts as an interface between the REST and DAO layers. */ public class ActionManagerImpl implements ActionManager { @@ -131,94 +128,82 @@ public class ActionManagerImpl implements ActionManager { private final ActionArtifactDao actionArtifactDao; private final VersionInfoDao versionInfoDao; private final UniqueValueDao uniqueValueDao; + private final Logger log = LoggerFactory.getLogger(this.getClass().getName()); + + public ActionManagerImpl() { + actionDao = ActionDaoFactory.getInstance().createInterface(); + versioningManager = ActionVersioningManagerFactory.getInstance().createInterface(); + actionArtifactDao = ActionArtifactDaoFactory.getInstance().createInterface(); + versionInfoDao = VersionInfoDaoFactory.getInstance().createInterface(); + actionDao.registerVersioning(ACTION_VERSIONABLE_TYPE); + uniqueValueDao = UniqueValueDaoFactory.getInstance().createInterface(); + } - private final Logger log = LoggerFactory.getLogger(this.getClass() - .getName()); - - public ActionManagerImpl() { - actionDao = ActionDaoFactory.getInstance().createInterface(); - versioningManager = ActionVersioningManagerFactory.getInstance().createInterface(); - actionArtifactDao = ActionArtifactDaoFactory.getInstance().createInterface(); - versionInfoDao = VersionInfoDaoFactory.getInstance().createInterface(); - actionDao.registerVersioning(ACTION_VERSIONABLE_TYPE); - uniqueValueDao = UniqueValueDaoFactory.getInstance().createInterface(); - } - - public ActionManagerImpl(ActionDao actionDao, ActionVersioningManager versioningManager, - ActionArtifactDao actionArtifactDao, VersionInfoDao versionInfoDao, - UniqueValueDao uniqueValueDao) { - this.actionDao = actionDao; - this.versioningManager = versioningManager; - this.actionArtifactDao = actionArtifactDao; - this.versionInfoDao = versionInfoDao; - this.uniqueValueDao = uniqueValueDao; - } - /** - * List All Major, Last Minor and Candidate version (if any) for Given Action Invariant UUID - * - * @param invariantId Invariant UUID of the action for which the information is required - * @return List of All Major, Last Minor and Candidate version if any Of {@link Action} with given - * actionInvariantUuId. - * @throws ActionException Exception with an action library specific code, short description and - * detailed message for the error occurred during the operation - */ + public ActionManagerImpl(ActionDao actionDao, ActionVersioningManager versioningManager, ActionArtifactDao actionArtifactDao, + VersionInfoDao versionInfoDao, UniqueValueDao uniqueValueDao) { + this.actionDao = actionDao; + this.versioningManager = versioningManager; + this.actionArtifactDao = actionArtifactDao; + this.versionInfoDao = versionInfoDao; + this.uniqueValueDao = uniqueValueDao; + } + /** + * List All Major, Last Minor and Candidate version (if any) for Given Action Invariant UUID + * + * @param invariantId Invariant UUID of the action for which the information is required + * @return List of All Major, Last Minor and Candidate version if any Of {@link Action} with given actionInvariantUuId. + * @throws ActionException Exception with an action library specific code, short description and detailed message for the error occurred during + * the operation + */ @Override public List getActionsByActionInvariantUuId(String invariantId) { List actions; - log.debug(" entering getActionsByActionInvariantUuId with invariantID = " + invariantId); actions = actionDao.getActionsByActionInvariantUuId(invariantId != null ? invariantId.toUpperCase() : null); - if (actions != null && actions.isEmpty()) { throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); } - log.debug(" exit getActionsByActionInvariantUuId with invariantID = " + invariantId); return actions; } /** - * Get list of actions based on a filter criteria. If no filter is sent all - * actions will be returned + * Get list of actions based on a filter criteria. If no filter is sent all actions will be returned * - * @param filterType - * Filter by Vendor/Category/Model/Component/None - * @param filterValue - * Filter Parameter Value (Vendor ID/Category ID/Model - * ID/Component ID) - * @return List of {@link Action} objects based on a filter criteria
    - * Empty List if no records match the provided filter criteria + * @param filterType Filter by Vendor/Category/Model/Component/None + * @param filterValue Filter Parameter Value (Vendor ID/Category ID/Model ID/Component ID) + * @return List of {@link Action} objects based on a filter criteria
    Empty List if no records match the provided filter criteria */ @Override public List getFilteredActions(String filterType, String filterValue) { List actions; log.debug(" entering getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue); switch (filterType) { - case FILTER_TYPE_NONE: - // Business validation for OPENECOMP Component type fetch (if any) - break; - case FILTER_TYPE_VENDOR: - // Business validation for vendor type fetch (if any) - break; - case FILTER_TYPE_CATEGORY: - // Business validation for Category type fetch (if any) - break; - case FILTER_TYPE_MODEL: - // Business validation for model type fetch (if any) - break; - case FILTER_TYPE_OPEN_ECOMP_COMPONENT: - // Business validation for OPENECOMP Component type fetch (if any) - break; - case FILTER_TYPE_NAME: - actions = actionDao.getFilteredActions(filterType, filterValue != null ? filterValue.toLowerCase() : null); - if (actions != null && actions.isEmpty()) { - throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); - } - log.debug(" exit getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue); - return actions; - default: - break; + case FILTER_TYPE_NONE: + // Business validation for OPENECOMP Component type fetch (if any) + break; + case FILTER_TYPE_VENDOR: + // Business validation for vendor type fetch (if any) + break; + case FILTER_TYPE_CATEGORY: + // Business validation for Category type fetch (if any) + break; + case FILTER_TYPE_MODEL: + // Business validation for model type fetch (if any) + break; + case FILTER_TYPE_OPEN_ECOMP_COMPONENT: + // Business validation for OPENECOMP Component type fetch (if any) + break; + case FILTER_TYPE_NAME: + actions = actionDao.getFilteredActions(filterType, filterValue != null ? filterValue.toLowerCase() : null); + if (actions != null && actions.isEmpty()) { + throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); + } + log.debug(" exit getFilteredActions By filterType = " + filterType + WITH_VALUE + filterValue); + return actions; + default: + break; } actions = actionDao.getFilteredActions(filterType, filterValue != null ? filterValue.toLowerCase() : null); List majorMinorVersionList = getMajorMinorVersionActions(actions); @@ -230,20 +215,16 @@ public class ActionManagerImpl implements ActionManager { /** * Get the properties of an action version by its UUID. * - * @param actionUuId - * UUID of the specific action version - * @return {@link Action} object corresponding the version represented by - * the UUID + * @param actionUuId UUID of the specific action version + * @return {@link Action} object corresponding the version represented by the UUID */ @Override public Action getActionsByActionUuId(String actionUuId) { log.debug(" entering getActionsByActionUuId with actionUUID = " + actionUuId); Action action = actionDao.getActionsByActionUuId(actionUuId != null ? actionUuId.toUpperCase() : null); - if (action == null) { throw new ActionException(ACTION_ENTITY_NOT_EXIST_CODE, ACTION_ENTITY_NOT_EXIST); } - log.debug(" exit getActionsByActionUuId with actionUUID = " + actionUuId); return action; } @@ -251,9 +232,7 @@ public class ActionManagerImpl implements ActionManager { /** * List OPENECOMP Components supported by Action Library. * - * @return List of {@link OpenEcompComponent} objects supported by Action - * Library
    - * Empty List if no components are found + * @return List of {@link OpenEcompComponent} objects supported by Action Library
    Empty List if no components are found */ @Override public List getOpenEcompComponents() { @@ -263,16 +242,13 @@ public class ActionManagerImpl implements ActionManager { /** * Delete an action. * - * @param actionInvariantUuId - * Invariant UUID of the action to be deleted - * @param user - * User id of the user performing the operation + * @param actionInvariantUuId Invariant UUID of the action to be deleted + * @param user User id of the user performing the operation */ @Override public void deleteAction(String actionInvariantUuId, String user) { try { - log.debug( - "entering deleteAction with actionInvariantUuId = " + actionInvariantUuId + " and user = " + user); + log.debug("entering deleteAction with actionInvariantUuId = " + actionInvariantUuId + " and user = " + user); actionLogPreProcessor(ActionSubOperation.DELETE_ACTION, TARGET_ENTITY_API); versioningManager.delete(ACTION_VERSIONABLE_TYPE, actionInvariantUuId, user); actionLogPostProcessor(COMPLETE); @@ -286,10 +262,8 @@ public class ActionManagerImpl implements ActionManager { /** * Create a new Action. * - * @param action - * Action object model of the user request for creating an action - * @param user - * AT&T id of the user sending the create request + * @param action Action object model of the user request for creating an action + * @param user AT&T id of the user sending the create request * @return {@link Action} model object for the created action */ @Override @@ -300,8 +274,7 @@ public class ActionManagerImpl implements ActionManager { uniqueValueUtil.validateUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName()); actionLogPostProcessor(COMPLETE); } catch (CoreException exception) { - String errorDesc = String.format(ACTION_ENTITY_UNIQUE_VALUE_MSG, ActionConstants.UniqueValues.ACTION_NAME, - action.getName()); + String errorDesc = String.format(ACTION_ENTITY_UNIQUE_VALUE_MSG, ActionConstants.UniqueValues.ACTION_NAME, action.getName()); log.error(errorDesc, exception); actionLogPostProcessor(ERROR, ACTION_ENTITY_UNIQUE_VALUE_ERROR, errorDesc, false); throw new ActionException(ACTION_ENTITY_UNIQUE_VALUE_ERROR, errorDesc); @@ -312,55 +285,47 @@ public class ActionManagerImpl implements ActionManager { action.setTimestamp(getCurrentTimeStampUtc()); action.setActionInvariantUuId(CommonMethods.nextUuId()); action.setActionUuId(CommonMethods.nextUuId()); - actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_VERSION, TARGET_ENTITY_API); Version version = versioningManager.create(ACTION_VERSIONABLE_TYPE, action.getActionInvariantUuId(), user); actionLogPostProcessor(COMPLETE); log.metrics(""); - action.setVersion(version.toString()); action.setStatus(ActionStatus.Locked); action = updateData(action); action = actionDao.createAction(action); - actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_UNIQUE_VALUE, TARGET_ENTITY_API); uniqueValueUtil.createUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName()); actionLogPostProcessor(COMPLETE); log.metrics(""); - return action; } /** * Update an existing action. * - * @param action - * Action object model of the user request for creating an action - * @param user - * AT&T id of the user sending the update request + * @param action Action object model of the user request for creating an action + * @param user AT&T id of the user sending the update request * @return {@link Action} model object for the update action */ @Override public Action updateAction(Action action, String user) { try { - log.debug("entering updateAction to update action with invariantUuId = " + action.getActionInvariantUuId() - + BY_USER + user); + log.debug("entering updateAction to update action with invariantUuId = " + action.getActionInvariantUuId() + BY_USER + user); String invariantUuId = action.getActionInvariantUuId(); actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_API); - VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, invariantUuId, - user, VersionableEntityAction.Write); + VersionInfo versionInfo = versioningManager + .getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, invariantUuId, user, VersionableEntityAction.Write); actionLogPostProcessor(COMPLETE); log.metrics(""); - Version activeVersion = versionInfo.getActiveVersion(); validateActions(action, activeVersion); action.setStatus(ActionStatus.Locked); // Status will be Checkout - // for update + + // for update updateData(action); action.setUser(user); action.setTimestamp(getCurrentTimeStampUtc()); actionDao.updateAction(action); - } catch (CoreException ce) { formAndThrowException(ce); } @@ -371,10 +336,8 @@ public class ActionManagerImpl implements ActionManager { /** * Checkout an existing action. * - * @param invariantUuId - * actionInvariantUuId of the action to be checked out - * @param user - * AT&T id of the user sending the checkout request + * @param invariantUuId actionInvariantUuId of the action to be checked out + * @param user AT&T id of the user sending the checkout request * @return {@link Action} model object for the checkout action */ @Override @@ -387,21 +350,15 @@ public class ActionManagerImpl implements ActionManager { version = versioningManager.checkout(ACTION_VERSIONABLE_TYPE, invariantUuId, user); actionLogPostProcessor(COMPLETE); log.metrics(""); - actionEntity = updateUniqueIdForVersion(invariantUuId, version, ActionStatus.Locked.name(), user); } catch (CoreException exception) { - if (exception.code() != null && exception.code() - .id() - .equals(VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY)) { + if (exception.code() != null && exception.code().id().equals(VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY)) { actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB); - VersionInfoEntity versionInfoEntity = versionInfoDao - .get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId)); + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId)); actionLogPostProcessor(COMPLETE); log.metrics(""); - String checkoutUser = versionInfoEntity.getCandidate() - .getUser(); - log.debug("Actual checkout user for Action with invariantUUID= " + invariantUuId + " is = " - + checkoutUser); + String checkoutUser = versionInfoEntity.getCandidate().getUser(); + log.debug("Actual checkout user for Action with invariantUUID= " + invariantUuId + " is = " + checkoutUser); if (!checkoutUser.equals(user)) { throw new ActionException(ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER, exception.getMessage()); } @@ -415,21 +372,17 @@ public class ActionManagerImpl implements ActionManager { /** * Undo an already checked out action. * - * @param invariantUuId - * actionInvariantUuId of the checked out action - * @param user - * AT&T id of the user sending the request + * @param invariantUuId actionInvariantUuId of the checked out action + * @param user AT&T id of the user sending the request */ @Override public void undoCheckout(String invariantUuId, String user) { Version version; try { log.debug("entering undoCheckout for Action with invariantUUID= " + invariantUuId + BY_USER + user); - actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB); // Get list of uploaded artifacts in this checked out version - VersionInfoEntity versionInfoEntity = versionInfoDao - .get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId)); + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId)); actionLogPostProcessor(COMPLETE); log.metrics(""); if (versionInfoEntity == null) { @@ -442,41 +395,35 @@ public class ActionManagerImpl implements ActionManager { } else { activeVersion = versionInfoEntity.getActiveVersion(); } - actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VERSION, TARGET_ENTITY_DB); - Action action = actionDao.get(new ActionEntity(invariantUuId, activeVersion)) - .toDto(); + Action action = actionDao.get(new ActionEntity(invariantUuId, activeVersion)).toDto(); actionLogPostProcessor(COMPLETE); log.metrics(""); - // Perform undo checkout on the action actionLogPreProcessor(ActionSubOperation.UNDO_CHECKOUT_ACTION, TARGET_ENTITY_API); version = versioningManager.undoCheckout(ACTION_VERSIONABLE_TYPE, invariantUuId, user); actionLogPostProcessor(COMPLETE); log.metrics(""); - if (version.equals(new Version(0, 0))) { actionLogPreProcessor(ActionSubOperation.DELETE_UNIQUEVALUE, TARGET_ENTITY_API); UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); uniqueValueUtil.deleteUniqueValue(ActionConstants.UniqueValues.ACTION_NAME, action.getName()); actionLogPostProcessor(COMPLETE); log.metrics(""); - actionLogPreProcessor(ActionSubOperation.DELETE_ACTIONVERSION, TARGET_ENTITY_DB); // Added for the case where Create->Undo_Checkout->Checkout + // should not get the action versionInfoDao.delete(new VersionInfoEntity(ACTION_VERSIONABLE_TYPE, invariantUuId)); actionLogPostProcessor(COMPLETE); log.metrics(""); } - List currentVersionArtifacts = action.getArtifacts(); - // Delete the artifacts from action_artifact table (if any) if (CollectionUtils.isNotEmpty(currentVersionArtifacts) && currentVersionArtifacts.size() > 0) { for (ActionArtifact artifact : currentVersionArtifacts) { ActionArtifactEntity artifactDeleteEntity = new ActionArtifactEntity(artifact.getArtifactUuId(), - getEffectiveVersion(activeVersion.toString())); + getEffectiveVersion(activeVersion.toString())); actionLogPreProcessor(ActionSubOperation.DELETE_ARTIFACT, TARGET_ENTITY_DB); actionArtifactDao.delete(artifactDeleteEntity); actionLogPostProcessor(COMPLETE); @@ -492,10 +439,8 @@ public class ActionManagerImpl implements ActionManager { /** * Checkin a checked out action. * - * @param invariantUuId - * actionInvariantUuId of the checked out action - * @param user - * AT&T id of the user sending the request + * @param invariantUuId actionInvariantUuId of the checked out action + * @param user AT&T id of the user sending the request * @return {@link Action} model object for the updated action */ @Override @@ -519,10 +464,8 @@ public class ActionManagerImpl implements ActionManager { /** * Submit a checked in action. * - * @param invariantUuId - * actionInvariantUuId of the checked in action - * @param user - * AT&T id of the user sending the request + * @param invariantUuId actionInvariantUuId of the checked in action + * @param user AT&T id of the user sending the request * @return {@link Action} model object for the updated action */ @Override @@ -546,11 +489,8 @@ public class ActionManagerImpl implements ActionManager { /** * Download an artifact of an action. * - * @param artifactUuId - * {@link ActionArtifact} object representing the artifact and - * its metadata - * @param actionUuId - * UUID of the action for which the artifact has to be downloaded + * @param artifactUuId {@link ActionArtifact} object representing the artifact and its metadata + * @param actionUuId UUID of the action for which the artifact has to be downloaded * @return downloaded action artifact object */ @Override @@ -563,20 +503,17 @@ public class ActionManagerImpl implements ActionManager { List artifacts = action.getArtifacts(); String actionVersion = action.getVersion(); int effectiveVersion = getEffectiveVersion(actionVersion); - ActionArtifact artifactMetadata = getArtifactMetadataFromAction(artifacts, ARTIFACT_METADATA_ATTR_UUID, - artifactUuId); + ActionArtifact artifactMetadata = getArtifactMetadataFromAction(artifacts, ARTIFACT_METADATA_ATTR_UUID, artifactUuId); if (artifactMetadata != null) { String artifactName = artifactMetadata.getArtifactName(); actionArtifact = actionArtifactDao.downloadArtifact(effectiveVersion, artifactUuId); actionArtifact.setArtifactName(artifactName); - } else { throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, - ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); + ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); } } else { - throw new ActionException(ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE, - ActionErrorConstants.ACTION_ENTITY_NOT_EXIST); + throw new ActionException(ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE, ActionErrorConstants.ACTION_ENTITY_NOT_EXIST); } log.debug(" exit downloadArtifact with actionUUID= " + actionUuId + " and artifactUUID= " + artifactUuId); return actionArtifact; @@ -585,79 +522,62 @@ public class ActionManagerImpl implements ActionManager { /** * Upload an artifact to an action. * - * @param artifact - * {@link ActionArtifact} object representing the artifact and - * its metadata - * @param actionInvariantUuId - * Invariant UUID of the action to which the artifact has to be - * uploaded - * @param user - * User ID of the user sending the request + * @param artifact {@link ActionArtifact} object representing the artifact and its metadata + * @param actionInvariantUuId Invariant UUID of the action to which the artifact has to be uploaded + * @param user User ID of the user sending the request * @return Uploaded action artifact object */ @Override public ActionArtifact uploadArtifact(ActionArtifact artifact, String actionInvariantUuId, String user) { ActionArtifact uploadArtifactResponse = new ActionArtifact(); try { - log.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= " - + artifact.getArtifactName()); + log.debug("entering uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= " + artifact.getArtifactName()); actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB); - VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, - actionInvariantUuId, user, VersionableEntityAction.Write); + VersionInfo versionInfo = versioningManager + .getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, actionInvariantUuId, user, VersionableEntityAction.Write); actionLogPostProcessor(COMPLETE); log.metrics(""); Version activeVersion = versionInfo.getActiveVersion(); actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB); - Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion)) - .toDto(); + Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion)).toDto(); actionLogPostProcessor(COMPLETE); log.metrics(""); String artifactUuId = generateActionArtifactUuId(action, artifact.getArtifactName()); // Check for Unique document name List actionArtifacts = action.getArtifacts(); - ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts, - ARTIFACT_METADATA_ATTR_NAME, artifact.getArtifactName()); + ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts, ARTIFACT_METADATA_ATTR_NAME, artifact.getArtifactName()); if (artifactMetadata != null) { - throw new ActionException(ACTION_ARTIFACT_ALREADY_EXISTS_CODE, - String.format(ACTION_ARTIFACT_ALREADY_EXISTS, actionInvariantUuId)); + throw new ActionException(ACTION_ARTIFACT_ALREADY_EXISTS_CODE, String.format(ACTION_ARTIFACT_ALREADY_EXISTS, actionInvariantUuId)); } - // Create the artifact artifact.setArtifactUuId(artifactUuId); artifact.setTimestamp(getCurrentTimeStampUtc()); artifact.setEffectiveVersion(getEffectiveVersion(activeVersion.toString())); actionArtifactDao.uploadArtifact(artifact); - // Update the action data field and timestamp addArtifactMetadataInActionData(action, artifact); - // Set the response object uploadArtifactResponse.setArtifactUuId(artifact.getArtifactUuId()); } catch (CoreException ce) { formAndThrowException(ce); } - log.debug("exit uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= " - + artifact.getArtifactName()); + log.debug("exit uploadArtifact with actionInvariantUuId= " + actionInvariantUuId + "artifactName= " + artifact.getArtifactName()); return uploadArtifactResponse; } @Override public void deleteArtifact(String actionInvariantUuId, String artifactUuId, String user) { - log.debug("enter deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId - + " and user = " + user); + log.debug("enter deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId + " and user = " + user); Action action = actionDao.getLockedAction(actionInvariantUuId, user); List actionArtifacts = action.getArtifacts(); - ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts, ARTIFACT_METADATA_ATTR_UUID, - artifactUuId); + ActionArtifact artifactMetadata = getArtifactMetadataFromAction(actionArtifacts, ARTIFACT_METADATA_ATTR_UUID, artifactUuId); if (artifactMetadata == null) { throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, - ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); + ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); } - if (artifactMetadata.getArtifactProtection() - .equals(ActionArtifactProtection.readOnly.name())) { + if (artifactMetadata.getArtifactProtection().equals(ActionArtifactProtection.readOnly.name())) { throw new ActionException(ACTION_ARTIFACT_DELETE_READ_ONLY, ACTION_ARTIFACT_DELETE_READ_ONLY_MSG); } else { - // Update action by removing artifact metadata String jsonData = action.getData(); List artifacts = action.getArtifacts();// action.getArtifacts(); @@ -670,7 +590,6 @@ public class ActionManagerImpl implements ActionManager { it.remove(); } } - Map dataMap = JsonUtil.json2Object(jsonData, LinkedHashMap.class); dataMap.put("artifacts", artifacts); String data = JsonUtil.object2Json(dataMap); @@ -681,66 +600,58 @@ public class ActionManagerImpl implements ActionManager { actionLogPostProcessor(COMPLETE, null, "", false); log.metrics(""); // delete Artifact if it's upload and delete action on same checkout + // version String artifactName = artifactMetadata.getArtifactName(); String generatedArtifactUuId = generateActionArtifactUuId(action, artifactName); if (generatedArtifactUuId.equals(artifactUuId)) { if (artifact != null) { ActionArtifactEntity artifactDeleteEntity = new ActionArtifactEntity(artifact.getArtifactUuId(), - getEffectiveVersion(action.getVersion())); + getEffectiveVersion(action.getVersion())); actionLogPreProcessor(ActionSubOperation.DELETE_ACTION_ARTIFACT, TARGET_ENTITY_DB); actionArtifactDao.delete(artifactDeleteEntity); } actionLogPostProcessor(COMPLETE, null, "", false); log.metrics(""); } - } - log.debug("exit deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId - + " and user = " + user); + log.debug("exit deleteArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifactUuId + " and user = " + user); } /** * Update an existing artifact. * - * @param artifact - * {@link ActionArtifact} object representing the artifact and - * its metadata - * @param actionInvariantUuId - * Invariant UUID of the action to which the artifact has to be - * uploaded - * @param user - * User ID of the user sending the request + * @param artifact {@link ActionArtifact} object representing the artifact and its metadata + * @param actionInvariantUuId Invariant UUID of the action to which the artifact has to be uploaded + * @param user User ID of the user sending the request */ public void updateArtifact(ActionArtifact artifact, String actionInvariantUuId, String user) { try { - log.debug("Enter updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID - + artifact.getArtifactUuId() + " and user = " + user); + log.debug( + "Enter updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifact.getArtifactUuId() + " and user = " + + user); actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_API); - VersionInfo versionInfo = versioningManager.getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, - actionInvariantUuId, user, VersionableEntityAction.Write); + VersionInfo versionInfo = versioningManager + .getEntityVersionInfo(ACTION_VERSIONABLE_TYPE, actionInvariantUuId, user, VersionableEntityAction.Write); actionLogPostProcessor(COMPLETE, null, "", false); log.metrics(""); Version activeVersion = versionInfo.getActiveVersion(); actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB); - Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion)) - .toDto(); + Action action = actionDao.get(new ActionEntity(actionInvariantUuId, activeVersion)).toDto(); actionLogPostProcessor(COMPLETE, null, "", false); log.metrics(""); List actionArtifacts = action.getArtifacts(); - ActionArtifact artifactMetadataByUuId = getArtifactMetadataFromAction(actionArtifacts, - ARTIFACT_METADATA_ATTR_UUID, artifact.getArtifactUuId()); + ActionArtifact artifactMetadataByUuId = getArtifactMetadataFromAction(actionArtifacts, ARTIFACT_METADATA_ATTR_UUID, + artifact.getArtifactUuId()); // Check if artifact is already in action or not if (artifactMetadataByUuId == null) { throw new ActionException(ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE, - ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); + ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST); } // If user tries to change artifact name - if (artifact.getArtifactName() != null && !artifactMetadataByUuId.getArtifactName() - .equalsIgnoreCase(artifact.getArtifactName())) { + if (artifact.getArtifactName() != null && !artifactMetadataByUuId.getArtifactName().equalsIgnoreCase(artifact.getArtifactName())) { throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE, ACTION_ARTIFACT_UPDATE_NAME_INVALID); } - byte[] payload = artifact.getArtifact(); String artifactLabel = artifact.getArtifactLabel(); String artifactCategory = artifact.getArtifactCategory(); @@ -748,15 +659,12 @@ public class ActionManagerImpl implements ActionManager { String artifactProtection = artifact.getArtifactProtection(); String artifactName = artifact.getArtifactName(); // If artifact read only - if (artifactMetadataByUuId.getArtifactProtection() - .equals(ActionArtifactProtection.readOnly.name())) { - if (artifactName != null || artifactLabel != null || artifactCategory != null - || artifactDescription != null || payload != null) { + if (artifactMetadataByUuId.getArtifactProtection().equals(ActionArtifactProtection.readOnly.name())) { + if (artifactName != null || artifactLabel != null || artifactCategory != null || artifactDescription != null || payload != null) { throw new ActionException(ACTION_ARTIFACT_UPDATE_READ_ONLY, ACTION_ARTIFACT_UPDATE_READ_ONLY_MSG); } // Changing value from readOnly to readWrite - if (artifactProtection != null - && artifactProtection.equals(ActionArtifactProtection.readWrite.name())) { + if (artifactProtection != null && artifactProtection.equals(ActionArtifactProtection.readWrite.name())) { artifactMetadataByUuId.setArtifactProtection(ActionArtifactProtection.readWrite.name()); artifactMetadataByUuId.setTimestamp(getCurrentTimeStampUtc()); updateArtifactMetadataInActionData(action, artifactMetadataByUuId); @@ -777,6 +685,7 @@ public class ActionManagerImpl implements ActionManager { } if (payload != null) { // get artifact data from action_artifact table for updating + // the content ActionArtifact artifactContent = new ActionArtifact(); artifactContent.setArtifactUuId(artifact.getArtifactUuId()); @@ -788,32 +697,28 @@ public class ActionManagerImpl implements ActionManager { artifactMetadataByUuId.setTimestamp(getCurrentTimeStampUtc()); updateArtifactMetadataInActionData(action, artifactMetadataByUuId); } - log.debug("exit updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID - + artifact.getArtifactUuId() + " and user = " + user); + log.debug( + "exit updateArtifact with actionInvariantUuId= " + actionInvariantUuId + ARTIFACT_UUID + artifact.getArtifactUuId() + " and user = " + + user); } catch (CoreException coreException) { formAndThrowException(coreException); } } /** - * Generate artifact UUID at runtime using action name and effective - * version. + * Generate artifact UUID at runtime using action name and effective version. * - * @param action - * {@link Action} for which the artifact is being - * uploaded/updated/downloaded - * @param artifactName - * Artifact name + * @param action {@link Action} for which the artifact is being uploaded/updated/downloaded + * @param artifactName Artifact name * @return Generated UUID string */ private String generateActionArtifactUuId(Action action, String artifactName) { int effectiveVersion = getEffectiveVersion(action.getVersion()); // Upper case for maintaining case-insensitive behavior for the artifact + // names - String artifactUuIdString = action.getName() - .toUpperCase() + effectiveVersion + artifactName.toUpperCase(); - String generateArtifactUuId = UUID.nameUUIDFromBytes((artifactUuIdString).getBytes()) - .toString(); + String artifactUuIdString = action.getName().toUpperCase() + effectiveVersion + artifactName.toUpperCase(); + String generateArtifactUuId = UUID.nameUUIDFromBytes((artifactUuIdString).getBytes()).toString(); String artifactUuId = generateArtifactUuId.replace("-", ""); return artifactUuId.toUpperCase(); } @@ -821,8 +726,7 @@ public class ActionManagerImpl implements ActionManager { /** * Generate the effective action version for artifact operations. * - * @param actionVersion - * Version of the action as a string + * @param actionVersion Version of the action as a string * @return Effective version to be used for artifact operations */ private int getEffectiveVersion(String actionVersion) { @@ -831,11 +735,9 @@ public class ActionManagerImpl implements ActionManager { } /** - * Update the data field of the Action object with the modified/generated - * fields after an operation. + * Update the data field of the Action object with the modified/generated fields after an operation. * - * @param action - * Action object whose data field has to be updated + * @param action Action object whose data field has to be updated * @return Updated {@link Action} object */ private Action updateData(Action action) { @@ -844,9 +746,7 @@ public class ActionManagerImpl implements ActionManager { dataMap.put(ActionConstants.UNIQUE_ID, action.getActionUuId()); dataMap.put(ActionConstants.VERSION, action.getVersion()); dataMap.put(ActionConstants.INVARIANTUUID, action.getActionInvariantUuId()); - dataMap.put(ActionConstants.STATUS, action.getStatus() - .name()); - + dataMap.put(ActionConstants.STATUS, action.getStatus().name()); String data = action.getData(); Map currentDataMap = JsonUtil.json2Object(data, LinkedHashMap.class); dataMap.putAll(currentDataMap); @@ -857,16 +757,12 @@ public class ActionManagerImpl implements ActionManager { } /** - * Method to add the artifact metadata in the data attribute of action - * table. + * Method to add the artifact metadata in the data attribute of action table. * - * @param action - * Action to which artifact is uploaded - * @param artifact - * Uploaded artifact object + * @param action Action to which artifact is uploaded + * @param artifact Uploaded artifact object */ private void addArtifactMetadataInActionData(Action action, ActionArtifact artifact) { - ActionArtifact artifactMetadata = new ActionArtifact(); artifactMetadata.setArtifactUuId(artifact.getArtifactUuId()); artifactMetadata.setArtifactName(artifact.getArtifactName()); @@ -875,7 +771,6 @@ public class ActionManagerImpl implements ActionManager { artifactMetadata.setArtifactDescription(artifact.getArtifactDescription()); artifactMetadata.setArtifactCategory(artifact.getArtifactCategory()); artifactMetadata.setTimestamp(artifact.getTimestamp()); - List actionArtifacts = action.getArtifacts(); if (actionArtifacts == null) { actionArtifacts = new ArrayList<>(); @@ -892,20 +787,17 @@ public class ActionManagerImpl implements ActionManager { } /** - * Get a list of last major and last minor version (no candidate) of action - * from a list of actions. + * Get a list of last major and last minor version (no candidate) of action from a list of actions. * - * @param actions - * Exhaustive list of the action versions - * @return List {@link Action} of last major and last minor version (no - * candidate) of action from a list of actions + * @param actions Exhaustive list of the action versions + * @return List {@link Action} of last major and last minor version (no candidate) of action from a list of actions */ private List getMajorMinorVersionActions(List actions) { log.debug(" entering getMajorMinorVersionActions for actions "); List list = new LinkedList<>(); actionLogPreProcessor(ActionSubOperation.GET_VERSIONINFO_FOR_ALL_ACTIONS, TARGET_ENTITY_API); - Map actionVersionMap = versioningManager.listEntitiesVersionInfo(ACTION_VERSIONABLE_TYPE, - "", VersionableEntityAction.Read); + Map actionVersionMap = versioningManager + .listEntitiesVersionInfo(ACTION_VERSIONABLE_TYPE, "", VersionableEntityAction.Read); actionLogPostProcessor(COMPLETE); log.metrics(""); for (Action action : actions) { @@ -913,13 +805,11 @@ public class ActionManagerImpl implements ActionManager { continue; } VersionInfo actionVersionInfo = actionVersionMap.get(action.getActionInvariantUuId()); - if (actionVersionInfo.getActiveVersion() != null && actionVersionInfo.getActiveVersion() - .equals(Version.valueOf(action.getVersion()))) { + if (actionVersionInfo.getActiveVersion() != null && actionVersionInfo.getActiveVersion().equals(Version.valueOf(action.getVersion()))) { list.add(action); } else if (actionVersionInfo.getLatestFinalVersion() != null && actionVersionInfo.getLatestFinalVersion() - .equals(Version.valueOf(action.getVersion())) - && !actionVersionInfo.getLatestFinalVersion() - .equals(actionVersionInfo.getActiveVersion())) { + .equals(Version.valueOf(action.getVersion())) && !actionVersionInfo.getLatestFinalVersion() + .equals(actionVersionInfo.getActiveVersion())) { list.add(action); } } @@ -928,99 +818,91 @@ public class ActionManagerImpl implements ActionManager { } /** - * CoreException object wrapper from Version library to Action Library - * Exception. + * CoreException object wrapper from Version library to Action Library Exception. * - * @param exception - * CoreException object from version library + * @param exception CoreException object from version library */ private void formAndThrowException(CoreException exception) { - log.debug("entering formAndThrowException with input CoreException =" + exception.code() - .id() + " " + exception.getMessage()); + log.debug("entering formAndThrowException with input CoreException =" + exception.code().id() + " " + exception.getMessage()); String errorDescription = exception.getMessage(); - String errorCode = exception.code() - .id(); + String errorCode = exception.code().id(); ActionException actionException = new ActionException(); switch (errorCode) { - case VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST: - actionException.setErrorCode(ACTION_ENTITY_NOT_EXIST_CODE); - actionException.setDescription(ACTION_ENTITY_NOT_EXIST); - break; - case VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY: - actionException.setErrorCode(ACTION_CHECKOUT_ON_LOCKED_ENTITY); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.CHECKIN_ON_UNLOCKED_ENTITY: - actionException.setErrorCode(ACTION_CHECKIN_ON_UNLOCKED_ENTITY); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED: - actionException.setErrorCode(ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.SUBMIT_LOCKED_ENTITY_NOT_ALLOWED: - actionException.setErrorCode(ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY: - actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER: - actionException.setErrorCode(ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER); - actionException.setDescription(errorDescription.replace("edit", "updat")); - break; - case VersioningErrorCodes.CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER: - actionException.setErrorCode(ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER: - actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER); - actionException.setDescription(errorDescription); - break; - case VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY: - actionException.setErrorCode(ACTION_UPDATE_ON_UNLOCKED_ENTITY); - actionException.setDescription(errorDescription.replace("edit", "update")); - break; - case VersioningErrorCodes.DELETE_ON_LOCKED_ENTITY: - actionException.setErrorCode(ACTION_DELETE_ON_LOCKED_ENTITY_CODE); - actionException.setDescription(errorDescription); - break; - default: - actionException.setErrorCode(ACTION_INTERNAL_SERVER_ERR_CODE); - actionException.setDescription(exception.getMessage()); - + case VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST: + actionException.setErrorCode(ACTION_ENTITY_NOT_EXIST_CODE); + actionException.setDescription(ACTION_ENTITY_NOT_EXIST); + break; + case VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY: + actionException.setErrorCode(ACTION_CHECKOUT_ON_LOCKED_ENTITY); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.CHECKIN_ON_UNLOCKED_ENTITY: + actionException.setErrorCode(ACTION_CHECKIN_ON_UNLOCKED_ENTITY); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED: + actionException.setErrorCode(ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.SUBMIT_LOCKED_ENTITY_NOT_ALLOWED: + actionException.setErrorCode(ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY: + actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER: + actionException.setErrorCode(ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER); + actionException.setDescription(errorDescription.replace("edit", "updat")); + break; + case VersioningErrorCodes.CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER: + actionException.setErrorCode(ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER: + actionException.setErrorCode(ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER); + actionException.setDescription(errorDescription); + break; + case VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY: + actionException.setErrorCode(ACTION_UPDATE_ON_UNLOCKED_ENTITY); + actionException.setDescription(errorDescription.replace("edit", "update")); + break; + case VersioningErrorCodes.DELETE_ON_LOCKED_ENTITY: + actionException.setErrorCode(ACTION_DELETE_ON_LOCKED_ENTITY_CODE); + actionException.setDescription(errorDescription); + break; + default: + actionException.setErrorCode(ACTION_INTERNAL_SERVER_ERR_CODE); + actionException.setDescription(exception.getMessage()); } // Todo - Uncomment only if class to be added in ERROR Log + /* * actionErrorLogProcessor(CategoryLogLevel.ERROR, * actionException.getErrorCode(), actionException.getDescription()); * log.error(""); */ - log.debug("exit formAndThrowException with ActionException =" + actionException.getErrorCode() + " " - + actionException.getDescription()); + log.debug("exit formAndThrowException with ActionException =" + actionException.getErrorCode() + " " + actionException.getDescription()); throw actionException; } /** - * Validates an action object for business layer validations before an - * update operation. + * Validates an action object for business layer validations before an update operation. * - * @param action - * Action object to be validated - * @param activeVersion - * Active version of the actoin object + * @param action Action object to be validated + * @param activeVersion Active version of the actoin object */ private void validateActions(Action action, Version activeVersion) { try { // Set version if not already available in input request + // If version set in input compare it with version from DB if (StringUtils.isEmpty(action.getVersion())) { action.setVersion(activeVersion.toString()); } else { if (!activeVersion.equals(Version.valueOf(action.getVersion()))) { - throw new ActionException(ACTION_UPDATE_INVALID_VERSION, - String.format(ACTION_REQUESTED_VERSION_INVALID, action.getVersion())); + throw new ActionException(ACTION_UPDATE_INVALID_VERSION, String.format(ACTION_REQUESTED_VERSION_INVALID, action.getVersion())); } } String invariantUuId = action.getActionInvariantUuId(); @@ -1031,21 +913,18 @@ public class ActionManagerImpl implements ActionManager { } List invalidParameters = new LinkedList<>(); // Prevent update of name, version and id fields - if (!existingAction.getName() - .equals(action.getName())) { + if (!existingAction.getName().equals(action.getName())) { throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE_NAME, ACTION_UPDATE_NOT_ALLOWED_FOR_NAME); } - if (!StringUtils.isEmpty(action.getActionUuId()) && !existingAction.getActionUuId() - .equals(action.getActionUuId())) { + if (!StringUtils.isEmpty(action.getActionUuId()) && !existingAction.getActionUuId().equals(action.getActionUuId())) { invalidParameters.add(UNIQUE_ID); } if (action.getStatus() != null && (existingAction.getStatus() != action.getStatus())) { invalidParameters.add(STATUS); } - if (!invalidParameters.isEmpty()) { throw new ActionException(ACTION_UPDATE_NOT_ALLOWED_CODE, - String.format(ACTION_UPDATE_PARAM_INVALID, StringUtils.join(invalidParameters, ", "))); + String.format(ACTION_UPDATE_PARAM_INVALID, StringUtils.join(invalidParameters, ", "))); } action.setActionUuId(existingAction.getActionUuId()); } catch (IllegalArgumentException iae) { @@ -1061,10 +940,8 @@ public class ActionManagerImpl implements ActionManager { /** * Get an action version entity object. * - * @param invariantUuId - * Invariant UUID of the action - * @param version - * Version of the action + * @param invariantUuId Invariant UUID of the action + * @param version Version of the action * @return {@link ActionEntity} object of the action version */ private ActionEntity getActionsEntityByVersion(String invariantUuId, Version version) { @@ -1072,8 +949,7 @@ public class ActionManagerImpl implements ActionManager { ActionEntity entity = null; if (version != null) { actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VERSION, TARGET_ENTITY_DB); - entity = actionDao - .get(new ActionEntity(invariantUuId != null ? invariantUuId.toUpperCase() : null, version)); + entity = actionDao.get(new ActionEntity(invariantUuId != null ? invariantUuId.toUpperCase() : null, version)); actionLogPostProcessor(COMPLETE); log.metrics(""); } @@ -1084,34 +960,27 @@ public class ActionManagerImpl implements ActionManager { /** * Get an action version object. * - * @param invariantUuId - * Invariant UUID of the action - * @param version - * Version of the action + * @param invariantUuId Invariant UUID of the action + * @param version Version of the action * @return {@link Action} object of the action version */ private Action getActions(String invariantUuId, Version version) { - ActionEntity actionEntity = getActionsEntityByVersion( - invariantUuId != null ? invariantUuId.toUpperCase() : null, version); + ActionEntity actionEntity = getActionsEntityByVersion(invariantUuId != null ? invariantUuId.toUpperCase() : null, version); return actionEntity != null ? actionEntity.toDto() : new Action(); } /** * Create and set the Unique ID in for an action version row. * - * @param invariantUuId - * Invariant UUID of the action - * @param version - * Version of the action - * @param status - * Status of the action - * @param user - * AT&T id of the user sending the request + * @param invariantUuId Invariant UUID of the action + * @param version Version of the action + * @param status Status of the action + * @param user AT&T id of the user sending the request * @return {@link ActionEntity} object of the action version */ private ActionEntity updateUniqueIdForVersion(String invariantUuId, Version version, String status, String user) { - log.debug("entering updateUniqueIdForVersion to update action with invariantUuId= " + invariantUuId - + " with version,status and user as ::" + version + " " + status + " " + user); + log.debug("entering updateUniqueIdForVersion to update action with invariantUuId= " + invariantUuId + " with version,status and user as ::" + + version + " " + status + " " + user); // generate UUID AND update for newly created entity row ActionEntity actionEntity = getActionsEntityByVersion(invariantUuId, version); if (actionEntity != null) { @@ -1123,7 +992,6 @@ public class ActionManagerImpl implements ActionManager { dataMap.put(ActionConstants.VERSION, version.toString()); dataMap.put(ActionConstants.STATUS, status); data = JsonUtil.object2Json(dataMap); - actionEntity.setData(data); actionEntity.setActionUuId(uniqueId); actionEntity.setStatus(status); @@ -1134,7 +1002,6 @@ public class ActionManagerImpl implements ActionManager { actionLogPostProcessor(COMPLETE); log.metrics(""); } - log.debug("exit updateUniqueIdForVersion to update action with invariantUUID= " + invariantUuId); return actionEntity; } @@ -1142,19 +1009,15 @@ public class ActionManagerImpl implements ActionManager { /** * Set the status for an action version row. * - * @param invariantUuId - * Invariant UUID of the action - * @param version - * Version of the action - * @param status - * Status of the action - * @param user - * AT&T id of the user sending the request + * @param invariantUuId Invariant UUID of the action + * @param version Version of the action + * @param status Status of the action + * @param user AT&T id of the user sending the request * @return {@link ActionEntity} object of the action version */ private ActionEntity updateStatusForVersion(String invariantUuId, Version version, String status, String user) { - log.debug("entering updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version - + " for updating status " + status + " by user " + user); + log.debug("entering updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version + " for updating status " + status + + " by user " + user); ActionEntity actionEntity = getActionsEntityByVersion(invariantUuId, version); if (actionEntity != null) { String data = actionEntity.getData(); @@ -1170,46 +1033,40 @@ public class ActionManagerImpl implements ActionManager { actionLogPostProcessor(COMPLETE); log.metrics(""); } - log.debug("exit updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version - + " for updating status " + status + " by user " + user); + log.debug("exit updateStatusForVersion with invariantUuId= " + invariantUuId + AND_VERSION + version + " for updating status " + status + + " by user " + user); return actionEntity; - } /** * Gets an artifact from the action artifact metadata by artifact name. * - * @param actionArtifactList - * Action's existing artifact list - * @param artifactFilterType - * Search criteria for artifact in action artifact metadata - * @param artifactFilterValue - * Value of Search parameter - * @return Artifact metadata object if artifact is present in action and - * null otherwise + * @param actionArtifactList Action's existing artifact list + * @param artifactFilterType Search criteria for artifact in action artifact metadata + * @param artifactFilterValue Value of Search parameter + * @return Artifact metadata object if artifact is present in action and null otherwise */ - private ActionArtifact getArtifactMetadataFromAction(List actionArtifactList, - String artifactFilterType, String artifactFilterValue) { + private ActionArtifact getArtifactMetadataFromAction(List actionArtifactList, String artifactFilterType, + String artifactFilterValue) { ActionArtifact artifact = null; if (actionArtifactList != null && !actionArtifactList.isEmpty()) { for (ActionArtifact entry : actionArtifactList) { switch (artifactFilterType) { - case ARTIFACT_METADATA_ATTR_UUID: - String artifactUuId = entry.getArtifactUuId(); - if (artifactUuId != null && artifactUuId.equals(artifactFilterValue)) { - artifact = entry; + case ARTIFACT_METADATA_ATTR_UUID: + String artifactUuId = entry.getArtifactUuId(); + if (artifactUuId != null && artifactUuId.equals(artifactFilterValue)) { + artifact = entry; + break; + } break; - } - break; - case ARTIFACT_METADATA_ATTR_NAME: - String existingArtifactName = entry.getArtifactName() - .toLowerCase(); - if (existingArtifactName.equals(artifactFilterValue.toLowerCase())) { - artifact = entry; + case ARTIFACT_METADATA_ATTR_NAME: + String existingArtifactName = entry.getArtifactName().toLowerCase(); + if (existingArtifactName.equals(artifactFilterValue.toLowerCase())) { + artifact = entry; + break; + } break; - } - break; - default: + default: } } } @@ -1217,18 +1074,14 @@ public class ActionManagerImpl implements ActionManager { } /** - * Method to update the artifact metadata in the data attribute of action - * table. + * Method to update the artifact metadata in the data attribute of action table. * - * @param action - * Action to which artifact is uploaded - * @param updatedArtifact - * updated artifact object + * @param action Action to which artifact is uploaded + * @param updatedArtifact updated artifact object */ private void updateArtifactMetadataInActionData(Action action, ActionArtifact updatedArtifact) { for (ActionArtifact entry : action.getArtifacts()) { - if (entry.getArtifactUuId() - .equals(updatedArtifact.getArtifactUuId())) { + if (entry.getArtifactUuId().equals(updatedArtifact.getArtifactUuId())) { entry.setArtifactLabel(updatedArtifact.getArtifactLabel()); entry.setArtifactCategory(updatedArtifact.getArtifactCategory()); entry.setArtifactDescription(updatedArtifact.getArtifactDescription()); diff --git a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManager.java b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManager.java index 8499e7a96a..cd8a9571c0 100644 --- a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManager.java +++ b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManager.java @@ -13,17 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.activitylog; +import java.util.Collection; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ActivityLogManager { - void logActivity(ActivityLogEntity activityLogEntity); + void logActivity(ActivityLogEntity activityLogEntity); - Collection listLoggedActivities(String itemId, Version versionId); + Collection listLoggedActivities(String itemId, Version versionId); } diff --git a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManagerFactory.java b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManagerFactory.java index 639345c7f0..fbfcc4a4df 100644 --- a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/ActivityLogManagerFactory.java @@ -18,8 +18,8 @@ package org.openecomp.sdc.activitylog; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; - public abstract class ActivityLogManagerFactory extends AbstractComponentFactory { + public static ActivityLogManagerFactory getInstance() { return AbstractFactory.getInstance(ActivityLogManagerFactory.class); } diff --git a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerFactoryImpl.java index c1dd5d0a75..31819dc1c7 100644 --- a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerFactoryImpl.java @@ -20,19 +20,19 @@ import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; import org.openecomp.sdc.activitylog.dao.ActivityLogDaoFactory; public class ActivityLogManagerFactoryImpl extends ActivityLogManagerFactory { - private final ActivityLogManager INSTANCE; + private final ActivityLogManager INSTANCE; - public ActivityLogManagerFactoryImpl() { - this.INSTANCE = new ActivityLogManagerImpl(ActivityLogDaoFactory.getInstance().createInterface()); - } + public ActivityLogManagerFactoryImpl() { + this.INSTANCE = new ActivityLogManagerImpl(ActivityLogDaoFactory.getInstance().createInterface()); + } - ActivityLogManagerFactoryImpl(ActivityLogManager activityLogManager) { - this.INSTANCE = activityLogManager; - } + ActivityLogManagerFactoryImpl(ActivityLogManager activityLogManager) { + this.INSTANCE = activityLogManager; + } - @Override - public ActivityLogManager createInterface() { - return INSTANCE; - } + @Override + public ActivityLogManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerImpl.java b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerImpl.java index 39a2d5c962..2b4e5c95de 100644 --- a/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-activity-log-manager/src/main/java/org/openecomp/sdc/activitylog/impl/ActivityLogManagerImpl.java @@ -13,32 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.activitylog.impl; +import java.util.Collection; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.activitylog.ActivityLogManager; import org.openecomp.sdc.activitylog.dao.ActivityLogDao; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public class ActivityLogManagerImpl implements ActivityLogManager { - private ActivityLogDao activityLogDao; - public ActivityLogManagerImpl(ActivityLogDao activityLogDao) { - this.activityLogDao = activityLogDao; - } + private ActivityLogDao activityLogDao; + + public ActivityLogManagerImpl(ActivityLogDao activityLogDao) { + this.activityLogDao = activityLogDao; + } - @Override - public void logActivity(ActivityLogEntity activityLogEntity) { - activityLogEntity.setId(CommonMethods.nextUuId()); - activityLogDao.create(activityLogEntity); - } + @Override + public void logActivity(ActivityLogEntity activityLogEntity) { + activityLogEntity.setId(CommonMethods.nextUuId()); + activityLogDao.create(activityLogEntity); + } - @Override - public Collection listLoggedActivities(String itemId, Version version) { - return activityLogDao.list(new ActivityLogEntity(itemId, version)); - } + @Override + public Collection listLoggedActivities(String itemId, Version version) { + return activityLogDao.list(new ActivityLogEntity(itemId, version)); + } } diff --git a/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/ApplicationConfigManager.java b/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/ApplicationConfigManager.java index ff95e5af3c..74c7193018 100644 --- a/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/ApplicationConfigManager.java +++ b/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/ApplicationConfigManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.applicationconfig; +import java.util.Collection; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; -import java.util.Collection; - /** * Created by Talio on 8/8/2016. */ public interface ApplicationConfigManager { - void insertIntoTable(String namespace, String key, String value); + void insertIntoTable(String namespace, String key, String value); - ConfigurationData getFromTable(String namespace, String key); + ConfigurationData getFromTable(String namespace, String key); - Collection getListOfConfigurationByNamespace(String namespace); + Collection getListOfConfigurationByNamespace(String namespace); } diff --git a/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/impl/ApplicationConfigManagerImpl.java b/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/impl/ApplicationConfigManagerImpl.java index bc9354f221..9c164b74c3 100644 --- a/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/impl/ApplicationConfigManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-application-config-manager/src/main/java/org/openecomp/sdc/applicationconfig/impl/ApplicationConfigManagerImpl.java @@ -12,10 +12,10 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.applicationconfig.impl; +import java.util.Collection; import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.impl.ApplicationConfigImpl; @@ -25,37 +25,33 @@ import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import java.util.Collection; - /** * Created by Talio on 8/8/2016. */ public class ApplicationConfigManagerImpl implements ApplicationConfigManager { - private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR = - "SCHEMA_GENERATOR_INITIALIZATION_ERROR"; - private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG = - "Error occurred while loading questionnaire schema templates"; - private ApplicationConfig applicationConfig = new ApplicationConfigImpl(); - - @Override - public void insertIntoTable(String namespace, String key, String value) { - try { - applicationConfig.insertValue(namespace, key, value); - } catch (Exception exception) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory - .APPLICATION).withId(SCHEMA_GENERATOR_INITIALIZATION_ERROR).withMessage( - SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG).build(), exception); + private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR = "SCHEMA_GENERATOR_INITIALIZATION_ERROR"; + private static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG = "Error occurred while loading questionnaire schema templates"; + private ApplicationConfig applicationConfig = new ApplicationConfigImpl(); + + @Override + public void insertIntoTable(String namespace, String key, String value) { + try { + applicationConfig.insertValue(namespace, key, value); + } catch (Exception exception) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(SCHEMA_GENERATOR_INITIALIZATION_ERROR) + .withMessage(SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG).build(), exception); + } } - } - @Override - public ConfigurationData getFromTable(String namespace, String key) { - return applicationConfig.getConfigurationData(namespace, key); - } + @Override + public ConfigurationData getFromTable(String namespace, String key) { + return applicationConfig.getConfigurationData(namespace, key); + } - @Override - public Collection getListOfConfigurationByNamespace(String namespace) { - return applicationConfig.getListOfConfigurationByNamespace(namespace); - } + @Override + public Collection getListOfConfigurationByNamespace(String namespace) { + return applicationConfig.getListOfConfigurationByNamespace(namespace); + } } diff --git a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManager.java b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManager.java index 28c32e049f..1231469f31 100644 --- a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManager.java +++ b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.conflicts; import org.openecomp.conflicts.types.Conflict; @@ -27,14 +26,13 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ConflictsManager { - boolean isConflicted(String itemId, Version version); + boolean isConflicted(String itemId, Version version); - ItemVersionConflict getConflict(String itemId, Version version); + ItemVersionConflict getConflict(String itemId, Version version); - void finalizeMerge(String itemId, Version version); + void finalizeMerge(String itemId, Version version); - Conflict getConflict(String itemId, Version version, String conflictId); + Conflict getConflict(String itemId, Version version, String conflictId); - void resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution); + void resolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution); } diff --git a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManagerFactory.java b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManagerFactory.java index 7a24cfd311..b13a4329c3 100644 --- a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/ConflictsManagerFactory.java @@ -22,8 +22,8 @@ package org.openecomp.sdc.conflicts; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; - public abstract class ConflictsManagerFactory extends AbstractComponentFactory { + public static ConflictsManagerFactory getInstance() { return AbstractFactory.getInstance(ConflictsManagerFactory.class); } diff --git a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerFactoryImpl.java index 2d703c4a87..72347580b0 100644 --- a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerFactoryImpl.java @@ -19,17 +19,16 @@ */ package org.openecomp.sdc.conflicts.impl; - import org.openecomp.conflicts.dao.ConflictsDaoFactory; import org.openecomp.sdc.conflicts.ConflictsManager; import org.openecomp.sdc.conflicts.ConflictsManagerFactory; public class ConflictsManagerFactoryImpl extends ConflictsManagerFactory { - private static final ConflictsManager INSTANCE = - new ConflictsManagerImpl(ConflictsDaoFactory.getInstance().createInterface()); - @Override - public ConflictsManager createInterface() { - return INSTANCE; - } + private static final ConflictsManager INSTANCE = new ConflictsManagerImpl(ConflictsDaoFactory.getInstance().createInterface()); + + @Override + public ConflictsManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerImpl.java b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerImpl.java index 284823baac..5ae23783c4 100644 --- a/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-conflict-manager/src/main/java/org/openecomp/sdc/conflicts/impl/ConflictsManagerImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.conflicts.impl; +import java.util.Optional; import org.openecomp.conflicts.ItemMergeHandler; import org.openecomp.conflicts.ItemMergeHandlerFactory; import org.openecomp.conflicts.dao.ConflictsDao; @@ -33,100 +33,67 @@ import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.conflicts.ConflictsManager; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Optional; - public class ConflictsManagerImpl implements ConflictsManager { - private static final String ELEMENT_CONFLICT_NOT_EXIST_ERR_ID = "ELEMENT_CONFLICT_NOT_EXIST"; - private static final String ELEMENT_CONFLICT_NOT_EXISTS_MSG = - "Item Id %s, version Id %s, element conflict with Id %s does not exists."; - - private final ConflictsDao conflictsDao; - - public ConflictsManagerImpl(ConflictsDao conflictsDao) { - this.conflictsDao = conflictsDao; - } - - @Override - public boolean isConflicted(String itemId, Version version) { - Optional itemMergeHandler = - ItemMergeHandlerFactory.getInstance().createInterface(itemId); - - return conflictsDao.isConflicted(itemId, version) || - (itemMergeHandler.isPresent() && - itemMergeHandler.get().isConflicted(itemId, version)); - } - - @Override - public ItemVersionConflict getConflict(String itemId, Version version) { - ItemVersionConflict conflicts = conflictsDao.getConflict(itemId, version); + private static final String ELEMENT_CONFLICT_NOT_EXIST_ERR_ID = "ELEMENT_CONFLICT_NOT_EXIST"; + private static final String ELEMENT_CONFLICT_NOT_EXISTS_MSG = "Item Id %s, version Id %s, element conflict with Id %s does not exists."; + private final ConflictsDao conflictsDao; - ItemMergeHandlerFactory.getInstance().createInterface(itemId) - .ifPresent(itemMergeHandler -> itemMergeHandler - .postListConflicts(itemId, version, conflicts)); - - return conflicts; - } - - @Override - public void finalizeMerge(String itemId, Version version) { - ItemMergeHandlerFactory.getInstance().createInterface(itemId) - .ifPresent(mergeHandler -> mergeHandler.finalizeMerge(itemId, version)); - } - - @Override - public Conflict getConflict(String itemId, Version version, String conflictId) { - Optional itemMergeHandler = - ItemMergeHandlerFactory.getInstance().createInterface(itemId); - if (itemMergeHandler.isPresent()) { - Optional conflict = - itemMergeHandler.get().getConflict(itemId, version, conflictId); - if (conflict.isPresent()) { - return conflict.get(); - } + public ConflictsManagerImpl(ConflictsDao conflictsDao) { + this.conflictsDao = conflictsDao; } - Conflict conflict = conflictsDao.getConflict(itemId, version, conflictId); - - itemMergeHandler.ifPresent(mergeHandler -> - mergeHandler.postGetConflict(itemId, version, conflict)); - - if (conflict == null) { - throw getConflictNotExistException(itemId, version, conflictId); + @Override + public boolean isConflicted(String itemId, Version version) { + Optional itemMergeHandler = ItemMergeHandlerFactory.getInstance().createInterface(itemId); + return conflictsDao.isConflicted(itemId, version) || (itemMergeHandler.isPresent() && itemMergeHandler.get().isConflicted(itemId, version)); } - return conflict; - } - @Override - public void resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution) { - if (Resolution.OTHER.equals(resolution.getResolution())) { - throw new UnsupportedOperationException( - "Resolution other than 'THEIRS' or 'YOURS' is not supported."); + @Override + public ItemVersionConflict getConflict(String itemId, Version version) { + ItemVersionConflict conflicts = conflictsDao.getConflict(itemId, version); + ItemMergeHandlerFactory.getInstance().createInterface(itemId) + .ifPresent(itemMergeHandler -> itemMergeHandler.postListConflicts(itemId, version, conflicts)); + return conflicts; } - Optional itemMergeHandler = - ItemMergeHandlerFactory.getInstance().createInterface(itemId); - if (!itemMergeHandler.isPresent() || - !itemMergeHandler.get() - .resolveConflict(itemId, version, conflictId, resolution)) { - - getConflict(itemId, version, conflictId); // validate that the conflict exist - itemMergeHandler.ifPresent(mergeHandler -> - mergeHandler.preResolveConflict(itemId, version, conflictId, resolution)); + @Override + public void finalizeMerge(String itemId, Version version) { + ItemMergeHandlerFactory.getInstance().createInterface(itemId).ifPresent(mergeHandler -> mergeHandler.finalizeMerge(itemId, version)); + } - conflictsDao.resolveConflict(itemId, version, conflictId, resolution); + @Override + public Conflict getConflict(String itemId, Version version, String conflictId) { + Optional itemMergeHandler = ItemMergeHandlerFactory.getInstance().createInterface(itemId); + if (itemMergeHandler.isPresent()) { + Optional conflict = itemMergeHandler.get().getConflict(itemId, version, conflictId); + if (conflict.isPresent()) { + return conflict.get(); + } + } + Conflict conflict = conflictsDao.getConflict(itemId, version, conflictId); + itemMergeHandler.ifPresent(mergeHandler -> mergeHandler.postGetConflict(itemId, version, conflict)); + if (conflict == null) { + throw getConflictNotExistException(itemId, version, conflictId); + } + return conflict; } - } - private CoreException getConflictNotExistException(String itemId, Version version, - String conflictId) { - return new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId(ELEMENT_CONFLICT_NOT_EXIST_ERR_ID) - .withMessage( - String.format(ELEMENT_CONFLICT_NOT_EXISTS_MSG, itemId, version.getId(), conflictId)) - .build()); - } + @Override + public void resolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution) { + if (Resolution.OTHER.equals(resolution.getResolution())) { + throw new UnsupportedOperationException("Resolution other than 'THEIRS' or 'YOURS' is not supported."); + } + Optional itemMergeHandler = ItemMergeHandlerFactory.getInstance().createInterface(itemId); + if (!itemMergeHandler.isPresent() || !itemMergeHandler.get().resolveConflict(itemId, version, conflictId, resolution)) { + getConflict(itemId, version, conflictId); // validate that the conflict exist + itemMergeHandler.ifPresent(mergeHandler -> mergeHandler.preResolveConflict(itemId, version, conflictId, resolution)); + conflictsDao.resolveConflict(itemId, version, conflictId, resolution); + } + } + private CoreException getConflictNotExistException(String itemId, Version version, String conflictId) { + return new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(ELEMENT_CONFLICT_NOT_EXIST_ERR_ID) + .withMessage(String.format(ELEMENT_CONFLICT_NOT_EXISTS_MSG, itemId, version.getId(), conflictId)).build()); + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDao.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDao.java index 947387b4a6..0f1351e9bb 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDao.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health; public interface HealthCheckDao { - boolean checkHealth() throws Exception; - String getVersion(); + + boolean checkHealth() throws Exception; + + String getVersion(); } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDaoFactory.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDaoFactory.java index 387d24d07c..d76eee25ef 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDaoFactory.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class HealthCheckDaoFactory extends AbstractComponentFactory { - public static HealthCheckDaoFactory getInstance() { - return AbstractFactory.getInstance(HealthCheckDaoFactory.class); - } + + public static HealthCheckDaoFactory getInstance() { + return AbstractFactory.getInstance(HealthCheckDaoFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManager.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManager.java index 0575d06058..6a543cbcf5 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManager.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManager.java @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health; -import org.openecomp.sdc.health.data.HealthInfo; - import java.util.Collection; +import org.openecomp.sdc.health.data.HealthInfo; public interface HealthCheckManager { + Collection checkHealth(); } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManagerFactory.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManagerFactory.java index c3766068b2..00c3001496 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/HealthCheckManagerFactory.java @@ -22,8 +22,8 @@ package org.openecomp.sdc.health; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; - public abstract class HealthCheckManagerFactory extends AbstractComponentFactory { + public static HealthCheckManagerFactory getInstance() { return AbstractFactory.getInstance(HealthCheckManagerFactory.class); } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckResult.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckResult.java index bd47422a20..e243e7e555 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckResult.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckResult.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.data; import java.util.Collection; /** - * { - "sdcVersion": "1702.0.83.37.1", + * { "sdcVersion": "1702.0.83.37.1", "componentsInfo": [ { @@ -36,11 +34,11 @@ import java.util.Collection; ….. ] } - */ public class HealthCheckResult { + String sdcVersion; - Collection componentsInfo; + Collection componentsInfo; public HealthCheckResult() { } @@ -60,6 +58,4 @@ public class HealthCheckResult { public void setComponentsInfo(Collection componentsInfo) { this.componentsInfo = componentsInfo; } - - } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckStatus.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckStatus.java index c5ef04477c..fccbe2a907 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckStatus.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthCheckStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.data; - public enum HealthCheckStatus { - UP("UP"), - DOWN("DOWN"); - + UP("UP"), DOWN("DOWN"); private String name; HealthCheckStatus(String name) { this.name = name; } - - @Override - public String toString() { - return name; - } - - public static final HealthCheckStatus toValue(String inVal){ - for (HealthCheckStatus val : values()){ - if (val.toString().equals(inVal)){ + public static final HealthCheckStatus toValue(String inVal) { + for (HealthCheckStatus val : values()) { + if (val.toString().equals(inVal)) { return val; } } return null; } + + @Override + public String toString() { + return name; + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthInfo.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthInfo.java index 3bb58fbaf3..bad6ebfb89 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthInfo.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/HealthInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.data; /** @@ -34,6 +33,7 @@ package org.openecomp.sdc.health.data; } */ public class HealthInfo { + private MonitoredModules healthCheckComponent; private HealthCheckStatus healthCheckStatus; private String version; @@ -83,11 +83,7 @@ public class HealthInfo { @Override public String toString() { - return "HealthInfo{" + - "healthCheckComponent='" + healthCheckComponent + '\'' + - ", healthCheckStatus=" + healthCheckStatus + - ", version='" + version + '\'' + - ", description='" + description + '\'' + - '}'; + return "HealthInfo{" + "healthCheckComponent='" + healthCheckComponent + '\'' + ", healthCheckStatus=" + healthCheckStatus + ", version='" + + version + '\'' + ", description='" + description + '\'' + '}'; } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/MonitoredModules.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/MonitoredModules.java index b51d79095a..f990f64336 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/MonitoredModules.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/MonitoredModules.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.data; - public enum MonitoredModules { - BE("BE"), CAS("Cassandra"), - ZU("Zusammen"); - + BE("BE"), CAS("Cassandra"), ZU("Zusammen"); private String name; MonitoredModules(String name) { this.name = name; } - - @Override - public String toString() { - return name; - } - public static final MonitoredModules toValue(String inVal) { for (MonitoredModules val : values()) { if (val.toString().equals(inVal)) { @@ -45,4 +35,9 @@ public enum MonitoredModules { } return null; } + + @Override + public String toString() { + return name; + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/SiteMode.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/SiteMode.java index 810dee5355..be2cd33b1f 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/SiteMode.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/data/SiteMode.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.data; - public enum SiteMode { Active("active"), NOT_ACTIVE("NotActive"); - private String name; SiteMode(String name) { this.name = name; } - - @Override - public String toString() { - return name; - } - public static final SiteMode toValue(String inVal) { for (SiteMode val : values()) { if (val.toString().equals(inVal)) { @@ -44,4 +35,9 @@ public enum SiteMode { } return null; } + + @Override + public String toString() { + return name; + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoFactoryImpl.java index ec0931c90b..02291ed23c 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.impl; - import org.openecomp.sdc.health.HealthCheckDao; import org.openecomp.sdc.health.HealthCheckDaoFactory; -public class HealthCheckDaoFactoryImpl - extends HealthCheckDaoFactory { - private static final HealthCheckDao INSTANCE = - new HealthCheckDaoImpl(); +public class HealthCheckDaoFactoryImpl extends HealthCheckDaoFactory { + + private static final HealthCheckDao INSTANCE = new HealthCheckDaoImpl(); - @Override - public HealthCheckDao createInterface() { - return INSTANCE; - } + @Override + public HealthCheckDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoImpl.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoImpl.java index f9b4215322..340af95849 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoImpl.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.health.impl; - import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.exceptions.DriverException; import com.datastax.driver.mapping.annotations.Accessor; @@ -34,9 +32,7 @@ import org.openecomp.sdc.logging.api.LoggerFactory; public class HealthCheckDaoImpl implements HealthCheckDao { private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - - private static final CheckHealthAccessor accessor = - noSqlDb.getMappingManager().createAccessor(CheckHealthAccessor.class); + private static final CheckHealthAccessor accessor = noSqlDb.getMappingManager().createAccessor(CheckHealthAccessor.class); private static final Logger logger = LoggerFactory.getLogger(HealthCheckDaoImpl.class); @Override @@ -63,7 +59,5 @@ public class HealthCheckDaoImpl implements HealthCheckDao { @Query("SELECT * FROM application_config LIMIT 1") ResultSet checkHealth(); - } - } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerFactoryImpl.java index e5d85a2641..a50e5b15c2 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerFactoryImpl.java @@ -23,12 +23,15 @@ import org.openecomp.sdc.health.HealthCheckManager; import org.openecomp.sdc.health.HealthCheckManagerFactory; public class HealthCheckManagerFactoryImpl extends HealthCheckManagerFactory { - private static final HealthCheckManager INSTANCE ; + + private static final HealthCheckManager INSTANCE; static { - INSTANCE = new HealthCheckManagerImpl(); + INSTANCE = new HealthCheckManagerImpl(); } @Override - public HealthCheckManager createInterface() {return INSTANCE;} + public HealthCheckManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerImpl.java b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerImpl.java index dba724565f..de4c79950e 100644 --- a/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-healthcheck-manager/src/main/java/org/openecomp/sdc/health/impl/HealthCheckManagerImpl.java @@ -13,12 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.health.impl; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.commons.health.data.HealthStatus; import com.amdocs.zusammen.datatypes.SessionContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; import org.openecomp.core.zusammen.api.ZusammenUtil; @@ -30,16 +34,9 @@ import org.openecomp.sdc.health.data.MonitoredModules; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - public class HealthCheckManagerImpl implements HealthCheckManager { private static final Logger LOGGER = LoggerFactory.getLogger(HealthCheckManagerImpl.class); - private HealthCheckDao healthCheckDao; public HealthCheckManagerImpl() { @@ -53,22 +50,19 @@ public class HealthCheckManagerImpl implements HealthCheckManager { @Override public Collection checkHealth() { org.openecomp.sdc.health.data.HealthInfo zeHealthInfo = null; - org.openecomp.sdc.health.data.HealthInfo beHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.BE, HealthCheckStatus.UP, getBEVersion(), "OK"); + org.openecomp.sdc.health.data.HealthInfo beHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.BE, + HealthCheckStatus.UP, getBEVersion(), "OK"); org.openecomp.sdc.health.data.HealthInfo cassandraHealthInfo = null; String zVersion = "Unknown"; try { SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenAdaptor zusammenAdaptor = ZusammenAdaptorFactory - .getInstance().createInterface(); + ZusammenAdaptor zusammenAdaptor = ZusammenAdaptorFactory.getInstance().createInterface(); Collection zeHealthInfos = new ArrayList<>(); try { zeHealthInfos = zusammenAdaptor.checkHealth(context); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); - zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.ZU, HealthCheckStatus.DOWN, - zVersion, ex.getMessage()); + zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.ZU, HealthCheckStatus.DOWN, zVersion, ex.getMessage()); } boolean cassandraHealth = false; String description = "OK"; @@ -77,47 +71,34 @@ public class HealthCheckManagerImpl implements HealthCheckManager { } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); description = ex.getMessage(); - cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.CAS, HealthCheckStatus.DOWN, zVersion, ex.getMessage()); + cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.CAS, HealthCheckStatus.DOWN, zVersion, + ex.getMessage()); } zVersion = zusammenAdaptor.getVersion(context); if (cassandraHealthInfo == null) { HealthCheckStatus status = cassandraHealth ? HealthCheckStatus.UP : HealthCheckStatus.DOWN; - if (!cassandraHealth){ + if (!cassandraHealth) { description = "Cassandra is not available"; } - cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.CAS, status, - healthCheckDao.getVersion(), description); + cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.CAS, status, healthCheckDao.getVersion(), + description); } if (zeHealthInfo == null) { - List downHealth = zeHealthInfos.stream(). - filter(h -> h.getHealthStatus().equals(HealthStatus.DOWN)). - collect(Collectors.toList()); - + List downHealth = zeHealthInfos.stream().filter(h -> h.getHealthStatus().equals(HealthStatus.DOWN)) + .collect(Collectors.toList()); if (downHealth.isEmpty()) { - zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.ZU, HealthCheckStatus.UP, - zVersion, "OK"); + zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.ZU, HealthCheckStatus.UP, zVersion, "OK"); } else { - String desc = downHealth.stream().map(healthInfo -> healthInfo.getDescription()) - .collect(Collectors.joining(" , ", "[", "]")); - zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.ZU, HealthCheckStatus.DOWN, - zVersion, desc); + String desc = downHealth.stream().map(healthInfo -> healthInfo.getDescription()).collect(Collectors.joining(" , ", "[", "]")); + zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.ZU, HealthCheckStatus.DOWN, zVersion, desc); } - } } catch (Exception e) { LOGGER.error(e.getMessage(), e); - zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.ZU, HealthCheckStatus.DOWN, zVersion, e.getMessage() - ); - cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo( - MonitoredModules.CAS, HealthCheckStatus.DOWN, zVersion, e.getMessage()); + zeHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.ZU, HealthCheckStatus.DOWN, zVersion, e.getMessage()); + cassandraHealthInfo = new org.openecomp.sdc.health.data.HealthInfo(MonitoredModules.CAS, HealthCheckStatus.DOWN, zVersion, + e.getMessage()); } return Arrays.asList(zeHealthInfo, beHealthInfo, cassandraHealthInfo); } - - } - diff --git a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManager.java b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManager.java index a7e8ca549d..d5e8ce0342 100644 --- a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManager.java +++ b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManager.java @@ -15,29 +15,25 @@ */ package org.openecomp.sdc.itempermissions; -import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; - import java.util.Collection; import java.util.Optional; import java.util.Set; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; /** * Created by ayalaben on 6/18/2017. */ public interface PermissionsManager { - Collection listItemPermissions(String itemId); - - Set listUserPermittedItems(String userId, String permission); - - void updateItemPermissions(String itemId, String permission, Set addedUsersIds, - Set removedUsersIds); + Collection listItemPermissions(String itemId); - boolean isAllowed(String itemId, String userId, String action); + Set listUserPermittedItems(String userId, String permission); - Optional getUserItemPermission(String itemId, String userId); + void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds); - void deleteItemPermissions(String itemId); + boolean isAllowed(String itemId, String userId, String action); + Optional getUserItemPermission(String itemId, String userId); + void deleteItemPermissions(String itemId); } diff --git a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManagerFactory.java b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManagerFactory.java index 0353e5ce03..f37ccf9214 100644 --- a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/PermissionsManagerFactory.java @@ -21,10 +21,9 @@ import org.openecomp.core.factory.api.AbstractFactory; /** * Created by ayalaben on 6/18/2017. */ -public abstract class PermissionsManagerFactory extends - AbstractComponentFactory { +public abstract class PermissionsManagerFactory extends AbstractComponentFactory { - public static PermissionsManagerFactory getInstance() { - return AbstractFactory.getInstance(PermissionsManagerFactory.class); - } + public static PermissionsManagerFactory getInstance() { + return AbstractFactory.getInstance(PermissionsManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerFactoryImpl.java index 14539b0fa1..3848b7c9a4 100644 --- a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.itempermissions.dao.impl; import org.openecomp.sdc.itempermissions.PermissionsManager; @@ -28,11 +27,9 @@ import org.openecomp.sdc.versioning.AsdcItemManagerFactory; */ public class PermissionsManagerFactoryImpl extends PermissionsManagerFactory { - private static final PermissionsManager INSTANCE = - new PermissionsManagerImpl(PermissionsServicesFactory.getInstance().createInterface(), - AsdcItemManagerFactory.getInstance().createInterface(), - NotificationPropagationManagerFactory.getInstance().createInterface(), - SubscriptionServiceFactory.getInstance().createInterface()); + private static final PermissionsManager INSTANCE = new PermissionsManagerImpl(PermissionsServicesFactory.getInstance().createInterface(), + AsdcItemManagerFactory.getInstance().createInterface(), NotificationPropagationManagerFactory.getInstance().createInterface(), + SubscriptionServiceFactory.getInstance().createInterface()); @Override public PermissionsManager createInterface() { diff --git a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerImpl.java b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerImpl.java index 90b39bea6f..68edb21fd8 100644 --- a/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-item-permissions-manager/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsManagerImpl.java @@ -13,9 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.itempermissions.dao.impl; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.ITEM_ID_PROP; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.ITEM_NAME_PROP; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_CHANGED; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_GRANTED; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_ITEM; +import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.PERMISSION_USER; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -33,158 +44,130 @@ import org.openecomp.sdc.notification.services.SubscriptionService; import org.openecomp.sdc.versioning.AsdcItemManager; import org.openecomp.sdc.versioning.types.Item; -import java.util.*; - -import static org.openecomp.sdc.itempermissions.notifications.NotificationConstants.*; - /** * Created by ayalaben on 6/18/2017. */ public class PermissionsManagerImpl implements PermissionsManager { - private static final Logger LOGGER = LoggerFactory.getLogger(PermissionsManagerImpl.class); - private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; - - private PermissionsServices permissionsServices; - private AsdcItemManager asdcItemManager; - private NotificationPropagationManager notifier; - private SubscriptionService subscriptionService; - - public PermissionsManagerImpl(PermissionsServices permissionsServices, - AsdcItemManager asdcItemManager, - NotificationPropagationManager notificationPropagationManager, - SubscriptionService subscriptionService) { - this.permissionsServices = permissionsServices; - this.asdcItemManager = asdcItemManager; - this.notifier = notificationPropagationManager; - this.subscriptionService = subscriptionService; - } - - @Override - public Collection listItemPermissions(String itemId) { - - return permissionsServices.listItemPermissions(itemId); - } - - @Override - public Set listUserPermittedItems(String userId, String permission) { - return permissionsServices.listUserPermittedItems(userId,permission); - } - - @Override - public void updateItemPermissions(String itemId, String permission, Set addedUsersIds, - Set removedUsersIds) { - - String currentUser = - SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId(); - - if (!permissionsServices.isAllowed(itemId, currentUser, CHANGE_PERMISSIONS)) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(Messages.PERMISSIONS_ERROR.getErrorMessage()) - .withId(Messages.PERMISSIONS_ERROR.name()) - .withCategory(ErrorCategory.SECURITY).build()); + private static final Logger LOGGER = LoggerFactory.getLogger(PermissionsManagerImpl.class); + private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; + private PermissionsServices permissionsServices; + private AsdcItemManager asdcItemManager; + private NotificationPropagationManager notifier; + private SubscriptionService subscriptionService; + + public PermissionsManagerImpl(PermissionsServices permissionsServices, AsdcItemManager asdcItemManager, + NotificationPropagationManager notificationPropagationManager, SubscriptionService subscriptionService) { + this.permissionsServices = permissionsServices; + this.asdcItemManager = asdcItemManager; + this.notifier = notificationPropagationManager; + this.subscriptionService = subscriptionService; } - if (permission.equals(PermissionTypes.Owner.name()) ){ - if (addedUsersIds.size() == 1){ - asdcItemManager.updateOwner(itemId,addedUsersIds.iterator().next()); - } else { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(Messages.PERMISSIONS_OWNER_ERROR.getErrorMessage()) - .withId(Messages.PERMISSIONS_OWNER_ERROR.name()) - .withCategory(ErrorCategory.SECURITY).build()); - } + @Override + public Collection listItemPermissions(String itemId) { + return permissionsServices.listItemPermissions(itemId); } - permissionsServices - .updateItemPermissions(itemId, permission, addedUsersIds, removedUsersIds); - - sendNotifications(itemId, permission, addedUsersIds, removedUsersIds, currentUser); - } - - private void sendNotifications(String itemId, String permission, Set addedUsersIds, - Set removedUsersIds, String userName) { - - Item item = asdcItemManager.get(itemId); - addedUsersIds.forEach(affectedUser -> { - notifyUser(userName, true, item.getName(), itemId, affectedUser, permission); - subscriptionService.subscribe(affectedUser, itemId); - }); - removedUsersIds.forEach(affectedUser -> { - notifyUser(userName, false, item.getName(), itemId, affectedUser, permission); - subscriptionService.unsubscribe(affectedUser, itemId); - }); - - } - - private void notifyUser(String userName, boolean granted, String itemName, String itemId, - String affectedUser, String permission) { - Map details = new HashMap<>(); - details.put(PERMISSION_ITEM, permission); - details.put(ITEM_ID_PROP, itemId); - details.put(ITEM_NAME_PROP, itemName); - details.put(PERMISSION_GRANTED, granted); - details.put(PERMISSION_USER, userName); - PermissionEvent permissionEvent = new PermissionEvent(PERMISSION_CHANGED, affectedUser, - details, affectedUser); - - try { - notifier.directNotification(permissionEvent, affectedUser); - } catch (Exception e) { - LOGGER.error("Failed to send notification on permission changed for user '" + - affectedUser + "'"); + @Override + public Set listUserPermittedItems(String userId, String permission) { + return permissionsServices.listUserPermittedItems(userId, permission); } - } - - @Override - public boolean isAllowed(String itemId, String userId, String action) { - return permissionsServices.isAllowed(itemId, userId, action); - } - - @Override - public Optional getUserItemPermission(String itemId, String userId) { - return permissionsServices.getUserItemPermission(itemId, userId); - } - - @Override - public void deleteItemPermissions(String itemId) { - permissionsServices.deleteItemPermissions(itemId); - } - - private class PermissionEvent implements Event { + @Override + public void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds) { + String currentUser = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId(); + if (!permissionsServices.isAllowed(itemId, currentUser, CHANGE_PERMISSIONS)) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withMessage(Messages.PERMISSIONS_ERROR.getErrorMessage()).withId(Messages.PERMISSIONS_ERROR.name()) + .withCategory(ErrorCategory.SECURITY).build()); + } + if (permission.equals(PermissionTypes.Owner.name())) { + if (addedUsersIds.size() == 1) { + asdcItemManager.updateOwner(itemId, addedUsersIds.iterator().next()); + } else { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(Messages.PERMISSIONS_OWNER_ERROR.getErrorMessage()) + .withId(Messages.PERMISSIONS_OWNER_ERROR.name()).withCategory(ErrorCategory.SECURITY).build()); + } + } + permissionsServices.updateItemPermissions(itemId, permission, addedUsersIds, removedUsersIds); + sendNotifications(itemId, permission, addedUsersIds, removedUsersIds, currentUser); + } - private String eventType; - private String originatorId; - private Map attributes; - private String entityId; + private void sendNotifications(String itemId, String permission, Set addedUsersIds, Set removedUsersIds, String userName) { + Item item = asdcItemManager.get(itemId); + addedUsersIds.forEach(affectedUser -> { + notifyUser(userName, true, item.getName(), itemId, affectedUser, permission); + subscriptionService.subscribe(affectedUser, itemId); + }); + removedUsersIds.forEach(affectedUser -> { + notifyUser(userName, false, item.getName(), itemId, affectedUser, permission); + subscriptionService.unsubscribe(affectedUser, itemId); + }); + } - private PermissionEvent(String eventType, String originatorId, - Map attributes, String entityId) { - this.eventType = eventType; - this.originatorId = originatorId; - this.attributes = attributes; - this.entityId = entityId; + private void notifyUser(String userName, boolean granted, String itemName, String itemId, String affectedUser, String permission) { + Map details = new HashMap<>(); + details.put(PERMISSION_ITEM, permission); + details.put(ITEM_ID_PROP, itemId); + details.put(ITEM_NAME_PROP, itemName); + details.put(PERMISSION_GRANTED, granted); + details.put(PERMISSION_USER, userName); + PermissionEvent permissionEvent = new PermissionEvent(PERMISSION_CHANGED, affectedUser, details, affectedUser); + try { + notifier.directNotification(permissionEvent, affectedUser); + } catch (Exception e) { + LOGGER.error("Failed to send notification on permission changed for user '" + affectedUser + "'"); + } } @Override - public String getEventType() { - return eventType; + public boolean isAllowed(String itemId, String userId, String action) { + return permissionsServices.isAllowed(itemId, userId, action); } @Override - public String getOriginatorId() { - return originatorId; + public Optional getUserItemPermission(String itemId, String userId) { + return permissionsServices.getUserItemPermission(itemId, userId); } @Override - public Map getAttributes() { - return attributes; + public void deleteItemPermissions(String itemId) { + permissionsServices.deleteItemPermissions(itemId); } - @Override - public String getEntityId() { - return entityId; + private class PermissionEvent implements Event { + + private String eventType; + private String originatorId; + private Map attributes; + private String entityId; + + private PermissionEvent(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; + } + + @Override + public String getOriginatorId() { + return originatorId; + } + + @Override + public Map getAttributes() { + return attributes; + } + + @Override + public String getEntityId() { + return entityId; + } } - } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java index 56a4965381..4627fcee14 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookie.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.util.Set; - -public class AuthenticationCookie { +public class AuthenticationCookie { private String userID; private Set roles; private long maxSessionTime; private long currentSessionTime; - public AuthenticationCookie(){ } + public AuthenticationCookie() { + } - public AuthenticationCookie(AuthenticationCookie authenticationCookie){ + public AuthenticationCookie(AuthenticationCookie authenticationCookie) { this.userID = authenticationCookie.userID; this.roles = authenticationCookie.roles; this.maxSessionTime = authenticationCookie.maxSessionTime; @@ -41,10 +40,11 @@ public class AuthenticationCookie { /** * Create new cookie with max_session_time and current_session_time started with same value + * * @param userId */ public AuthenticationCookie(String userId) { - this.userID =userId; + this.userID = userId; long currentTimeMilliSec = System.currentTimeMillis(); this.maxSessionTime = currentTimeMilliSec; this.currentSessionTime = currentTimeMilliSec; @@ -74,7 +74,6 @@ public class AuthenticationCookie { this.maxSessionTime = maxSessionTime; } - public long getCurrentSessionTime() { return currentSessionTime; } @@ -85,14 +84,22 @@ public class AuthenticationCookie { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuthenticationCookie)) return false; - + if (this == o) { + return true; + } + if (!(o instanceof AuthenticationCookie)) { + return false; + } AuthenticationCookie that = (AuthenticationCookie) o; - - if (getMaxSessionTime() != that.getMaxSessionTime()) return false; - if (getCurrentSessionTime() != that.getCurrentSessionTime()) return false; - if (getUserID() != null ? !getUserID().equals(that.getUserID()) : that.getUserID() != null) return false; + if (getMaxSessionTime() != that.getMaxSessionTime()) { + return false; + } + if (getCurrentSessionTime() != that.getCurrentSessionTime()) { + return false; + } + if (getUserID() != null ? !getUserID().equals(that.getUserID()) : that.getUserID() != null) { + return false; + } return getRoles() != null ? getRoles().containsAll(that.getRoles()) : that.getRoles() == null; } @@ -107,11 +114,7 @@ public class AuthenticationCookie { @Override public String toString() { - return "AuthenticationCookie{" + - "userID='" + userID + '\'' + - ", roles=" + roles + - ", maxSessionTime=" + maxSessionTime + - ", currentSessionTime=" + currentSessionTime + - '}'; + return "AuthenticationCookie{" + "userID='" + userID + '\'' + ", roles=" + roles + ", maxSessionTime=" + maxSessionTime + + ", currentSessionTime=" + currentSessionTime + '}'; } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java index f0a33da8a7..d71c8593f3 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/AuthenticationCookieUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; +import java.io.IOException; +import javax.servlet.http.Cookie; import org.openecomp.sdc.securityutil.filters.SessionValidationFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.http.Cookie; -import java.io.IOException; - public class AuthenticationCookieUtils { private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); @@ -43,10 +41,12 @@ public class AuthenticationCookieUtils { * @throws CipherUtilException * @throws IOException */ - public static Cookie updateSessionTime(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) throws CipherUtilException, IOException { + public static Cookie updateSessionTime(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) + throws CipherUtilException, IOException { AuthenticationCookie authenticationCookie = getAuthenticationCookie(cookie, filterConfiguration); long newTime = System.currentTimeMillis(); - log.debug("SessionValidationFilter: Going to set new session time in cookie, old value: {}, new value: {}", authenticationCookie.getCurrentSessionTime(), newTime); + log.debug("SessionValidationFilter: Going to set new session time in cookie, old value: {}, new value: {}", + authenticationCookie.getCurrentSessionTime(), newTime); authenticationCookie.setCurrentSessionTime(newTime); String encryptedCookie = getEncryptedCookie(authenticationCookie, filterConfiguration); return createUpdatedCookie(cookie, encryptedCookie, filterConfiguration); @@ -54,13 +54,14 @@ public class AuthenticationCookieUtils { /** * Create new Cookie object with same attributes as original cookie + * * @param cookie * @param encryptedCookie * @param cookieConfiguration * @return */ public static Cookie createUpdatedCookie(Cookie cookie, String encryptedCookie, ISessionValidationCookieConfiguration cookieConfiguration) { - Cookie updatedCookie = new Cookie(cookie.getName(), encryptedCookie ); + Cookie updatedCookie = new Cookie(cookie.getName(), encryptedCookie); updatedCookie.setSecure(true); updatedCookie.setPath(cookieConfiguration.getCookiePath()); updatedCookie.setDomain(cookieConfiguration.getCookieDomain()); @@ -77,7 +78,8 @@ public class AuthenticationCookieUtils { * @throws IOException * @throws CipherUtilException */ - public static String getEncryptedCookie(AuthenticationCookie authenticationCookie, ISessionValidationFilterConfiguration filterConfiguration) throws IOException, CipherUtilException { + public static String getEncryptedCookie(AuthenticationCookie authenticationCookie, ISessionValidationFilterConfiguration filterConfiguration) + throws IOException, CipherUtilException { String changedCookieJson = RepresentationUtils.toRepresentation(authenticationCookie); return CipherUtil.encryptPKC(changedCookieJson, filterConfiguration.getSecurityKey()); } @@ -90,7 +92,8 @@ public class AuthenticationCookieUtils { * @return * @throws CipherUtilException */ - public static AuthenticationCookie getAuthenticationCookie(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) throws CipherUtilException { + public static AuthenticationCookie getAuthenticationCookie(Cookie cookie, ISessionValidationFilterConfiguration filterConfiguration) + throws CipherUtilException { String originalCookieJson = CipherUtil.decryptPKC(cookie.getValue(), filterConfiguration.getSecurityKey()); return RepresentationUtils.fromRepresentation(originalCookieJson, AuthenticationCookie.class); } @@ -108,7 +111,8 @@ public class AuthenticationCookieUtils { long sessionExpirationDate = authenticationCookie.getMaxSessionTime() + filterConfiguration.getMaxSessionTimeOut(); long sessionTime = authenticationCookie.getCurrentSessionTime(); long currentTime = System.currentTimeMillis(); - log.debug("SessionValidationFilter: Checking if session expired: session time: {}, expiration time: {}, current time: {}", sessionTime, sessionExpirationDate, currentTime); + log.debug("SessionValidationFilter: Checking if session expired: session time: {}, expiration time: {}, current time: {}", sessionTime, + sessionExpirationDate, currentTime); return currentTime > sessionExpirationDate || isSessionIdle(sessionTime, currentTime, filterConfiguration); } @@ -123,8 +127,8 @@ public class AuthenticationCookieUtils { private static boolean isSessionIdle(long sessionTimeValue, long currentTime, ISessionValidationFilterConfiguration filterConfiguration) { long currentIdleTime = currentTime - sessionTimeValue; long maxIdleTime = filterConfiguration.getSessionIdleTimeOut(); - log.debug("SessionValidationFilter: Checking if session idle: session time: {}, current idle time: {}, max idle time: {}", currentTime, currentIdleTime, maxIdleTime); + log.debug("SessionValidationFilter: Checking if session idle: session time: {}, current idle time: {}, max idle time: {}", currentTime, + currentIdleTime, maxIdleTime); return currentIdleTime >= maxIdleTime; } - } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java index 71ac6151f7..d69471e398 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtil.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.security.SecureRandom; @@ -31,18 +30,17 @@ import org.slf4j.LoggerFactory; public class CipherUtil { - private static Logger log = LoggerFactory.getLogger(CipherUtil.class.getName()); + public static final int GCM_TAG_LENGTH = 16; + public static final int GCM_IV_LENGTH = 12; private static final String ALGORITHM = "AES"; private static final String ALGORITHM_DETAILS = ALGORITHM + "/GCM/NoPadding"; private static final String CIPHER_PROVIDER = "SunJCE"; - - public static final int GCM_TAG_LENGTH = 16; - public static final int GCM_IV_LENGTH = 12; - private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ALGORITHM_NAME = "SHA1PRNG"; + private static Logger log = LoggerFactory.getLogger(CipherUtil.class.getName()); - private CipherUtil() {} + private CipherUtil() { + } /** * Encrypt the text using the secret key in key.properties file @@ -59,11 +57,9 @@ public class CipherUtil { cipher = Cipher.getInstance(ALGORITHM_DETAILS, CIPHER_PROVIDER); SecureRandom secureRandom = SecureRandom.getInstance(ALGORITHM_NAME); secureRandom.nextBytes(iv); - GCMParameterSpec spec = - new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, iv); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, iv); cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(base64key), spec); finalByte = cipher.doFinal(value.getBytes()); - } catch (Exception ex) { log.error("encrypt failed", ex); throw new CipherUtilException(ex); @@ -74,12 +70,10 @@ public class CipherUtil { /** * Decrypts the text using the secret key in key.properties file. * - * @param message The encrypted string that must be decrypted using the ONAP Portal Encryption - * Key + * @param message The encrypted string that must be decrypted using the ONAP Portal Encryption Key * @return The String decrypted * @throws CipherUtilException if any decryption step fails */ - public static String decryptPKC(String message, String base64key) throws CipherUtilException { byte[] encryptedMessage = Base64.decodeBase64(message); Cipher cipher; @@ -87,12 +81,10 @@ public class CipherUtil { try { cipher = Cipher.getInstance(ALGORITHM_DETAILS, CIPHER_PROVIDER); byte[] initVector = Arrays.copyOfRange(encryptedMessage, 0, GCM_IV_LENGTH); - GCMParameterSpec spec = - new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); + GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * java.lang.Byte.SIZE, initVector); byte[] realData = subarray(encryptedMessage, GCM_IV_LENGTH, encryptedMessage.length); cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(base64key), spec); decrypted = cipher.doFinal(realData); - } catch (Exception ex) { log.error("decrypt failed", ex); throw new CipherUtilException(ex); @@ -129,11 +121,9 @@ public class CipherUtil { if (startIndexInclusive < 0) { startIndexInclusive = 0; } - if (endIndexExclusive > array.length) { endIndexExclusive = array.length; } - int newSize = endIndexExclusive - startIndexInclusive; if (newSize <= 0) { return EMPTY_BYTE_ARRAY; diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java index 5b1a602b58..9e202de3c4 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/CipherUtilException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -42,5 +42,4 @@ public class CipherUtilException extends Exception { public CipherUtilException(Throwable cause) { super(cause); } - } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java index d684238db1..5371d0174f 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationCookieConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; /** - * Configuration for Cookie object , have to be same over all components of application + * Configuration for Cookie object , have to be same over all components of application */ public interface ISessionValidationCookieConfiguration { String getCookieName(); + String getCookieDomain(); + String getCookiePath(); + boolean isCookieHttpOnly(); } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java index ccae39423e..25e5683ebf 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/ISessionValidationFilterConfiguration.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import java.util.List; @@ -25,9 +24,12 @@ import java.util.List; public interface ISessionValidationFilterConfiguration extends ISessionValidationCookieConfiguration { String getSecurityKey(); + long getMaxSessionTimeOut(); + long getSessionIdleTimeOut(); // max idle time for session + String getRedirectURL(); - List getExcludedUrls(); // comma separated URLs, like this "/config,/configmgr,/rest,/kibanaProxy" -} + List getExcludedUrls(); // comma separated URLs, like this "/config,/configmgr,/rest,/kibanaProxy" +} diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java index e10bd81d0f..bbaece44a2 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/Passwords.java @@ -7,9 +7,9 @@ package org.openecomp.sdc.securityutil;/*- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,170 +18,171 @@ package org.openecomp.sdc.securityutil;/*- * ============LICENSE_END========================================================= */ -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Arrays; import java.util.Random; - +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class Passwords { - private static Logger log = LoggerFactory.getLogger( Passwords.class.getName()); - private static final Random RANDOM = new SecureRandom(); - private static final int SALT = 0; - private static final int HASH = 1; - private static final String HASH_ALGORITHM = "SHA-256"; - - /** - * static utility class - */ - private Passwords() { - } - - /** - * the method calculates a hash with a generated salt for the given password - * - * @param password - * @return a "salt:hash" value - */ - public static String hashPassword(String password) { - if (password!=null){ - byte[] salt = getNextSalt(); - byte byteData[] = hash(salt, password.getBytes()); - if (byteData != null) { - return toHex(salt) + ":" + toHex(byteData); - } - } - return null; - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param expectedHash - * @return - */ - public static boolean isExpectedPassword(String password, String expectedHash) { - if (password==null && expectedHash==null) - return true; - if (password==null || expectedHash==null) //iff exactly 1 is null - return false; - if (!expectedHash.contains(":")){ - log.error("invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + - "\t\t\t"); - return false; - } - String[] params = expectedHash.split(":"); - return isExpectedPassword(password, params[SALT], params[HASH]); - } - - /** - * the method checks if the given password matches the calculated hash - * - * @param password - * @param salt - * @param hash - * the hash generated using the salt - * @return true if the password matched the hash - */ - public static boolean isExpectedPassword(String password, String salt, String hash) { - if ( password == null && hash == null ) - return true; - if ( salt == null ){ - log.error("salt must be initialized"); - return false; - } - //unintialized params - if ( password == null || hash == null ) - return false; - byte[] saltBytes = fromHex(salt); - byte[] hashBytes = fromHex(hash); - - byte byteData[] = hash(saltBytes, password.getBytes()); - if (byteData != null) { - return Arrays.equals(byteData, hashBytes); - } - return false; - } - - public static void main(String[] args) { - if (args.length > 1 || args.length > 0) { - System.out.println("[" + hashPassword(args[0]) + "]"); - } else { - System.out.println("no passward passed."); - } - - } - - /** - * Returns a random salt to be used to hash a password. - * - * @return a 16 bytes random salt - */ - private static byte[] getNextSalt() { - byte[] salt = new byte[16]; - RANDOM.nextBytes(salt); - return salt; - } - - /** - * hase's the salt and value using the chosen algorithm - * - * @param salt - * @param password - * @return an array of bytes resulting from the hash - */ - private static byte[] hash(byte[] salt, byte[] password) { - MessageDigest md; - byte[] byteData = null; - try { - md = MessageDigest.getInstance(HASH_ALGORITHM); - md.update(salt); - md.update(password); - byteData = md.digest(); - } catch (NoSuchAlgorithmException e) { - System.out.println("invalid algorithm name"); - } - return byteData; - } - - /** - * Converts a string of hexadecimal characters into a byte array. - * - * @param hex - * the hex string - * @return the hex string decoded into a byte array - */ - private static byte[] fromHex(String hex) { - if ( hex == null ) - return null; - byte[] binary = new byte[hex.length() / 2]; - for (int i = 0; i < binary.length; i++) { - binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); - } - return binary; - } - - /** - * Converts a byte array into a hexadecimal string. - * - * @param array - * the byte array to convert - * @return a length*2 character string encoding the byte array - */ - private static String toHex(byte[] array) { - BigInteger bi = new BigInteger(1, array); - String hex = bi.toString(16); - int paddingLength = (array.length * 2) - hex.length(); - if (paddingLength > 0) - return String.format("%0" + paddingLength + "d", 0) + hex; - else - return hex; - } + private static final Random RANDOM = new SecureRandom(); + private static final int SALT = 0; + private static final int HASH = 1; + private static final String HASH_ALGORITHM = "SHA-256"; + private static Logger log = LoggerFactory.getLogger(Passwords.class.getName()); + + /** + * static utility class + */ + private Passwords() { + } + + /** + * the method calculates a hash with a generated salt for the given password + * + * @param password + * @return a "salt:hash" value + */ + public static String hashPassword(String password) { + if (password != null) { + byte[] salt = getNextSalt(); + byte byteData[] = hash(salt, password.getBytes()); + if (byteData != null) { + return toHex(salt) + ":" + toHex(byteData); + } + } + return null; + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param expectedHash + * @return + */ + public static boolean isExpectedPassword(String password, String expectedHash) { + if (password == null && expectedHash == null) { + return true; + } + if (password == null || expectedHash == null) //iff exactly 1 is null + { + return false; + } + if (!expectedHash.contains(":")) { + log.error( + "invalid password expecting hash at the prefix of the password (ex. e0277df331f4ff8f74752ac4a8fbe03b:6dfbad308cdf53c9ff2ee2dca811ee92f1b359586b33027580e2ff92578edbd0)\n" + + "\t\t\t"); + return false; + } + String[] params = expectedHash.split(":"); + return isExpectedPassword(password, params[SALT], params[HASH]); + } + + /** + * the method checks if the given password matches the calculated hash + * + * @param password + * @param salt + * @param hash the hash generated using the salt + * @return true if the password matched the hash + */ + public static boolean isExpectedPassword(String password, String salt, String hash) { + if (password == null && hash == null) { + return true; + } + if (salt == null) { + log.error("salt must be initialized"); + return false; + } + //unintialized params + if (password == null || hash == null) { + return false; + } + byte[] saltBytes = fromHex(salt); + byte[] hashBytes = fromHex(hash); + byte byteData[] = hash(saltBytes, password.getBytes()); + if (byteData != null) { + return Arrays.equals(byteData, hashBytes); + } + return false; + } + + public static void main(String[] args) { + if (args.length > 1 || args.length > 0) { + System.out.println("[" + hashPassword(args[0]) + "]"); + } else { + System.out.println("no passward passed."); + } + } + + /** + * Returns a random salt to be used to hash a password. + * + * @return a 16 bytes random salt + */ + private static byte[] getNextSalt() { + byte[] salt = new byte[16]; + RANDOM.nextBytes(salt); + return salt; + } + + /** + * hase's the salt and value using the chosen algorithm + * + * @param salt + * @param password + * @return an array of bytes resulting from the hash + */ + private static byte[] hash(byte[] salt, byte[] password) { + MessageDigest md; + byte[] byteData = null; + try { + md = MessageDigest.getInstance(HASH_ALGORITHM); + md.update(salt); + md.update(password); + byteData = md.digest(); + } catch (NoSuchAlgorithmException e) { + System.out.println("invalid algorithm name"); + } + return byteData; + } + + /** + * Converts a string of hexadecimal characters into a byte array. + * + * @param hex the hex string + * @return the hex string decoded into a byte array + */ + private static byte[] fromHex(String hex) { + if (hex == null) { + return null; + } + byte[] binary = new byte[hex.length() / 2]; + for (int i = 0; i < binary.length; i++) { + binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16); + } + return binary; + } + + /** + * Converts a byte array into a hexadecimal string. + * + * @param array the byte array to convert + * @return a length*2 character string encoding the byte array + */ + private static String toHex(byte[] array) { + BigInteger bi = new BigInteger(1, array); + String hex = bi.toString(16); + int paddingLength = (array.length * 2) - hex.length(); + if (paddingLength > 0) { + return String.format("%0" + paddingLength + "d", 0) + hex; + } else { + return hex; + } + } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java index 7fece5fda0..f47e61213e 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/RepresentationUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; - public class RepresentationUtils { private static final Logger log = LoggerFactory.getLogger(RepresentationUtils.class.getName()); @@ -41,7 +39,6 @@ public class RepresentationUtils { * @throws IOException */ public static String toRepresentation(T elementToRepresent) throws IOException { - ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); @@ -67,7 +64,6 @@ public class RepresentationUtils { } catch (Exception e) { log.error("Error when parsing JSON of object of type {}", clazz.getSimpleName(), e); } // return null in case of exception - return object; } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java index 30414e38b7..c5dbabfb30 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/FilterServletOutputStream.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; -import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.WriteListener; public class FilterServletOutputStream extends ServletOutputStream { @@ -38,12 +37,12 @@ public class FilterServletOutputStream extends ServletOutputStream { stream.write(b); } - public void write(byte[] b) throws IOException { + public void write(byte[] b) throws IOException { stream.write(b); } - public void write(byte[] b, int off, int len) throws IOException { - stream.write(b,off,len); + public void write(byte[] b, int off, int len) throws IOException { + stream.write(b, off, len); } @Override @@ -53,6 +52,5 @@ public class FilterServletOutputStream extends ServletOutputStream { @Override public void setWriteListener(WriteListener writeListener) { - } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java index dd4576e811..5ef821e542 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/ResponceWrapper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; +import java.io.ByteArrayOutputStream; +import java.io.PrintWriter; import javax.servlet.ServletOutputStream; -import javax.servlet.WriteListener; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayWriter; -import java.io.IOException; -import java.io.PrintWriter; public class ResponceWrapper extends HttpServletResponseWrapper { + private ByteArrayOutputStream output; private int contentLength; private String contentType; @@ -51,23 +48,21 @@ public class ResponceWrapper extends HttpServletResponseWrapper { return new PrintWriter(getOutputStream(), true); } + public int getContentLength() { + return contentLength; + } + public void setContentLength(int length) { this.contentLength = length; super.setContentLength(length); } - public int getContentLength() { - return contentLength; + public String getContentType() { + return contentType; } public void setContentType(String type) { this.contentType = type; super.setContentType(type); } - - - public String getContentType() { - return contentType; - - } } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java index e54a08af6f..81cc4cd49d 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SampleFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; - -import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; - -import javax.servlet.http.Cookie; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.servlet.http.Cookie; +import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; public class SampleFilter extends SessionValidationFilter { + @Override + public ISessionValidationFilterConfiguration getFilterConfiguration() { + return Configuration.getInstance(); + } + + @Override + protected Cookie addRoleToCookie(Cookie updatedCookie) { + return updatedCookie; + } + + @Override + protected boolean isRoleValid(Cookie cookie) { + return true; + } + private static class Configuration implements ISessionValidationFilterConfiguration { private static Configuration instance; - private String securityKey; private long maxSessionTimeOut; private long sessionIdleTimeOut; private String redirectURL; private List excludedUrls; - private String cookieName; private String cookieDomain; private String cookiePath; @@ -48,40 +58,19 @@ public class SampleFilter extends SessionValidationFilter { private Configuration() { //security key should be exactly 16 characters long clear text and then encoded to base64 this.securityKey = "AGLDdG4D04BKm2IxIWEr8o=="; - this.maxSessionTimeOut = 24L*60L*60L*1000L; - this.sessionIdleTimeOut = 60L*60L*1000L; + this.maxSessionTimeOut = 24L * 60L * 60L * 1000L; + this.sessionIdleTimeOut = 60L * 60L * 1000L; this.redirectURL = "https://www.e-access.att.com/ecomp_portal_ist/ecompportal/process_csp"; - this.excludedUrls = new ArrayList<>(Arrays.asList("/config","/configmgr","/rest","/kibanaProxy","/healthcheck","/upload.*")); - + this.excludedUrls = new ArrayList<>(Arrays.asList("/config", "/configmgr", "/rest", "/kibanaProxy", "/healthcheck", "/upload.*")); this.cookieName = "kuku"; this.cookieDomain = ""; this.cookiePath = "/"; this.isCookieHttpOnly = true; } - public void setSecurityKey(String securityKey) { - this.securityKey = securityKey; - } - - public void setMaxSessionTimeOut(long maxSessionTimeOut) { - this.maxSessionTimeOut = maxSessionTimeOut; - } - - public void setCookieName(String cookieName) { - this.cookieName = cookieName; - } - - public void setRedirectURL(String redirectURL) { - this.redirectURL = redirectURL; - } - - public void setExcludedUrls(List excludedUrls) { - this.excludedUrls = excludedUrls; - } - - public static Configuration getInstance(){ - if (instance == null ){ - instance = new Configuration(); + public static Configuration getInstance() { + if (instance == null) { + instance = new Configuration(); } return instance; } @@ -91,11 +80,19 @@ public class SampleFilter extends SessionValidationFilter { return securityKey; } + public void setSecurityKey(String securityKey) { + this.securityKey = securityKey; + } + @Override public long getMaxSessionTimeOut() { return maxSessionTimeOut; } + public void setMaxSessionTimeOut(long maxSessionTimeOut) { + this.maxSessionTimeOut = maxSessionTimeOut; + } + @Override public long getSessionIdleTimeOut() { return sessionIdleTimeOut; @@ -106,6 +103,10 @@ public class SampleFilter extends SessionValidationFilter { return cookieName; } + public void setCookieName(String cookieName) { + this.cookieName = cookieName; + } + @Override public String getCookieDomain() { return cookieDomain; @@ -126,27 +127,17 @@ public class SampleFilter extends SessionValidationFilter { return redirectURL; } + public void setRedirectURL(String redirectURL) { + this.redirectURL = redirectURL; + } + @Override public List getExcludedUrls() { return excludedUrls; } - } - - @Override - public ISessionValidationFilterConfiguration getFilterConfiguration() { - return Configuration.getInstance(); - } - - @Override - protected Cookie addRoleToCookie(Cookie updatedCookie) { - return updatedCookie; - } - @Override - protected boolean isRoleValid(Cookie cookie) { - return true; + public void setExcludedUrls(List excludedUrls) { + this.excludedUrls = excludedUrls; + } } - } - - diff --git a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java index de235bff89..cf24874f38 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java +++ b/openecomp-be/backend/openecomp-sdc-security-util/src/main/java/org/openecomp/sdc/securityutil/filters/SessionValidationFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.securityutil.filters; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.securityutil.AuthenticationCookieUtils; -import org.openecomp.sdc.securityutil.CipherUtilException; -import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.apache.commons.lang.StringUtils; - +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; @@ -38,33 +34,70 @@ import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; +import org.apache.commons.lang.StringUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.openecomp.sdc.securityutil.AuthenticationCookieUtils; +import org.openecomp.sdc.securityutil.CipherUtilException; +import org.openecomp.sdc.securityutil.ISessionValidationFilterConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; public abstract class SessionValidationFilter implements Filter { - private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); - private ISessionValidationFilterConfiguration filterConfiguration; - private List excludedUrls; + private static final Logger log = LoggerFactory.getLogger(SessionValidationFilter.class.getName()); private static final String REQUEST_ID = ONAPLogConstants.MDCs.REQUEST_ID; private static final String ONAP_REQUEST_ID_HEADER = ONAPLogConstants.Headers.REQUEST_ID; private static final String REQUEST_ID_HEADER = "X-RequestID"; private static final String TRANSACTION_ID_HEADER = "X-TransactionId"; private static final String ECOMP_REQUEST_ID_HEADER = "X-ECOMP-RequestID"; - private static final String PARTNER_NAME = ONAPLogConstants.MDCs.PARTNER_NAME; private static final String USER_ID_HEADER = "USER_ID"; private static final String ONAP_PARTNER_NAME_HEADER = ONAPLogConstants.Headers.PARTNER_NAME; private static final String USER_AGENT_HEADER = "User-Agent"; private static final String UNKNOWN = "UNKNOWN"; + private ISessionValidationFilterConfiguration filterConfiguration; + private List excludedUrls; + public static void fillMDCFromHeaders(HttpServletRequest httpServletRequest) { + fillRequestIdFromHeader(httpServletRequest); + fillPartnerNameFromHeader(httpServletRequest); + } + + private static void fillRequestIdFromHeader(HttpServletRequest httpServletRequest) { + if (MDC.get(REQUEST_ID) == null) { + if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(REQUEST_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(TRANSACTION_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(TRANSACTION_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER))) { + MDC.put(REQUEST_ID, httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER)); + } else { + MDC.put(REQUEST_ID, UUID.randomUUID().toString()); + } + } + } + + private static void fillPartnerNameFromHeader(HttpServletRequest httpServletRequest) { + if (MDC.get(PARTNER_NAME) == null) { + if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_ID_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_ID_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER)); + } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_AGENT_HEADER))) { + MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_AGENT_HEADER)); + } else { + MDC.put(PARTNER_NAME, UNKNOWN); + } + } + } public abstract ISessionValidationFilterConfiguration getFilterConfiguration(); + protected abstract Cookie addRoleToCookie(Cookie updatedCookie); + protected abstract boolean isRoleValid(Cookie cookie); @Override @@ -74,52 +107,52 @@ public abstract class SessionValidationFilter implements Filter { } @Override - public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + public final void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; final HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; - long startTime = System.nanoTime(); fillMDCFromHeaders(httpRequest); log.debug("SessionValidationFilter: Validation started, received request with URL {}", httpRequest.getRequestURL()); - // request preprocessing boolean isContinueProcessing = preProcessingRequest(servletRequest, servletResponse, filterChain, httpRequest, httpResponse, startTime); List cookies = null; Cookie extractedCookie = null; - // request processing if (isContinueProcessing) { cookies = extractAuthenticationCookies(httpRequest.getCookies()); extractedCookie = cookies.get(0); isContinueProcessing = processRequest(httpRequest, httpResponse, extractedCookie); } - // response processing - if(isContinueProcessing){ - log.debug("SessionValidationFilter: Cookie from request {} is valid, passing request to session extension ...", httpRequest.getRequestURL()); + if (isContinueProcessing) { + log.debug("SessionValidationFilter: Cookie from request {} is valid, passing request to session extension ...", + httpRequest.getRequestURL()); Cookie updatedCookie = processResponse(extractedCookie); cleanResponceFromLeftoverCookies(httpResponse, cookies); log.debug("SessionValidationFilter: request {} passed all validations, passing request to endpoint ...", httpRequest.getRequestURL()); httpResponse.addCookie(updatedCookie); long durationSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); long durationMil = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); - log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), durationSec, durationMil); + log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), + durationSec, durationMil); filterChain.doFilter(servletRequest, httpResponse); } } - - private boolean preProcessingRequest(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, HttpServletRequest httpRequest, HttpServletResponse httpResponse, long startTime) throws IOException, ServletException { - + private boolean preProcessingRequest(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain, + HttpServletRequest httpRequest, HttpServletResponse httpResponse, long startTime) + throws IOException, ServletException { boolean isPreProcessingSucceeded = true; if (isUrlFromWhiteList(httpRequest)) { - log.debug("SessionValidationFilter: URL {} excluded from access validation , passing request to endpoint ... ", httpRequest.getRequestURL()); + log.debug("SessionValidationFilter: URL {} excluded from access validation , passing request to endpoint ... ", + httpRequest.getRequestURL()); long durationSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); long durationMil = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); - log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), durationSec, durationMil); + log.debug("SessionValidationFilter: Validation ended, running time for URL {} is: {} seconds {} miliseconds", httpRequest.getPathInfo(), + durationSec, durationMil); filterChain.doFilter(servletRequest, servletResponse); isPreProcessingSucceeded = false; - } else if (!isCookiePresent(httpRequest.getCookies())) { //redirect to portal app log.debug("SessionValidationFilter: Cookie from request {} is not valid, redirecting request to portal", httpRequest.getRequestURL()); @@ -130,7 +163,7 @@ public abstract class SessionValidationFilter implements Filter { } private boolean processRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Cookie cookie) throws IOException { - boolean isProcessSuccessful= true; + boolean isProcessSuccessful = true; try { if (AuthenticationCookieUtils.isSessionExpired(cookie, filterConfiguration)) { //redirect to portal app @@ -143,7 +176,6 @@ public abstract class SessionValidationFilter implements Filter { log.debug("SessionValidationFilter: Cookie decryption error : {}", e.getMessage(), e); isProcessSuccessful = false; } - if (!isRoleValid(cookie)) { //redirect to portal app log.debug("SessionValidationFilter: Role is not valid, redirecting request {} to portal", httpRequest.getRequestURL()); @@ -184,33 +216,32 @@ public abstract class SessionValidationFilter implements Filter { log.debug("SessionValidationFilter: Extracting authentication cookies, {} cookies in request", cookies.length); List authenticationCookies = Arrays.stream(cookies).filter(c -> isCookieNameMatch(actualCookieName, c)).collect(Collectors.toList()); log.debug("SessionValidationFilter: Extracted {} authentication cookies from request", authenticationCookies.size()); - if( authenticationCookies.size() > 1 ){ - authenticationCookies.forEach( cookie -> log.debug("SessionValidationFilter: Multiple cookies found cookie name, {} cookie value {}", cookie.getName(), cookie.getValue())); + if (authenticationCookies.size() > 1) { + authenticationCookies.forEach(cookie -> log + .debug("SessionValidationFilter: Multiple cookies found cookie name, {} cookie value {}", cookie.getName(), cookie.getValue())); } return authenticationCookies; } - // use contains for matching due issue with ecomp portal ( change cookie name, add prefix ), temp solution private boolean isCookieNameMatch(String actualCookieName, Cookie c) { return c.getName().contains(actualCookieName); } private boolean isUrlFromWhiteList(HttpServletRequest httpRequest) { - if (httpRequest.getPathInfo() == null){ + if (httpRequest.getPathInfo() == null) { final String servletPath = httpRequest.getServletPath().toLowerCase(); - log.debug("SessionValidationFilter: pathInfo is null, trying to check by servlet path white list validation -> ServletPath: {} ", servletPath); - return excludedUrls.stream(). - anyMatch( e -> servletPath.matches(e)); + log.debug("SessionValidationFilter: pathInfo is null, trying to check by servlet path white list validation -> ServletPath: {} ", + servletPath); + return excludedUrls.stream().anyMatch(e -> servletPath.matches(e)); } String pathInfo = httpRequest.getPathInfo().toLowerCase(); log.debug("SessionValidationFilter: white list validation -> PathInfo: {} ", pathInfo); - return excludedUrls.stream(). - anyMatch( e -> pathInfo.matches(e)); + return excludedUrls.stream().anyMatch(e -> pathInfo.matches(e)); } private void cleanResponceFromLeftoverCookies(HttpServletResponse httpResponse, List cookiesList) { - for (Cookie cookie:cookiesList){ + for (Cookie cookie : cookiesList) { Cookie cleanCookie = AuthenticationCookieUtils.createUpdatedCookie(cookie, null, filterConfiguration); cleanCookie.setMaxAge(0); log.debug("SessionValidationFilter Cleaning Cookie cookie name: {} added to responce", cleanCookie.getName()); @@ -218,45 +249,7 @@ public abstract class SessionValidationFilter implements Filter { } } - public static void fillMDCFromHeaders(HttpServletRequest httpServletRequest) { - fillRequestIdFromHeader(httpServletRequest); - fillPartnerNameFromHeader(httpServletRequest); - - } - - private static void fillRequestIdFromHeader(HttpServletRequest httpServletRequest){ - if (MDC.get(REQUEST_ID) == null) { - if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(ONAP_REQUEST_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(REQUEST_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(TRANSACTION_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(TRANSACTION_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER))) { - MDC.put(REQUEST_ID, httpServletRequest.getHeader(ECOMP_REQUEST_ID_HEADER)); - } else { - MDC.put(REQUEST_ID, UUID.randomUUID().toString()); - } - } - } - - private static void fillPartnerNameFromHeader(HttpServletRequest httpServletRequest){ - if (MDC.get(PARTNER_NAME) == null) { - if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_ID_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_ID_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(ONAP_PARTNER_NAME_HEADER)); - } else if (StringUtils.isNotEmpty(httpServletRequest.getHeader(USER_AGENT_HEADER))) { - MDC.put(PARTNER_NAME, httpServletRequest.getHeader(USER_AGENT_HEADER)); - } else { - MDC.put(PARTNER_NAME, UNKNOWN); - } - } - } - - @Override public void destroy() { - } } diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/UploadValidationManager.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/UploadValidationManager.java index 88aceeb87d..22f014742c 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/UploadValidationManager.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/UploadValidationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation; -import org.openecomp.sdc.validation.types.ValidationFileResponse; - import java.io.IOException; import java.io.InputStream; +import org.openecomp.sdc.validation.types.ValidationFileResponse; /** * Created by TALIO on 4/20/2016. */ public interface UploadValidationManager { - - ValidationFileResponse validateFile(String type, InputStream heatFileToUpload) throws IOException; - - + ValidationFileResponse validateFile(String type, InputStream heatFileToUpload) throws IOException; } diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java index 90f8ad369b..6a9015489b 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/impl/UploadValidationManagerImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.impl; import java.io.IOException; @@ -44,76 +43,60 @@ import org.openecomp.sdc.validation.UploadValidationManager; import org.openecomp.sdc.validation.types.ValidationFileResponse; import org.openecomp.sdc.validation.util.ValidationManagerUtil; - /** * Created by TALIO on 4/20/2016. */ public class UploadValidationManagerImpl implements UploadValidationManager { - private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData) throws IOException { - final Map zipFileAndByteMap; - try { - zipFileAndByteMap = ZipUtils.readZip(uploadFileData, true); - } catch (final ZipException e) { - throw new IOException(e); + private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData) throws IOException { + final Map zipFileAndByteMap; + try { + zipFileAndByteMap = ZipUtils.readZip(uploadFileData, true); + } catch (final ZipException e) { + throw new IOException(e); + } + final boolean zipHasFolders = zipFileAndByteMap.values().stream().anyMatch(Objects::isNull); + if (zipHasFolders) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) + .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()).withCategory(ErrorCategory.APPLICATION).build()); + } + final FileContentHandler mapFileContent = new FileContentHandler(); + zipFileAndByteMap.entrySet().stream().filter(entry -> entry.getValue() != null) + .forEach(zipEntry -> mapFileContent.addFile(zipEntry.getKey(), zipEntry.getValue())); + return mapFileContent; } - final boolean zipHasFolders = zipFileAndByteMap.values().stream().anyMatch(Objects::isNull); - if (zipHasFolders) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) - .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + @Override + public ValidationFileResponse validateFile(String type, InputStream fileToValidate) throws IOException { + ValidationFileResponse validationFileResponse = new ValidationFileResponse(); + HeatTreeManager tree; + ValidationStructureList validationStructureList = new ValidationStructureList(); + if (type.equalsIgnoreCase("heat")) { + FileContentHandler content = getFileContent(fileToValidate); + if (!content.containsFile(SdcCommon.MANIFEST_NAME)) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(Messages.MANIFEST_NOT_EXIST.getErrorMessage()) + .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()).withCategory(ErrorCategory.APPLICATION).build()); + } + Map> errors = validateHeatUploadData(content); + tree = HeatTreeManagerUtil.initHeatTreeManager(content); + tree.createTree(); + if (MapUtils.isNotEmpty(errors)) { + tree.addErrors(errors); + validationStructureList.setImportStructure(tree.getTree()); + } + } else { + throw new RuntimeException("invalid type:" + type); + } + validationFileResponse.setValidationData(validationStructureList); + return validationFileResponse; } - final FileContentHandler mapFileContent = new FileContentHandler(); - zipFileAndByteMap.entrySet().stream() - .filter(entry -> entry.getValue() != null) - .forEach(zipEntry -> mapFileContent.addFile(zipEntry.getKey(), zipEntry.getValue())); - - return mapFileContent; - } - - @Override - public ValidationFileResponse validateFile(String type, InputStream fileToValidate) - throws IOException { - ValidationFileResponse validationFileResponse = new ValidationFileResponse(); - - HeatTreeManager tree; - ValidationStructureList validationStructureList = new ValidationStructureList(); - if (type.equalsIgnoreCase("heat")) { - FileContentHandler content = getFileContent(fileToValidate); - if (!content.containsFile(SdcCommon.MANIFEST_NAME)) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.MANIFEST_NOT_EXIST.getErrorMessage()) - .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); - } - Map> errors = validateHeatUploadData(content); - tree = HeatTreeManagerUtil.initHeatTreeManager(content); - tree.createTree(); - - if (MapUtils.isNotEmpty(errors)) { - tree.addErrors(errors); - validationStructureList.setImportStructure(tree.getTree()); - } - } else { - throw new RuntimeException("invalid type:" + type); + private Map> validateHeatUploadData(FileContentHandler fileContentMap) { + ValidationManager validationManager = ValidationManagerUtil.initValidationManager(fileContentMap); + return validationManager.validate(); } - validationFileResponse.setValidationData(validationStructureList); - return validationFileResponse; - } - - private Map> validateHeatUploadData(FileContentHandler fileContentMap) { - ValidationManager validationManager = - ValidationManagerUtil.initValidationManager(fileContentMap); - return validationManager.validate(); - } - - private FileContentHandler getFileContent(InputStream is) throws IOException { - return getFileContentMapFromZip(FileUtils.toByteArray(is)); - - - } + private FileContentHandler getFileContent(InputStream is) throws IOException { + return getFileContentMapFromZip(FileUtils.toByteArray(is)); + } } diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileResponse.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileResponse.java index bf6923d3de..41de2b73a3 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileResponse.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.types; import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; public class ValidationFileResponse { - private ValidationStructureList validationData; - public ValidationStructureList getValidationData() { - return validationData; - } + private ValidationStructureList validationData; + + public ValidationStructureList getValidationData() { + return validationData; + } - public void setValidationData(ValidationStructureList validationData) { - this.validationData = validationData; - } + public void setValidationData(ValidationStructureList validationData) { + this.validationData = validationData; + } } diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileStatus.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileStatus.java index 4bf7be8b79..2ed4520f2a 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileStatus.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/types/ValidationFileStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.types; public enum ValidationFileStatus { - Success, - Failure + Success, Failure } diff --git a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java index 6a7466d20d..3117082419 100644 --- a/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java +++ b/openecomp-be/backend/openecomp-sdc-validation-manager/src/main/java/org/openecomp/sdc/validation/util/ValidationManagerUtil.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.util; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.validation.api.ValidationManager; @@ -25,42 +28,36 @@ import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; - - public class ValidationManagerUtil { - private ValidationManagerUtil(){} + private ValidationManagerUtil() { + } - /** - * Handle missing manifest. - * - * @param fileContentMap the file content map - * @param errors the errors - */ - public static void handleMissingManifest(FileContentHandler fileContentMap, - Map> errors) throws IOException { - try (InputStream manifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { - if (manifest == null) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); - } + /** + * Handle missing manifest. + * + * @param fileContentMap the file content map + * @param errors the errors + */ + public static void handleMissingManifest(FileContentHandler fileContentMap, Map> errors) throws IOException { + try (InputStream manifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + if (manifest == null) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); + } + } } - } - /** - * Init validation manager validation manager. - * - * @param fileContentMap the file content map - * @return the validation manager - */ - public static ValidationManager initValidationManager(FileContentHandler fileContentMap) { - ValidationManager validationManager = ValidationManagerFactory.getInstance().createInterface(); - fileContentMap.getFileList().forEach(fileName -> validationManager - .addFile(fileName, FileUtils.toByteArray(fileContentMap.getFileContentAsStream(fileName)))); - return validationManager; - } + /** + * Init validation manager validation manager. + * + * @param fileContentMap the file content map + * @return the validation manager + */ + public static ValidationManager initValidationManager(FileContentHandler fileContentMap) { + ValidationManager validationManager = ValidationManagerFactory.getInstance().createInterface(); + fileContentMap.getFileList() + .forEach(fileName -> validationManager.addFile(fileName, FileUtils.toByteArray(fileContentMap.getFileContentAsStream(fileName)))); + return validationManager; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManager.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManager.java index 60288b53c3..c5c93ae00c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,82 +17,80 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense; -import org.openecomp.sdc.vendorlicense.dao.types.*; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.util.Collection; import java.util.Set; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementModel; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; +import org.openecomp.sdc.versioning.dao.types.Version; public interface VendorLicenseManager { - void validate(String vendorLicenseModelId, Version version); - - VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity licenseModel); - - void updateVendorLicenseModel(VendorLicenseModelEntity licenseModel); - - VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); - - void deleteVendorLicenseModel(String vlmId, Version version); + void validate(String vendorLicenseModelId, Version version); + VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity licenseModel); - Collection listLicenseAgreements(String vlmId, Version version); + void updateVendorLicenseModel(VendorLicenseModelEntity licenseModel); - LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); + VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); - void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, - Set addedFeatureGroupIds, Set removedFeatureGroupIds); + void deleteVendorLicenseModel(String vlmId, Version version); - LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId); + Collection listLicenseAgreements(String vlmId, Version version); - void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId); + LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); + void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, Set addedFeatureGroupIds, Set removedFeatureGroupIds); - Collection listFeatureGroups(String vlmId, Version version); + LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, String licenseAgreementId); - FeatureGroupEntity createFeatureGroup(FeatureGroupEntity fg); + void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId); - void updateFeatureGroup(FeatureGroupEntity featureGroup, - Set addedLicenseKeyGroups, Set removedLicenseKeyGroups, - Set addedEntitlementPools, Set removedEntitlementPools); + Collection listFeatureGroups(String vlmId, Version version); - FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); + FeatureGroupEntity createFeatureGroup(FeatureGroupEntity fg); - void deleteFeatureGroup(FeatureGroupEntity featureGroup); + void updateFeatureGroup(FeatureGroupEntity featureGroup, Set addedLicenseKeyGroups, Set removedLicenseKeyGroups, + Set addedEntitlementPools, Set removedEntitlementPools); + FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); - Collection listEntitlementPools(String vlmId, Version version); + void deleteFeatureGroup(FeatureGroupEntity featureGroup); - EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); + Collection listEntitlementPools(String vlmId, Version version); - void updateEntitlementPool(EntitlementPoolEntity entitlementPool); + EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); - EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool); + void updateEntitlementPool(EntitlementPoolEntity entitlementPool); - void deleteEntitlementPool(EntitlementPoolEntity entitlementPool); + EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool); + void deleteEntitlementPool(EntitlementPoolEntity entitlementPool); - Collection listLicenseKeyGroups(String vlmId, Version version); + Collection listLicenseKeyGroups(String vlmId, Version version); - LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LimitEntity createLimit(LimitEntity limitEntity); + LimitEntity createLimit(LimitEntity limitEntity); - Collection listLimits(String vlmId, Version version, String epLkgId); + Collection listLimits(String vlmId, Version version, String epLkgId); - void deleteLimit(LimitEntity limitEntity); + void deleteLimit(LimitEntity limitEntity); - void updateLimit(LimitEntity limitEntity); + void updateLimit(LimitEntity limitEntity); - LimitEntity getLimit(LimitEntity entitlementPool); + LimitEntity getLimit(LimitEntity entitlementPool); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManagerFactory.java index 68ea919d22..fa05c03b5e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -26,10 +25,9 @@ import org.openecomp.core.factory.api.AbstractFactory; /** * Created by ayalaben on 8/3/2017 */ -public abstract class VendorLicenseManagerFactory extends - AbstractComponentFactory { +public abstract class VendorLicenseManagerFactory extends AbstractComponentFactory { - public static VendorLicenseManagerFactory getInstance() { - return AbstractFactory.getInstance(VendorLicenseManagerFactory.class); - } + public static VendorLicenseManagerFactory getInstance() { + return AbstractFactory.getInstance(VendorLicenseManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/errors/LimitErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/errors/LimitErrorBuilder.java index b2a155dc21..3c0463596a 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/errors/LimitErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/errors/LimitErrorBuilder.java @@ -13,38 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.errors; - import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; public class LimitErrorBuilder { - private static final String LIMIT_INVALID_ATTR_VALUE_MSG = "The %s value doesn't meet the " - + "expected attribute value."; - - private static final String DUPLICATE_LIMIT_NAME_NOT_ALLOWED_MSG = - "Invalid request, Limit with name %s already exists for type %s."; - - private LimitErrorBuilder(){ - - } - - public static ErrorCode getInvalidValueErrorBuilder(String attribute, String errorCode) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(errorCode); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(LIMIT_INVALID_ATTR_VALUE_MSG, attribute)); - return builder.build(); - } - - public static ErrorCode getDuplicateNameErrorbuilder(String name, String type) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorLicenseErrorCodes.DUPLICATE_LIMIT_NAME_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format (DUPLICATE_LIMIT_NAME_NOT_ALLOWED_MSG, name, type )); - return builder.build(); - } + private static final String LIMIT_INVALID_ATTR_VALUE_MSG = "The %s value doesn't meet the " + "expected attribute value."; + private static final String DUPLICATE_LIMIT_NAME_NOT_ALLOWED_MSG = "Invalid request, Limit with name %s already exists for type %s."; + + private LimitErrorBuilder() { + } + + public static ErrorCode getInvalidValueErrorBuilder(String attribute, String errorCode) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(errorCode); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(LIMIT_INVALID_ATTR_VALUE_MSG, attribute)); + return builder.build(); + } + + public static ErrorCode getDuplicateNameErrorbuilder(String name, String type) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VendorLicenseErrorCodes.DUPLICATE_LIMIT_NAME_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(DUPLICATE_LIMIT_NAME_NOT_ALLOWED_MSG, name, type)); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerFactoryImpl.java index ac7eb115b1..16a789bd8d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.impl; import org.openecomp.core.dao.UniqueValueDaoFactory; import org.openecomp.sdc.vendorlicense.VendorLicenseManager; import org.openecomp.sdc.vendorlicense.VendorLicenseManagerFactory; -import org.openecomp.sdc.vendorlicense.dao.*; +import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDaoFactory; +import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory; +import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; +import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDaoFactory; +import org.openecomp.sdc.vendorlicense.dao.LimitDaoFactory; +import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDaoFactory; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; /** * Created by ayalaben on 8/3/2017 */ public class VendorLicenseManagerFactoryImpl extends VendorLicenseManagerFactory { - private static final VendorLicenseManager INSTANCE = - new VendorLicenseManagerImpl( - VendorLicenseFacadeFactory.getInstance().createInterface(), - VendorLicenseModelDaoFactory.getInstance().createInterface(), - LicenseAgreementDaoFactory.getInstance().createInterface(), - FeatureGroupDaoFactory.getInstance().createInterface(), - EntitlementPoolDaoFactory.getInstance().createInterface(), - LicenseKeyGroupDaoFactory.getInstance().createInterface(), - LimitDaoFactory.getInstance().createInterface(), - UniqueValueDaoFactory.getInstance().createInterface()); - @Override - public VendorLicenseManager createInterface() { - return INSTANCE; - } + private static final VendorLicenseManager INSTANCE = new VendorLicenseManagerImpl(VendorLicenseFacadeFactory.getInstance().createInterface(), + VendorLicenseModelDaoFactory.getInstance().createInterface(), LicenseAgreementDaoFactory.getInstance().createInterface(), + FeatureGroupDaoFactory.getInstance().createInterface(), EntitlementPoolDaoFactory.getInstance().createInterface(), + LicenseKeyGroupDaoFactory.getInstance().createInterface(), LimitDaoFactory.getInstance().createInterface(), + UniqueValueDaoFactory.getInstance().createInterface()); + @Override + public VendorLicenseManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java index 6939eeed32..0fb5f58507 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-license-manager/src/main/java/org/openecomp/sdc/vendorlicense/impl/VendorLicenseManagerImpl.java @@ -13,9 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.impl; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.util.Collection; +import java.util.Optional; +import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.openecomp.core.dao.UniqueValueDao; import org.openecomp.core.util.UniqueValueUtil; @@ -45,596 +49,471 @@ import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.util.Collection; -import java.util.Optional; -import java.util.Set; - public class VendorLicenseManagerImpl implements VendorLicenseManager { - private UniqueValueUtil uniqueValueUtil; - private VendorLicenseFacade vendorLicenseFacade; - private VendorLicenseModelDao vendorLicenseModelDao; - private LicenseAgreementDao licenseAgreementDao; - private FeatureGroupDao featureGroupDao; - private EntitlementPoolDao entitlementPoolDao; - private LicenseKeyGroupDao licenseKeyGroupDao; - private LimitDao limitDao; - - private static final String EP_POOL_START_TIME = "T00:00:00Z"; - private static final String EP_POOL_EXPIRY_TIME = "T23:59:59Z"; - private static final DateTimeFormatter FORMATTER - = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); - public VendorLicenseManagerImpl(VendorLicenseFacade vendorLicenseFacade, - VendorLicenseModelDao vendorLicenseModelDao, - LicenseAgreementDao licenseAgreementDao, - FeatureGroupDao featureGroupDao, - EntitlementPoolDao entitlementPoolDao, - LicenseKeyGroupDao licenseKeyGroupDao, - LimitDao limitDao, - UniqueValueDao uniqueValueDao) { - this.vendorLicenseFacade = vendorLicenseFacade; - this.vendorLicenseModelDao = vendorLicenseModelDao; - this.licenseAgreementDao = licenseAgreementDao; - this.featureGroupDao = featureGroupDao; - this.entitlementPoolDao = entitlementPoolDao; - this.licenseKeyGroupDao = licenseKeyGroupDao; - this.limitDao = limitDao; - this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); - } - - - @Override - public void validate(String vendorLicenseModelId, Version version) { - vendorLicenseFacade.validate(vendorLicenseModelId, version); - } - - @Override - public VendorLicenseModelEntity createVendorLicenseModel( - VendorLicenseModelEntity vendorLicenseModelEntity) { - vendorLicenseModelDao.create(vendorLicenseModelEntity); - return vendorLicenseModelEntity; - } - - @Override - public void updateVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity) { - VendorLicenseModelEntity retrieved = vendorLicenseModelDao.get(vendorLicenseModelEntity); - if (retrieved == null){ - throw new CoreException((new ErrorCode.ErrorCodeBuilder() - .withMessage(String.format("Vlm with id %s and version %s does not exist.", - vendorLicenseModelEntity.getId(), vendorLicenseModelEntity.getVersion().getId()))).build()); - } - - String existingVendorName = retrieved.getVendorName(); - - updateUniqueName(VendorLicenseConstants.UniqueValues.VENDOR_NAME, existingVendorName, - vendorLicenseModelEntity.getVendorName()); - vendorLicenseModelDao.update(vendorLicenseModelEntity); - } - - @Override - public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { - return vendorLicenseFacade.getVendorLicenseModel(vlmId, version); - } - - @Override - public void deleteVendorLicenseModel(String vlmId, Version version) { - throw new UnsupportedOperationException(VendorLicenseConstants.UNSUPPORTED_OPERATION_ERROR); - } - - @Override - public Collection listLicenseAgreements(String vlmId, Version version) { - return licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, version, null)); - } - - @Override - public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { - return vendorLicenseFacade.createLicenseAgreement(licenseAgreement); - } - - @Override - public void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, - Set addedFeatureGroupIds, - Set removedFeatureGroupIds) { - LicenseAgreementEntity retrieved = licenseAgreementDao.get(licenseAgreement); - VersioningUtil - .validateEntityExistence(retrieved, licenseAgreement, VendorLicenseModelEntity.ENTITY_TYPE); - VersioningUtil.validateContainedEntitiesExistence(new FeatureGroupEntity().getEntityType(), - removedFeatureGroupIds, retrieved, retrieved.getFeatureGroupIds()); - VersioningUtil.validateEntitiesExistence(addedFeatureGroupIds, - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), - null), - featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); - - updateUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - retrieved.getName(), licenseAgreement.getName(), licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); - licenseAgreementDao.updateColumnsAndDeltaFeatureGroupIds(licenseAgreement, addedFeatureGroupIds, - removedFeatureGroupIds); - - addFeatureGroupsToLicenseAgreementRef(addedFeatureGroupIds, licenseAgreement); - removeFeatureGroupsToLicenseAgreementRef(removedFeatureGroupIds, licenseAgreement); - } - - @Override - public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId) { - return vendorLicenseFacade.getLicenseAgreementModel(vlmId, version, licenseAgreementId); - } - - @Override - public void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId) { - LicenseAgreementEntity input = - new LicenseAgreementEntity(vlmId, version, licenseAgreementId); - LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); - VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); - - removeFeatureGroupsToLicenseAgreementRef(retrieved.getFeatureGroupIds(), retrieved); - - licenseAgreementDao.delete(retrieved); - - deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - } - - @Override - public Collection listFeatureGroups(String vlmId, Version version) { - return vendorLicenseFacade.listFeatureGroups(vlmId, version); - } - - @Override - public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { - return vendorLicenseFacade.createFeatureGroup(featureGroup); - } - - @Override - public void updateFeatureGroup(FeatureGroupEntity featureGroup, - Set addedLicenseKeyGroups, - Set removedLicenseKeyGroups, - Set addedEntitlementPools, - Set removedEntitlementPools) { - FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); - VersioningUtil - .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); - - VersioningUtil.validateContainedEntitiesExistence(new LicenseKeyGroupEntity().getEntityType(), - removedLicenseKeyGroups, retrieved, retrieved.getLicenseKeyGroupIds()); - VersioningUtil.validateContainedEntitiesExistence(new EntitlementPoolEntity().getEntityType(), - removedEntitlementPools, retrieved, retrieved.getEntitlementPoolIds()); - - VersioningUtil.validateEntitiesExistence(addedLicenseKeyGroups, - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), - null), - licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); - VersioningUtil.validateEntitiesExistence(addedEntitlementPools, - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), - null), - entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE); - - updateUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - retrieved.getName(), featureGroup.getName(), featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - - addLicenseKeyGroupsToFeatureGroupsRef(addedLicenseKeyGroups, featureGroup); - removeLicenseKeyGroupsToFeatureGroupsRef(removedLicenseKeyGroups, featureGroup); - addEntitlementPoolsToFeatureGroupsRef(addedEntitlementPools, featureGroup); - removeEntitlementPoolsToFeatureGroupsRef(removedEntitlementPools, featureGroup); - - featureGroupDao.updateFeatureGroup(featureGroup, addedEntitlementPools, removedEntitlementPools, - addedLicenseKeyGroups, removedLicenseKeyGroups); - - } - - @Override - public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { - return vendorLicenseFacade.getFeatureGroupModel(featureGroup); - } - - @Override - public void deleteFeatureGroup(FeatureGroupEntity featureGroup) { - FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); - VersioningUtil - .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); - - removeLicenseKeyGroupsToFeatureGroupsRef(retrieved.getLicenseKeyGroupIds(), featureGroup); - removeEntitlementPoolsToFeatureGroupsRef(retrieved.getEntitlementPoolIds(), featureGroup); - - for (String licenceAgreementId : retrieved.getReferencingLicenseAgreements()) { - licenseAgreementDao.removeFeatureGroup( - new LicenseAgreementEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), - licenceAgreementId), featureGroup.getId()); - } - - featureGroupDao.delete(featureGroup); - - deleteUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - } - - @Override - public Collection listEntitlementPools(String vlmId, Version version) { - return vendorLicenseFacade.listEntitlementPools(vlmId, version); - } - - @Override - public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { - entitlementPool.setStartDate(getDate(entitlementPool.getStartDate(), EP_POOL_START_TIME)); - entitlementPool.setExpiryDate(getDate(entitlementPool.getExpiryDate(), EP_POOL_EXPIRY_TIME)); - validateCreateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), - entitlementPool.getVendorLicenseModelId()); - return vendorLicenseFacade.createEntitlementPool(entitlementPool); - } - - private String getDate(String date, String poolTime){ - return date != null ? (!date.trim().isEmpty() ? date + poolTime: null) : null; - } - - private void validateCreateDate(String startDate, String expiryDate, - String vendorLicenseModelId) { - //original logic allows both nulls - if(StringUtils.isEmpty(startDate) && StringUtils.isEmpty(expiryDate)){ - return; - } - - Optional parsedStartDate = parseLocalDate(startDate); - Optional parsedExpiryDate = parseLocalDate(expiryDate); - if (!parsedStartDate.isPresent()) { - throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); - } - - if (!parsedExpiryDate.isPresent() - && parsedStartDate.get().atStartOfDay().isBefore - (LocalDate.now().atStartOfDay())) { - throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); - } - - if(parsedExpiryDate.isPresent() && isNotValidatStartAndExpiryDate(parsedStartDate.get(), parsedExpiryDate.get())){ - throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); - } - } - - private boolean isNotValidatStartAndExpiryDate(LocalDate parsedStartDate, - LocalDate parsedExpiryDate) { - return parsedStartDate.atStartOfDay().isBefore(LocalDate.now().atStartOfDay()) - || parsedExpiryDate.atStartOfDay().isEqual(parsedStartDate.atStartOfDay()) - || parsedExpiryDate.isBefore(parsedStartDate); - } - - private static Optional parseLocalDate(String date) { - if (StringUtils.isEmpty(date)) { - return Optional.empty(); - } - - return Optional.of(LocalDate.parse(date, FORMATTER )); - } - - private void validateUpdateDate(String startDate, String expiryDate, - String vendorLicenseModelId) { - Optional parsedStartDate = parseLocalDate(startDate); - Optional parsedExpiryDate = parseLocalDate(expiryDate); - - if (parsedStartDate.isPresent() && parsedExpiryDate.isPresent() - && (parsedExpiryDate.get().atStartOfDay() - .isEqual(parsedStartDate.get().atStartOfDay()) - || parsedExpiryDate.get().isBefore(parsedStartDate.get() ))) { - throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); - } - - if (startDate == null && expiryDate != null) { - throw new CoreException( - new InvalidDateErrorBuilder(vendorLicenseModelId) - .build()); - } - } - - @Override - public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { - entitlementPool.setStartDate(getDate(entitlementPool.getStartDate(), EP_POOL_START_TIME)); - entitlementPool.setExpiryDate(getDate(entitlementPool.getExpiryDate(), EP_POOL_EXPIRY_TIME)); - validateUpdateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), - entitlementPool.getVendorLicenseModelId()); - vendorLicenseFacade.updateEntitlementPool(entitlementPool); - } - - @Override - public EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool) { - EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); - VersioningUtil - .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); - DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); - if (retrieved.getStartDate() != null) { - retrieved.setStartDate(LocalDate.parse(retrieved.getStartDate(), FORMATTER ).format - (targetFormatter)); - } - - if (retrieved.getExpiryDate() != null) { - retrieved.setExpiryDate(LocalDate.parse(retrieved.getExpiryDate(), FORMATTER ).format - (targetFormatter)); - } - return retrieved; - } - - @Override - public void deleteEntitlementPool(EntitlementPoolEntity entitlementPool) { - EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); - VersioningUtil - .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); - - for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { - featureGroupDao.removeEntitlementPool( - new FeatureGroupEntity(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion(), - referencingFeatureGroupId), entitlementPool.getId()); - } - - deleteChildLimits(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), - entitlementPool.getId()); - - entitlementPoolDao.delete(entitlementPool); - - deleteUniqueName(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - } - - protected void deleteChildLimits(String vlmId, Version version, String epLkgId) { - Optional> limitEntities = Optional.ofNullable( - listLimits(vlmId, version, epLkgId)); - limitEntities.ifPresent(entities -> entities.forEach(this::deleteLimit)); - } - - @Override - public Collection listLicenseKeyGroups(String vlmId, Version version) { - return vendorLicenseFacade.listLicenseKeyGroups(vlmId, version); - } - - @Override - public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup - .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + EP_POOL_START_TIME - : null) : null); - licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup - .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + EP_POOL_EXPIRY_TIME - : null) : null); - - validateCreateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), - licenseKeyGroup.getVendorLicenseModelId()); - return vendorLicenseFacade.createLicenseKeyGroup(licenseKeyGroup); - } - - @Override - public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - licenseKeyGroup.setStartDate(licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup - .getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + EP_POOL_START_TIME - : null) : null); - licenseKeyGroup.setExpiryDate(licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup - .getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + EP_POOL_EXPIRY_TIME - : null) : null); - - validateUpdateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), - licenseKeyGroup.getVendorLicenseModelId()); - vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroup); - } - - @Override - public LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); - VersioningUtil - .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); - return retrieved; - } - - @Override - public void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); - VersioningUtil - .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); - - for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { - featureGroupDao.removeLicenseKeyGroup( - new FeatureGroupEntity(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion(), - referencingFeatureGroupId), licenseKeyGroup.getId()); - } - - deleteChildLimits(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), - licenseKeyGroup.getId()); - - licenseKeyGroupDao.delete(licenseKeyGroup); - - deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - retrieved.getVendorLicenseModelId(), retrieved.getVersion().toString(), - retrieved.getName()); - } - - @Override - public LimitEntity createLimit(LimitEntity limit) { - validateLimit(limit); - LimitEntity createdLimit = vendorLicenseFacade.createLimit(limit); - updateParentForLimit(limit); - return createdLimit; - } - - private void validateLimit(LimitEntity limit) { - Collection limitList = - listLimits(limit.getVendorLicenseModelId(), limit.getVersion() - , limit.getEpLkgId()); - - if (!isLimitNameUnique(limitList, limit.getName(), limit.getType(), limit.getId())) { - final ErrorCode duplicateLimitNameErrorBuilder = - LimitErrorBuilder.getDuplicateNameErrorbuilder(limit.getName(), limit.getType().name()); - throw new CoreException(duplicateLimitNameErrorBuilder); - } - } - - private boolean isLimitNameUnique(Collection limitList, String name, LimitType - type, String id) { - for (LimitEntity limit : limitList) { - if (limit.getName().equalsIgnoreCase(name) && - limit.getType().name().equalsIgnoreCase(type.name())) { - if (id != null && limit.getId().equals(id)) { - continue; + + private static final String EP_POOL_START_TIME = "T00:00:00Z"; + private static final String EP_POOL_EXPIRY_TIME = "T23:59:59Z"; + private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss'Z'"); + private UniqueValueUtil uniqueValueUtil; + private VendorLicenseFacade vendorLicenseFacade; + private VendorLicenseModelDao vendorLicenseModelDao; + private LicenseAgreementDao licenseAgreementDao; + private FeatureGroupDao featureGroupDao; + private EntitlementPoolDao entitlementPoolDao; + private LicenseKeyGroupDao licenseKeyGroupDao; + private LimitDao limitDao; + + public VendorLicenseManagerImpl(VendorLicenseFacade vendorLicenseFacade, VendorLicenseModelDao vendorLicenseModelDao, + LicenseAgreementDao licenseAgreementDao, FeatureGroupDao featureGroupDao, EntitlementPoolDao entitlementPoolDao, + LicenseKeyGroupDao licenseKeyGroupDao, LimitDao limitDao, UniqueValueDao uniqueValueDao) { + this.vendorLicenseFacade = vendorLicenseFacade; + this.vendorLicenseModelDao = vendorLicenseModelDao; + this.licenseAgreementDao = licenseAgreementDao; + this.featureGroupDao = featureGroupDao; + this.entitlementPoolDao = entitlementPoolDao; + this.licenseKeyGroupDao = licenseKeyGroupDao; + this.limitDao = limitDao; + this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); + } + + private static Optional parseLocalDate(String date) { + if (StringUtils.isEmpty(date)) { + return Optional.empty(); + } + return Optional.of(LocalDate.parse(date, FORMATTER)); + } + + @Override + public void validate(String vendorLicenseModelId, Version version) { + vendorLicenseFacade.validate(vendorLicenseModelId, version); + } + + @Override + public VendorLicenseModelEntity createVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity) { + vendorLicenseModelDao.create(vendorLicenseModelEntity); + return vendorLicenseModelEntity; + } + + @Override + public void updateVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModelEntity) { + VendorLicenseModelEntity retrieved = vendorLicenseModelDao.get(vendorLicenseModelEntity); + if (retrieved == null) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage(String + .format("Vlm with id %s and version %s does not exist.", vendorLicenseModelEntity.getId(), + vendorLicenseModelEntity.getVersion().getId()))).build()); + } + String existingVendorName = retrieved.getVendorName(); + updateUniqueName(VendorLicenseConstants.UniqueValues.VENDOR_NAME, existingVendorName, vendorLicenseModelEntity.getVendorName()); + vendorLicenseModelDao.update(vendorLicenseModelEntity); + } + + @Override + public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { + return vendorLicenseFacade.getVendorLicenseModel(vlmId, version); + } + + @Override + public void deleteVendorLicenseModel(String vlmId, Version version) { + throw new UnsupportedOperationException(VendorLicenseConstants.UNSUPPORTED_OPERATION_ERROR); + } + + @Override + public Collection listLicenseAgreements(String vlmId, Version version) { + return licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, version, null)); + } + + @Override + public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { + return vendorLicenseFacade.createLicenseAgreement(licenseAgreement); + } + + @Override + public void updateLicenseAgreement(LicenseAgreementEntity licenseAgreement, Set addedFeatureGroupIds, + Set removedFeatureGroupIds) { + LicenseAgreementEntity retrieved = licenseAgreementDao.get(licenseAgreement); + VersioningUtil.validateEntityExistence(retrieved, licenseAgreement, VendorLicenseModelEntity.ENTITY_TYPE); + VersioningUtil.validateContainedEntitiesExistence(new FeatureGroupEntity().getEntityType(), removedFeatureGroupIds, retrieved, + retrieved.getFeatureGroupIds()); + VersioningUtil.validateEntitiesExistence(addedFeatureGroupIds, + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), null), featureGroupDao, + VendorLicenseModelEntity.ENTITY_TYPE); + updateUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, retrieved.getName(), licenseAgreement.getName(), + licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + licenseAgreementDao.updateColumnsAndDeltaFeatureGroupIds(licenseAgreement, addedFeatureGroupIds, removedFeatureGroupIds); + addFeatureGroupsToLicenseAgreementRef(addedFeatureGroupIds, licenseAgreement); + removeFeatureGroupsToLicenseAgreementRef(removedFeatureGroupIds, licenseAgreement); + } + + @Override + public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, String licenseAgreementId) { + return vendorLicenseFacade.getLicenseAgreementModel(vlmId, version, licenseAgreementId); + } + + @Override + public void deleteLicenseAgreement(String vlmId, Version version, String licenseAgreementId) { + LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); + LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); + VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); + removeFeatureGroupsToLicenseAgreementRef(retrieved.getFeatureGroupIds(), retrieved); + licenseAgreementDao.delete(retrieved); + deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, retrieved.getVendorLicenseModelId(), + retrieved.getVersion().toString(), retrieved.getName()); + } + + @Override + public Collection listFeatureGroups(String vlmId, Version version) { + return vendorLicenseFacade.listFeatureGroups(vlmId, version); + } + + @Override + public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { + return vendorLicenseFacade.createFeatureGroup(featureGroup); + } + + @Override + public void updateFeatureGroup(FeatureGroupEntity featureGroup, Set addedLicenseKeyGroups, Set removedLicenseKeyGroups, + Set addedEntitlementPools, Set removedEntitlementPools) { + FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); + VersioningUtil.validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); + VersioningUtil.validateContainedEntitiesExistence(new LicenseKeyGroupEntity().getEntityType(), removedLicenseKeyGroups, retrieved, + retrieved.getLicenseKeyGroupIds()); + VersioningUtil.validateContainedEntitiesExistence(new EntitlementPoolEntity().getEntityType(), removedEntitlementPools, retrieved, + retrieved.getEntitlementPoolIds()); + VersioningUtil.validateEntitiesExistence(addedLicenseKeyGroups, + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), null), licenseKeyGroupDao, + VendorLicenseModelEntity.ENTITY_TYPE); + VersioningUtil.validateEntitiesExistence(addedEntitlementPools, + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), null), entitlementPoolDao, + VendorLicenseModelEntity.ENTITY_TYPE); + updateUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, retrieved.getName(), featureGroup.getName(), + featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + addLicenseKeyGroupsToFeatureGroupsRef(addedLicenseKeyGroups, featureGroup); + removeLicenseKeyGroupsToFeatureGroupsRef(removedLicenseKeyGroups, featureGroup); + addEntitlementPoolsToFeatureGroupsRef(addedEntitlementPools, featureGroup); + removeEntitlementPoolsToFeatureGroupsRef(removedEntitlementPools, featureGroup); + featureGroupDao + .updateFeatureGroup(featureGroup, addedEntitlementPools, removedEntitlementPools, addedLicenseKeyGroups, removedLicenseKeyGroups); + } + + @Override + public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { + return vendorLicenseFacade.getFeatureGroupModel(featureGroup); + } + + @Override + public void deleteFeatureGroup(FeatureGroupEntity featureGroup) { + FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); + VersioningUtil.validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); + removeLicenseKeyGroupsToFeatureGroupsRef(retrieved.getLicenseKeyGroupIds(), featureGroup); + removeEntitlementPoolsToFeatureGroupsRef(retrieved.getEntitlementPoolIds(), featureGroup); + for (String licenceAgreementId : retrieved.getReferencingLicenseAgreements()) { + licenseAgreementDao + .removeFeatureGroup(new LicenseAgreementEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), licenceAgreementId), + featureGroup.getId()); + } + featureGroupDao.delete(featureGroup); + deleteUniqueName(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, retrieved.getVendorLicenseModelId(), + retrieved.getVersion().toString(), retrieved.getName()); + } + + @Override + public Collection listEntitlementPools(String vlmId, Version version) { + return vendorLicenseFacade.listEntitlementPools(vlmId, version); + } + + @Override + public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { + entitlementPool.setStartDate(getDate(entitlementPool.getStartDate(), EP_POOL_START_TIME)); + entitlementPool.setExpiryDate(getDate(entitlementPool.getExpiryDate(), EP_POOL_EXPIRY_TIME)); + validateCreateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), entitlementPool.getVendorLicenseModelId()); + return vendorLicenseFacade.createEntitlementPool(entitlementPool); + } + + private String getDate(String date, String poolTime) { + return date != null ? (!date.trim().isEmpty() ? date + poolTime : null) : null; + } + + private void validateCreateDate(String startDate, String expiryDate, String vendorLicenseModelId) { + //original logic allows both nulls + if (StringUtils.isEmpty(startDate) && StringUtils.isEmpty(expiryDate)) { + return; } - return false; - } - } - return true; - } - - @Override - public Collection listLimits(String vlmId, Version version, String epLkgId) { - return vendorLicenseFacade.listLimits(vlmId, version, epLkgId); - } - - @Override - public void deleteLimit(LimitEntity limitEntity) { - if (!isLimitPresent(limitEntity)) { - VersioningUtil - .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); - } - LimitEntity retrieved = limitDao.get(limitEntity); - VersioningUtil - .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); - - limitDao.delete(limitEntity); - - updateParentForLimit(limitEntity); - } - - @Override - public void updateLimit(LimitEntity limit) { - getLimit(limit); - validateLimit(limit); - LimitEntity retrieved = limitDao.get(limit); - if(!retrieved.equals(limit)){ - vendorLicenseFacade.updateLimit(limit); - updateParentForLimit(limit); - } - } - - private boolean isLimitPresent(LimitEntity limit) { - return limitDao.isLimitPresent(limit); - } - - @Override - public LimitEntity getLimit(LimitEntity limitEntity) { - if (!isLimitPresent(limitEntity)) { - VersioningUtil - .validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); - } - LimitEntity retrieved = limitDao.get(limitEntity); - VersioningUtil - .validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); - return retrieved; - } - - /** - * update Parent of limit (EP/LKG) versionuuid when limit is modified so that limit updates are - * captured in VLM XML - */ - private void updateParentForLimit(LimitEntity limit) { - if ("EntitlementPool".equals(limit.getParent())) { - EntitlementPoolEntity entitlementPoolEntity = - entitlementPoolDao.get(new EntitlementPoolEntity(limit.getVendorLicenseModelId(), - limit.getVersion(), limit.getEpLkgId())); - entitlementPoolEntity.setVersionUuId(CommonMethods.nextUuId()); - entitlementPoolDao.update(entitlementPoolEntity); - } - - if ("LicenseKeyGroup".equals(limit.getParent())) { - LicenseKeyGroupEntity licenseKeyGroupEntity = licenseKeyGroupDao.get( - new LicenseKeyGroupEntity(limit.getVendorLicenseModelId(), limit.getVersion(), - limit.getEpLkgId())); - licenseKeyGroupEntity.setVersionUuId(CommonMethods.nextUuId()); - licenseKeyGroupDao.update(licenseKeyGroupEntity); - } - } - - protected void addFeatureGroupsToLicenseAgreementRef(Set featureGroupIds, - LicenseAgreementEntity licenseAgreement) { - if (featureGroupIds != null) { - for (String featureGroupId : featureGroupIds) { - featureGroupDao.addReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); - } - } - } - - protected void removeFeatureGroupsToLicenseAgreementRef(Set featureGroupIds, - LicenseAgreementEntity licenseAgreement) { - if (featureGroupIds != null) { - for (String featureGroupId : featureGroupIds) { - featureGroupDao.removeReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), featureGroupId), licenseAgreement.getId()); - } - } - } - - protected void addLicenseKeyGroupsToFeatureGroupsRef(Set licenseKeyGroupIds, - FeatureGroupEntity featureGroup) { - if (licenseKeyGroupIds != null) { - for (String licenseKeyGroupId : licenseKeyGroupIds) { - licenseKeyGroupDao.addReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); - } - } - } - - protected void removeLicenseKeyGroupsToFeatureGroupsRef(Set licenseKeyGroupIds, - FeatureGroupEntity featureGroup) { - if (licenseKeyGroupIds != null) { - for (String licenseKeyGroupId : licenseKeyGroupIds) { - licenseKeyGroupDao.removeReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), licenseKeyGroupId), featureGroup.getId()); - } - } - } - - protected void addEntitlementPoolsToFeatureGroupsRef(Set entitlementPoolIds, - FeatureGroupEntity featureGroup) { - if (entitlementPoolIds != null) { - for (String entitlementPoolId : entitlementPoolIds) { - entitlementPoolDao.addReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); - } - } - } - - protected void removeEntitlementPoolsToFeatureGroupsRef(Set entitlementPoolIds, - FeatureGroupEntity featureGroup) { - if (entitlementPoolIds != null) { - for (String entitlementPoolId : entitlementPoolIds) { - entitlementPoolDao.removeReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), entitlementPoolId), featureGroup.getId()); - } - } - } - - protected void updateUniqueName(String uniqueValueType, String oldName, String newName, String... - context) { - uniqueValueUtil - .updateUniqueValue(uniqueValueType, oldName, newName, context); - } - - protected void deleteUniqueName(String uniqueValueType, String... uniqueCombination) { - uniqueValueUtil.deleteUniqueValue(uniqueValueType, uniqueCombination); - } + Optional parsedStartDate = parseLocalDate(startDate); + Optional parsedExpiryDate = parseLocalDate(expiryDate); + if (!parsedStartDate.isPresent()) { + throw new CoreException(new InvalidDateErrorBuilder(vendorLicenseModelId).build()); + } + if (!parsedExpiryDate.isPresent() && parsedStartDate.get().atStartOfDay().isBefore(LocalDate.now().atStartOfDay())) { + throw new CoreException(new InvalidDateErrorBuilder(vendorLicenseModelId).build()); + } + if (parsedExpiryDate.isPresent() && isNotValidatStartAndExpiryDate(parsedStartDate.get(), parsedExpiryDate.get())) { + throw new CoreException(new InvalidDateErrorBuilder(vendorLicenseModelId).build()); + } + } + + private boolean isNotValidatStartAndExpiryDate(LocalDate parsedStartDate, LocalDate parsedExpiryDate) { + return parsedStartDate.atStartOfDay().isBefore(LocalDate.now().atStartOfDay()) || parsedExpiryDate.atStartOfDay() + .isEqual(parsedStartDate.atStartOfDay()) || parsedExpiryDate.isBefore(parsedStartDate); + } + + private void validateUpdateDate(String startDate, String expiryDate, String vendorLicenseModelId) { + Optional parsedStartDate = parseLocalDate(startDate); + Optional parsedExpiryDate = parseLocalDate(expiryDate); + if (parsedStartDate.isPresent() && parsedExpiryDate.isPresent() && ( + parsedExpiryDate.get().atStartOfDay().isEqual(parsedStartDate.get().atStartOfDay()) || parsedExpiryDate.get() + .isBefore(parsedStartDate.get()))) { + throw new CoreException(new InvalidDateErrorBuilder(vendorLicenseModelId).build()); + } + if (startDate == null && expiryDate != null) { + throw new CoreException(new InvalidDateErrorBuilder(vendorLicenseModelId).build()); + } + } + + @Override + public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { + entitlementPool.setStartDate(getDate(entitlementPool.getStartDate(), EP_POOL_START_TIME)); + entitlementPool.setExpiryDate(getDate(entitlementPool.getExpiryDate(), EP_POOL_EXPIRY_TIME)); + validateUpdateDate(entitlementPool.getStartDate(), entitlementPool.getExpiryDate(), entitlementPool.getVendorLicenseModelId()); + vendorLicenseFacade.updateEntitlementPool(entitlementPool); + } + + @Override + public EntitlementPoolEntity getEntitlementPool(EntitlementPoolEntity entitlementPool) { + EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); + VersioningUtil.validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); + DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); + if (retrieved.getStartDate() != null) { + retrieved.setStartDate(LocalDate.parse(retrieved.getStartDate(), FORMATTER).format(targetFormatter)); + } + if (retrieved.getExpiryDate() != null) { + retrieved.setExpiryDate(LocalDate.parse(retrieved.getExpiryDate(), FORMATTER).format(targetFormatter)); + } + return retrieved; + } + + @Override + public void deleteEntitlementPool(EntitlementPoolEntity entitlementPool) { + EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); + VersioningUtil.validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); + for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { + featureGroupDao.removeEntitlementPool( + new FeatureGroupEntity(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), referencingFeatureGroupId), + entitlementPool.getId()); + } + deleteChildLimits(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), entitlementPool.getId()); + entitlementPoolDao.delete(entitlementPool); + deleteUniqueName(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, retrieved.getVendorLicenseModelId(), + retrieved.getVersion().toString(), retrieved.getName()); + } + + protected void deleteChildLimits(String vlmId, Version version, String epLkgId) { + Optional> limitEntities = Optional.ofNullable(listLimits(vlmId, version, epLkgId)); + limitEntities.ifPresent(entities -> entities.forEach(this::deleteLimit)); + } + + @Override + public Collection listLicenseKeyGroups(String vlmId, Version version) { + return vendorLicenseFacade.listLicenseKeyGroups(vlmId, version); + } + + @Override + public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + licenseKeyGroup.setStartDate( + licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup.getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + + EP_POOL_START_TIME : null) : null); + licenseKeyGroup.setExpiryDate( + licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup.getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + + EP_POOL_EXPIRY_TIME : null) : null); + validateCreateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), licenseKeyGroup.getVendorLicenseModelId()); + return vendorLicenseFacade.createLicenseKeyGroup(licenseKeyGroup); + } + + @Override + public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + licenseKeyGroup.setStartDate( + licenseKeyGroup.getStartDate() != null ? (licenseKeyGroup.getStartDate().trim().length() != 0 ? licenseKeyGroup.getStartDate() + + EP_POOL_START_TIME : null) : null); + licenseKeyGroup.setExpiryDate( + licenseKeyGroup.getExpiryDate() != null ? (licenseKeyGroup.getExpiryDate().trim().length() != 0 ? licenseKeyGroup.getExpiryDate() + + EP_POOL_EXPIRY_TIME : null) : null); + validateUpdateDate(licenseKeyGroup.getStartDate(), licenseKeyGroup.getExpiryDate(), licenseKeyGroup.getVendorLicenseModelId()); + vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroup); + } + + @Override + public LicenseKeyGroupEntity getLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); + VersioningUtil.validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); + return retrieved; + } + + @Override + public void deleteLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); + VersioningUtil.validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); + for (String referencingFeatureGroupId : retrieved.getReferencingFeatureGroups()) { + featureGroupDao.removeLicenseKeyGroup( + new FeatureGroupEntity(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), referencingFeatureGroupId), + licenseKeyGroup.getId()); + } + deleteChildLimits(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), licenseKeyGroup.getId()); + licenseKeyGroupDao.delete(licenseKeyGroup); + deleteUniqueName(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, retrieved.getVendorLicenseModelId(), + retrieved.getVersion().toString(), retrieved.getName()); + } + + @Override + public LimitEntity createLimit(LimitEntity limit) { + validateLimit(limit); + LimitEntity createdLimit = vendorLicenseFacade.createLimit(limit); + updateParentForLimit(limit); + return createdLimit; + } + + private void validateLimit(LimitEntity limit) { + Collection limitList = listLimits(limit.getVendorLicenseModelId(), limit.getVersion(), limit.getEpLkgId()); + if (!isLimitNameUnique(limitList, limit.getName(), limit.getType(), limit.getId())) { + final ErrorCode duplicateLimitNameErrorBuilder = LimitErrorBuilder.getDuplicateNameErrorbuilder(limit.getName(), limit.getType().name()); + throw new CoreException(duplicateLimitNameErrorBuilder); + } + } + + private boolean isLimitNameUnique(Collection limitList, String name, LimitType type, String id) { + for (LimitEntity limit : limitList) { + if (limit.getName().equalsIgnoreCase(name) && limit.getType().name().equalsIgnoreCase(type.name())) { + if (id != null && limit.getId().equals(id)) { + continue; + } + return false; + } + } + return true; + } + + @Override + public Collection listLimits(String vlmId, Version version, String epLkgId) { + return vendorLicenseFacade.listLimits(vlmId, version, epLkgId); + } + + @Override + public void deleteLimit(LimitEntity limitEntity) { + if (!isLimitPresent(limitEntity)) { + VersioningUtil.validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + } + LimitEntity retrieved = limitDao.get(limitEntity); + VersioningUtil.validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + limitDao.delete(limitEntity); + updateParentForLimit(limitEntity); + } + + @Override + public void updateLimit(LimitEntity limit) { + getLimit(limit); + validateLimit(limit); + LimitEntity retrieved = limitDao.get(limit); + if (!retrieved.equals(limit)) { + vendorLicenseFacade.updateLimit(limit); + updateParentForLimit(limit); + } + } + + private boolean isLimitPresent(LimitEntity limit) { + return limitDao.isLimitPresent(limit); + } + + @Override + public LimitEntity getLimit(LimitEntity limitEntity) { + if (!isLimitPresent(limitEntity)) { + VersioningUtil.validateEntityExistence(null, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + } + LimitEntity retrieved = limitDao.get(limitEntity); + VersioningUtil.validateEntityExistence(retrieved, limitEntity, VendorLicenseModelEntity.ENTITY_TYPE); + return retrieved; + } + + /** + * update Parent of limit (EP/LKG) versionuuid when limit is modified so that limit updates are captured in VLM XML + */ + private void updateParentForLimit(LimitEntity limit) { + if ("EntitlementPool".equals(limit.getParent())) { + EntitlementPoolEntity entitlementPoolEntity = entitlementPoolDao + .get(new EntitlementPoolEntity(limit.getVendorLicenseModelId(), limit.getVersion(), limit.getEpLkgId())); + entitlementPoolEntity.setVersionUuId(CommonMethods.nextUuId()); + entitlementPoolDao.update(entitlementPoolEntity); + } + if ("LicenseKeyGroup".equals(limit.getParent())) { + LicenseKeyGroupEntity licenseKeyGroupEntity = licenseKeyGroupDao + .get(new LicenseKeyGroupEntity(limit.getVendorLicenseModelId(), limit.getVersion(), limit.getEpLkgId())); + licenseKeyGroupEntity.setVersionUuId(CommonMethods.nextUuId()); + licenseKeyGroupDao.update(licenseKeyGroupEntity); + } + } + + protected void addFeatureGroupsToLicenseAgreementRef(Set featureGroupIds, LicenseAgreementEntity licenseAgreement) { + if (featureGroupIds != null) { + for (String featureGroupId : featureGroupIds) { + featureGroupDao.addReferencingLicenseAgreement( + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), featureGroupId), + licenseAgreement.getId()); + } + } + } + + protected void removeFeatureGroupsToLicenseAgreementRef(Set featureGroupIds, LicenseAgreementEntity licenseAgreement) { + if (featureGroupIds != null) { + for (String featureGroupId : featureGroupIds) { + featureGroupDao.removeReferencingLicenseAgreement( + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), featureGroupId), + licenseAgreement.getId()); + } + } + } + + protected void addLicenseKeyGroupsToFeatureGroupsRef(Set licenseKeyGroupIds, FeatureGroupEntity featureGroup) { + if (licenseKeyGroupIds != null) { + for (String licenseKeyGroupId : licenseKeyGroupIds) { + licenseKeyGroupDao.addReferencingFeatureGroup( + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), licenseKeyGroupId), + featureGroup.getId()); + } + } + } + + protected void removeLicenseKeyGroupsToFeatureGroupsRef(Set licenseKeyGroupIds, FeatureGroupEntity featureGroup) { + if (licenseKeyGroupIds != null) { + for (String licenseKeyGroupId : licenseKeyGroupIds) { + licenseKeyGroupDao.removeReferencingFeatureGroup( + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), licenseKeyGroupId), + featureGroup.getId()); + } + } + } + + protected void addEntitlementPoolsToFeatureGroupsRef(Set entitlementPoolIds, FeatureGroupEntity featureGroup) { + if (entitlementPoolIds != null) { + for (String entitlementPoolId : entitlementPoolIds) { + entitlementPoolDao.addReferencingFeatureGroup( + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), entitlementPoolId), + featureGroup.getId()); + } + } + } + + protected void removeEntitlementPoolsToFeatureGroupsRef(Set entitlementPoolIds, FeatureGroupEntity featureGroup) { + if (entitlementPoolIds != null) { + for (String entitlementPoolId : entitlementPoolIds) { + entitlementPoolDao.removeReferencingFeatureGroup( + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), entitlementPoolId), + featureGroup.getId()); + } + } + } + + protected void updateUniqueName(String uniqueValueType, String oldName, String newName, String... context) { + uniqueValueUtil.updateUniqueValue(uniqueValueType, oldName, newName, context); + } + + protected void deleteUniqueName(String uniqueValueType, String... uniqueCombination) { + uniqueValueUtil.deleteUniqueValue(uniqueValueType, uniqueCombination); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManager.java index 7ac636879b..7cdec000b3 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ComponentDependencyModelManager { - Collection list(String vspId, Version version); + Collection list(String vspId, Version version); - ComponentDependencyModelEntity createComponentDependency(ComponentDependencyModelEntity entity, - String vspId, Version version); + ComponentDependencyModelEntity createComponentDependency(ComponentDependencyModelEntity entity, String vspId, Version version); - void delete(String vspId, Version version, String dependencyId); + void delete(String vspId, Version version, String dependencyId); - void update(ComponentDependencyModelEntity entity); + void update(ComponentDependencyModelEntity entity); - ComponentDependencyModelEntity get(String vspId, Version version, String dependencyId); + ComponentDependencyModelEntity get(String vspId, Version version, String dependencyId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManagerFactory.java index bd5cd45561..ee2c447e20 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentDependencyModelManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; - import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class ComponentDependencyModelManagerFactory extends - AbstractComponentFactory { +public abstract class ComponentDependencyModelManagerFactory extends AbstractComponentFactory { - public static ComponentDependencyModelManagerFactory getInstance() { - return getInstance(ComponentDependencyModelManagerFactory.class); - } + public static ComponentDependencyModelManagerFactory getInstance() { + return getInstance(ComponentDependencyModelManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManager.java index 413529882d..a9a0a0377e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManager.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; @@ -27,27 +27,23 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ComponentManager { - Collection listComponents(String vspId, Version version); + Collection listComponents(String vspId, Version version); - void deleteComponents(String vspId, Version version); + void deleteComponents(String vspId, Version version); - ComponentEntity createComponent(ComponentEntity componentEntity); + ComponentEntity createComponent(ComponentEntity componentEntity); - CompositionEntityValidationData updateComponent(ComponentEntity componentEntity); + CompositionEntityValidationData updateComponent(ComponentEntity componentEntity); - CompositionEntityResponse getComponent(String vspId, Version version, - String componentId); + CompositionEntityResponse getComponent(String vspId, Version version, String componentId); - void deleteComponent(String vspId, Version version, String componentId); + void deleteComponent(String vspId, Version version, String componentId); - QuestionnaireResponse getQuestionnaire(String vspId, Version version, String componentId); + QuestionnaireResponse getQuestionnaire(String vspId, Version version, String componentId); - void updateQuestionnaire(String vspId, Version version, String componentId, - String questionnaireData); + void updateQuestionnaire(String vspId, Version version, String componentId, String questionnaireData); - void validateComponentExistence(String vspId, Version version, String componentId); + void validateComponentExistence(String vspId, Version version, String componentId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManagerFactory.java index 9af238e4e3..154f0a8c44 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComponentManagerFactory.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class ComponentManagerFactory extends AbstractComponentFactory { - public static ComponentManagerFactory getInstance() { - return getInstance(ComponentManagerFactory.class); - } + public static ComponentManagerFactory getInstance() { + return getInstance(ComponentManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManager.java index 2cf4063319..7899dd2bf1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManager.java @@ -13,10 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; +import java.util.Collection; +import java.util.Map; +import java.util.Set; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Component; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId; @@ -25,44 +31,36 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - public interface CompositionEntityDataManager { - Map> validateEntitiesQuestionnaire(); - - void addEntity(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput); + Map> validateEntitiesQuestionnaire(); - CompositionEntityValidationData validateEntity(CompositionEntity entity, - SchemaTemplateContext schemaTemplateContext, - SchemaTemplateInput schemaTemplateInput); + void addEntity(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput); - void buildTrees(); + CompositionEntityValidationData validateEntity(CompositionEntity entity, SchemaTemplateContext schemaTemplateContext, + SchemaTemplateInput schemaTemplateInput); - void addErrorsToTrees(Map> errors); + void buildTrees(); - Set getEntityListWithErrors(); + void addErrorsToTrees(Map> errors); - Collection getTrees(); + Set getEntityListWithErrors(); - void saveCompositionData(String vspId, Version version, CompositionData compositionData); + Collection getTrees(); - Set getAllErrorsByVsp(String vspId); + void saveCompositionData(String vspId, Version version, CompositionData compositionData); - ComponentEntity createComponent(ComponentEntity component, boolean isManualVsp); + Set getAllErrorsByVsp(String vspId); - NicEntity createNic(NicEntity nic); + ComponentEntity createComponent(ComponentEntity component, boolean isManualVsp); - DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); + NicEntity createNic(NicEntity nic); - ImageEntity createImage(ImageEntity image); + DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); - void saveComputesFlavorByComponent(String vspId, Version version, Component component, - String componentId); + ImageEntity createImage(ImageEntity image); - void saveImagesByComponent(String vspId, Version version, Component component, - String componentId); + void saveComputesFlavorByComponent(String vspId, Version version, Component component, String componentId); + void saveImagesByComponent(String vspId, Version version, Component component, String componentId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManagerFactory.java index be4f187c15..2d09bb2601 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/CompositionEntityDataManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class CompositionEntityDataManagerFactory extends - AbstractComponentFactory { +public abstract class CompositionEntityDataManagerFactory extends AbstractComponentFactory { - public static CompositionEntityDataManagerFactory getInstance() { - return getInstance(CompositionEntityDataManagerFactory.class); - } + public static CompositionEntityDataManagerFactory getInstance() { + return getInstance(CompositionEntityDataManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManager.java index ac903dd3da..bc531bc73f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ListComputeResponse; @@ -28,24 +28,19 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEnti import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ComputeManager { - Collection listComputes(String vspId, Version version, String componentId); + Collection listComputes(String vspId, Version version, String componentId); - ComputeEntity createCompute(ComputeEntity compute); + ComputeEntity createCompute(ComputeEntity compute); - CompositionEntityResponse getCompute(String vspId, Version version, - String componentId, String computeFlavorId); + CompositionEntityResponse getCompute(String vspId, Version version, String componentId, String computeFlavorId); - QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String componentId, - String computeFlavorId); + QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String componentId, String computeFlavorId); - void updateComputeQuestionnaire(String vspId, Version version, String componentId, - String computeId, String questionnaireData); + void updateComputeQuestionnaire(String vspId, Version version, String componentId, String computeId, String questionnaireData); - CompositionEntityValidationData updateCompute(ComputeEntity compute); + CompositionEntityValidationData updateCompute(ComputeEntity compute); - void deleteCompute(String vspId, Version version, String componentId, String computeFlavorId); + void deleteCompute(String vspId, Version version, String componentId, String computeFlavorId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManagerFactory.java index 063bae1237..cc09e3323a 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ComputeManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,6 +24,6 @@ import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class ComputeManagerFactory extends AbstractComponentFactory { public static ComputeManagerFactory getInstance() { - return getInstance(ComputeManagerFactory.class); + return getInstance(ComputeManagerFactory.class); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManager.java index b36c6f0864..e506bc019b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,34 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; - +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface DeploymentFlavorManager { + DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); - DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); - - Collection listDeploymentFlavors(String vspId, Version version); - - CompositionEntityResponse getDeploymentFlavor(String vspId, Version version, - String deploymentFlavorId); + Collection listDeploymentFlavors(String vspId, Version version); - CompositionEntityResponse getDeploymentFlavorSchema(String vspId, - Version version); + CompositionEntityResponse getDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); - void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); + CompositionEntityResponse getDeploymentFlavorSchema(String vspId, Version version); - CompositionEntityValidationData updateDeploymentFlavor( - DeploymentFlavorEntity deploymentFlavorEntity); + void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); + CompositionEntityValidationData updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManagerFactory.java index 97ae62978d..cc99db62d5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/DeploymentFlavorManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; - import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class DeploymentFlavorManagerFactory extends - AbstractComponentFactory { +public abstract class DeploymentFlavorManagerFactory extends AbstractComponentFactory { - public static DeploymentFlavorManagerFactory getInstance() { - return getInstance(DeploymentFlavorManagerFactory.class); - } + public static DeploymentFlavorManagerFactory getInstance() { + return getInstance(DeploymentFlavorManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManager.java index d1a8662821..f106c2a2ef 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; @@ -27,25 +27,21 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEnti import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Image; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ImageManager { - ImageEntity createImage(ImageEntity imageEntity); - CompositionEntityResponse getImageSchema(String vspId); + ImageEntity createImage(ImageEntity imageEntity); + + CompositionEntityResponse getImageSchema(String vspId); - Collection listImages(String vspId, Version version, String componentId); + Collection listImages(String vspId, Version version, String componentId); - CompositionEntityResponse getImage(String vspId, Version version, String componentId, - String imageId); + CompositionEntityResponse getImage(String vspId, Version version, String componentId, String imageId); - QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String componentId, - String imageId); + QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String componentId, String imageId); - void deleteImage(String vspId, Version version, String componentId, String imageId); + void deleteImage(String vspId, Version version, String componentId, String imageId); - CompositionEntityValidationData updateImage(ImageEntity imageEntity); + CompositionEntityValidationData updateImage(ImageEntity imageEntity); - void updateImageQuestionnaire(String vspId, Version version, String componentId, String imageId, - String questionnaireData); + void updateImageQuestionnaire(String vspId, Version version, String componentId, String imageId, String questionnaireData); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManagerFactory.java index 2ee014bb28..1caad874f1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ImageManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class ImageManagerFactory extends AbstractComponentFactory { - public static ImageManagerFactory getInstance() { - return getInstance(ImageManagerFactory.class); - } + public static ImageManagerFactory getInstance() { + return getInstance(ImageManagerFactory.class); + } } - diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ManualVspToscaManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ManualVspToscaManager.java index 4d8c861b9d..292723e1fa 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ManualVspToscaManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ManualVspToscaManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.sdc.generator.datatypes.tosca.VspModelInfo; @@ -26,7 +25,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ManualVspToscaManager { - VspModelInfo gatherVspInformation(String vspId, Version version); + VspModelInfo gatherVspInformation(String vspId, Version version); - ToscaServiceModel generateToscaModel(VspModelInfo vspModelInfo); + ToscaServiceModel generateToscaModel(VspModelInfo vspModelInfo); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManager.java index 36f06507dc..0bc55b2ff4 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManager.java @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.io.InputStream; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.InputStream; - public interface MonitoringUploadsManager { - void delete(String vspId, Version version, String componentId, - MonitoringUploadType monitoringUploadType); - void upload(InputStream object, String filename, String vspId, Version version, - String componentId, MonitoringUploadType monitoringUploadType); + void delete(String vspId, Version version, String componentId, MonitoringUploadType monitoringUploadType); + + void upload(InputStream object, String filename, String vspId, Version version, String componentId, MonitoringUploadType monitoringUploadType); - MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId); + MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManagerFactory.java index 9850b2e19b..db41837222 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/MonitoringUploadsManagerFactory.java @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class MonitoringUploadsManagerFactory - extends AbstractComponentFactory { +public abstract class MonitoringUploadsManagerFactory extends AbstractComponentFactory { - public static MonitoringUploadsManagerFactory getInstance() { - return getInstance(MonitoringUploadsManagerFactory.class); - } + public static MonitoringUploadsManagerFactory getInstance() { + return getInstance(MonitoringUploadsManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManager.java index fa740690b7..837f7803d9 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManager.java @@ -17,25 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface NetworkManager { - Collection listNetworks(String vspId, Version version); - NetworkEntity createNetwork(NetworkEntity network); + Collection listNetworks(String vspId, Version version); + + NetworkEntity createNetwork(NetworkEntity network); - CompositionEntityValidationData updateNetwork(NetworkEntity networkEntity); + CompositionEntityValidationData updateNetwork(NetworkEntity networkEntity); - CompositionEntityResponse getNetwork(String vspId, Version version, String networkId); + CompositionEntityResponse getNetwork(String vspId, Version version, String networkId); - void deleteNetwork(String vspId, Version version, String networkId); + void deleteNetwork(String vspId, Version version, String networkId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManagerFactory.java index a0b7465235..1c230a04bf 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NetworkManagerFactory.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class NetworkManagerFactory extends AbstractComponentFactory { - public static NetworkManagerFactory getInstance() { - return getInstance(NetworkManagerFactory.class); - } + public static NetworkManagerFactory getInstance() { + return getInstance(NetworkManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManager.java index b055d97ef3..3a600f346d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManager.java @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.util.Collection; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; @@ -27,24 +27,19 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEnti import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface NicManager { - Collection listNics(String vspId, Version version, String componentId); + Collection listNics(String vspId, Version version, String componentId); - NicEntity createNic(NicEntity nic); + NicEntity createNic(NicEntity nic); - CompositionEntityValidationData updateNic(NicEntity nicEntity); + CompositionEntityValidationData updateNic(NicEntity nicEntity); - CompositionEntityResponse getNic(String vspId, Version version, String componentId, - String nicId); + CompositionEntityResponse getNic(String vspId, Version version, String componentId, String nicId); - void deleteNic(String vspId, Version version, String componentId, String nicId); + void deleteNic(String vspId, Version version, String componentId, String nicId); - QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, String componentId, - String nicId); + QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, String componentId, String nicId); - void updateNicQuestionnaire(String vspId, Version version, String componentId, String nicId, - String questionnaireData); + void updateNicQuestionnaire(String vspId, Version version, String componentId, String nicId, String questionnaireData); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManagerFactory.java index 212619ce87..2749fee17f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/NicManagerFactory.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class NicManagerFactory extends AbstractComponentFactory { - public static NicManagerFactory getInstance() { - return getInstance(NicManagerFactory.class); - } + public static NicManagerFactory getInstance() { + return getInstance(NicManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManager.java index 5cf66874c4..f1c6aa5209 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManager.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct; import java.io.IOException; @@ -30,18 +29,17 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface OrchestrationTemplateCandidateManager { - OrchestrationTemplateActionResponse process(String vspId, Version version); + OrchestrationTemplateActionResponse process(String vspId, Version version); - Optional getFilesDataStructure(String vspId, Version version); + Optional getFilesDataStructure(String vspId, Version version); - ValidationResponse updateFilesDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure); + ValidationResponse updateFilesDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure); - Optional> get(String vspId, Version version) throws IOException; + Optional> get(String vspId, Version version) throws IOException; - Optional getInfo(String vspId, Version version); + Optional getInfo(String vspId, Version version); - void abort(String vspId, Version version); + void abort(String vspId, Version version); - UploadFileResponse upload(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo); + UploadFileResponse upload(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManagerFactory.java index b38355b8e9..8a5fe05d0d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/OrchestrationTemplateCandidateManagerFactory.java @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class OrchestrationTemplateCandidateManagerFactory - extends AbstractComponentFactory { +public abstract class OrchestrationTemplateCandidateManagerFactory extends AbstractComponentFactory { - public static OrchestrationTemplateCandidateManagerFactory getInstance() { - return getInstance(OrchestrationTemplateCandidateManagerFactory.class); - } + public static OrchestrationTemplateCandidateManagerFactory getInstance() { + return getInstance(OrchestrationTemplateCandidateManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManager.java index 979eea0fb8..c10a4c733c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManager.java @@ -17,33 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.File; import java.io.InputStream; import java.util.Collection; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; +import org.openecomp.sdc.versioning.dao.types.Version; public interface ProcessManager { - Collection listProcesses(String vspId, Version version, String componentId); - void deleteProcesses(String vspId, Version version, String componentId); + Collection listProcesses(String vspId, Version version, String componentId); + + void deleteProcesses(String vspId, Version version, String componentId); - ProcessEntity createProcess(ProcessEntity processEntity); + ProcessEntity createProcess(ProcessEntity processEntity); - ProcessEntity getProcess(String vspId, Version version, String componentId, String processId); + ProcessEntity getProcess(String vspId, Version version, String componentId, String processId); - void updateProcess(ProcessEntity processEntity); + void updateProcess(ProcessEntity processEntity); - void deleteProcess(String vspId, Version version, String componentId, String processId); + void deleteProcess(String vspId, Version version, String componentId, String processId); - File getProcessArtifact(String vspId, Version version, String componentId, String processId); + File getProcessArtifact(String vspId, Version version, String componentId, String processId); - void deleteProcessArtifact(String vspId, Version version, String componentId, String processId); + void deleteProcessArtifact(String vspId, Version version, String componentId, String processId); - void uploadProcessArtifact(InputStream uploadFile, String fileName, String vspId, - Version version, String componentId, String processId); + void uploadProcessArtifact(InputStream uploadFile, String fileName, String vspId, Version version, String componentId, String processId); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManagerFactory.java index f8d1038ca2..578e36778e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/ProcessManagerFactory.java @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; public abstract class ProcessManagerFactory extends AbstractComponentFactory { - public static ProcessManagerFactory getInstance() { - return getInstance(ProcessManagerFactory.class); - } + public static ProcessManagerFactory getInstance() { + return getInstance(ProcessManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductManager.java index 2339fa0921..6a92dbb209 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductManager.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct; +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.lang3.tuple.Pair; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; @@ -27,13 +32,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; - public interface VendorSoftwareProductManager { VspDetails createVsp(VspDetails vspDetails); @@ -48,12 +46,10 @@ public interface VendorSoftwareProductManager { Map> compile(String vspId, Version version); - QuestionnaireResponse getVspQuestionnaire(String vspId, Version version); void updateVspQuestionnaire(String vspId, Version version, String questionnaireData); - byte[] getOrchestrationTemplateFile(String vspId, Version version); OrchestrationTemplateEntity getOrchestrationTemplateInfo(String vspId, Version version); @@ -64,7 +60,6 @@ public interface VendorSoftwareProductManager { List listPackages(String category, String subCategory); - File getTranslatedFile(String vspId, Version version); File getInformationArtifact(String vspId, Version version); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VspManagerFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VspManagerFactory.java index a2f186428a..ac03524a12 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VspManagerFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VspManagerFactory.java @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; import org.openecomp.core.factory.api.AbstractComponentFactory; -public abstract class VspManagerFactory - extends AbstractComponentFactory { +public abstract class VspManagerFactory extends AbstractComponentFactory { - public static VspManagerFactory getInstance() { - return getInstance(VspManagerFactory.class); - } + public static VspManagerFactory getInstance() { + return getInstance(VspManagerFactory.class); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentDependencyModelErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentDependencyModelErrorBuilder.java index 249ad1cb28..c3869198b1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentDependencyModelErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentDependencyModelErrorBuilder.java @@ -13,60 +13,55 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.CYCLIC_DEPENDENCY_IN_COMPONENTS; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_COMPONENT_RELATION_TYPE; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.NO_SOURCE_COMPONENT; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.SAME_SOURCE_TARGET_COMPONENT; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.*; - public class ComponentDependencyModelErrorBuilder { - private static final String CYCLIC_DEPENDENCY_COMPONENT_MSG = "Cyclic dependency exists between" - + " components."; - - private static final String INVALID_REALTION_TYPE_MSG = "Invalid relation type for components."; - - private static final String NO_SOURCE_COMPONENT_MSG = "Source component is mandatory."; - - private static final String SOURCE_TARGET_COMPONENT_EQUAL_MSG = "Source and target components " - + "are same."; - - private ComponentDependencyModelErrorBuilder(){ + private static final String CYCLIC_DEPENDENCY_COMPONENT_MSG = "Cyclic dependency exists between" + " components."; + private static final String INVALID_REALTION_TYPE_MSG = "Invalid relation type for components."; + private static final String NO_SOURCE_COMPONENT_MSG = "Source component is mandatory."; + private static final String SOURCE_TARGET_COMPONENT_EQUAL_MSG = "Source and target components " + "are same."; - } + private ComponentDependencyModelErrorBuilder() { + } - public static ErrorCode getCyclicDependencyComponentErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(CYCLIC_DEPENDENCY_IN_COMPONENTS); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(CYCLIC_DEPENDENCY_COMPONENT_MSG); - return builder.build(); - } + public static ErrorCode getCyclicDependencyComponentErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(CYCLIC_DEPENDENCY_IN_COMPONENTS); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(CYCLIC_DEPENDENCY_COMPONENT_MSG); + return builder.build(); + } - public static ErrorCode getInvalidRelationTypeErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(INVALID_COMPONENT_RELATION_TYPE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(INVALID_REALTION_TYPE_MSG); - return builder.build(); - } + public static ErrorCode getInvalidRelationTypeErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(INVALID_COMPONENT_RELATION_TYPE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(INVALID_REALTION_TYPE_MSG); + return builder.build(); + } - public static ErrorCode getNoSourceComponentErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(NO_SOURCE_COMPONENT); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(NO_SOURCE_COMPONENT_MSG); - return builder.build(); - } + public static ErrorCode getNoSourceComponentErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(NO_SOURCE_COMPONENT); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(NO_SOURCE_COMPONENT_MSG); + return builder.build(); + } - public static ErrorCode getSourceTargetComponentEqualErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(SAME_SOURCE_TARGET_COMPONENT); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(SOURCE_TARGET_COMPONENT_EQUAL_MSG); - return builder.build(); - } + public static ErrorCode getSourceTargetComponentEqualErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(SAME_SOURCE_TARGET_COMPONENT); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(SOURCE_TARGET_COMPONENT_EQUAL_MSG); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentErrorBuilder.java index 74f4fd2a13..0271020c09 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComponentErrorBuilder.java @@ -13,28 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - public class ComponentErrorBuilder { - private static final String VFC_INVALID_MISSING_IMAGE_MSG = - "All VFC need to have atleast a single Image specified. Please fix the VFC Images and re-submit the VSP"; - - private ComponentErrorBuilder(){ - - } + private static final String VFC_INVALID_MISSING_IMAGE_MSG = "All VFC need to have atleast a single Image specified. Please fix the VFC Images and re-submit the VSP"; + private ComponentErrorBuilder() { + } - public static ErrorCode vfcMissingImageErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes.VFC_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(VFC_INVALID_MISSING_IMAGE_MSG); - return builder.build(); - } + public static ErrorCode vfcMissingImageErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VendorSoftwareProductErrorCodes.VFC_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(VFC_INVALID_MISSING_IMAGE_MSG); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CompositionEditNotAllowedErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CompositionEditNotAllowedErrorBuilder.java index 4e4de2279e..fbb25dc3b3 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CompositionEditNotAllowedErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CompositionEditNotAllowedErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; - public class CompositionEditNotAllowedErrorBuilder { - private static final String VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG = - "Composition entities may not be created / deleted for Vendor Software Product %s, version %s" - + "whose entities were uploaded"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public CompositionEditNotAllowedErrorBuilder(String vendorSoftwareProductId, Version version) { - builder.withId(VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG, vendorSoftwareProductId, - version == null ? null : version.toString())); + private static final String VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG = + "Composition entities may not be created / deleted for Vendor Software Product %s, version %s" + "whose entities were uploaded"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - } + /** + * Instantiates a new error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public CompositionEditNotAllowedErrorBuilder(String vendorSoftwareProductId, Version version) { + builder.withId(VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder + .withMessage(String.format(VSP_COMPOSITION_EDIT_NOT_ALLOWED_MSG, vendorSoftwareProductId, version == null ? null : version.toString())); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComputeErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComputeErrorBuilder.java index 5250b971ac..83cc92c119 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComputeErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ComputeErrorBuilder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -23,11 +22,10 @@ import org.openecomp.sdc.common.errors.ErrorCode; * The Compute error builder. */ public class ComputeErrorBuilder { - private static final String COMPUTE_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" - + ": name : must match %s"; - private ComputeErrorBuilder(){ + private static final String COMPUTE_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" + ": name : must match %s"; + private ComputeErrorBuilder() { } /** diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CreatePackageForNonFinalVendorSoftwareProductErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CreatePackageForNonFinalVendorSoftwareProductErrorBuilder.java index 04038fe6bc..39752b39e7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CreatePackageForNonFinalVendorSoftwareProductErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/CreatePackageForNonFinalVendorSoftwareProductErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,34 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.CREATE_PACKAGE_FOR_NON_FINAL_VSP; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.CREATE_PACKAGE_FOR_NON_FINAL_VSP; - - public class CreatePackageForNonFinalVendorSoftwareProductErrorBuilder { - private static final String CREATE_PACKAGE_FOR_NON_FINAL_VSP_MSG = - "Package creation for vendor software product with id %s and version %s is not allowed since " - + "it is not final (submitted)."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Create package for non final vendor software product error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(String vendorSoftwareProductId, - Version version) { - builder.withId(CREATE_PACKAGE_FOR_NON_FINAL_VSP); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String - .format(CREATE_PACKAGE_FOR_NON_FINAL_VSP_MSG, vendorSoftwareProductId, version == null ? null : version.toString())); - } - - public ErrorCode build() { - return builder.build(); - } + private static final String CREATE_PACKAGE_FOR_NON_FINAL_VSP_MSG = + "Package creation for vendor software product with id %s and version %s is not allowed since " + "it is not final (submitted)."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Create package for non final vendor software product error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public CreatePackageForNonFinalVendorSoftwareProductErrorBuilder(String vendorSoftwareProductId, Version version) { + builder.withId(CREATE_PACKAGE_FOR_NON_FINAL_VSP); + builder.withCategory(ErrorCategory.APPLICATION); + builder + .withMessage(String.format(CREATE_PACKAGE_FOR_NON_FINAL_VSP_MSG, vendorSoftwareProductId, version == null ? null : version.toString())); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeleteNicErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeleteNicErrorBuilder.java index 6a94d81643..61ad90185f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeleteNicErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeleteNicErrorBuilder.java @@ -13,18 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; public class DeleteNicErrorBuilder { - private static final String DELETE_NIC_NOT_ALLOWED_MSG = - "NIC cannot be deleted for VSPs onboarded with HEAT."; - private DeleteNicErrorBuilder(){ + private static final String DELETE_NIC_NOT_ALLOWED_MSG = "NIC cannot be deleted for VSPs onboarded with HEAT."; + private DeleteNicErrorBuilder() { } public static ErrorCode getDeleteNicForHeatOnboardedVspErrorBuilder() { @@ -34,5 +32,4 @@ public class DeleteNicErrorBuilder { builder.withMessage(String.format(DELETE_NIC_NOT_ALLOWED_MSG)); return builder.build(); } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeploymentFlavorErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeploymentFlavorErrorBuilder.java index ab0881268e..4869b77bc6 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeploymentFlavorErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DeploymentFlavorErrorBuilder.java @@ -13,43 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.versioning.dao.types.Version; public class DeploymentFlavorErrorBuilder { - private static final String CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = - "Deployment Flavor cannot be added for VSPs onboarded with HEAT."; - private static final String FEATURE_GROUP_NOT_EXIST_FOR_VSP_MSG = - "Invalid request, Feature Group provided does not exist for this Vsp."; - private static final String INVALID_COMPONENT_COMPUTE_ASSOCIATION_MSG - = "Invalid request,for valid association please provide ComponentId for Compute Flavor"; - private static final String SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED_MSG = - "Invalid Request,Same Vfc cannot be associated more than once."; - private static final String DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED_MSG = - "Invalid request, Deployment Flavor with model %s already exists for Vsp with Id %s."; - private static final String DEPLOYMENT_FLAVOUR_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" - + ": name : must match %s"; - private static final String INVALID_COMPUTE_FLAVOR_ID_MSG = - "Invalid request, Compute Flavor provided does not exist for this VFC."; - private static final String INVALID_COMPONENT_ID_MSG = - "Invalid request, Component provided does not exist for this VSP."; - private static final String INVALID_COMPONENT_COMPUTE_ASSOCIATION_ERROR_MSG="VSP cannot be " + - "submitted with an invalid Deployment Flavor. All Deployment Flavor should have atleast a VFC included with it's required Compute needs. " + - "Please fix the Deployment Flavor %s and re-submit the VSP."; - - private static final String FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR_MSG = "VSP cannot be " + - "submitted with an invalid Deployment Flavor. All Deployment Flavor should have " + - "FeatureGroup. Please fix the Deployment Flavor %s and re-submit the VSP."; - - private DeploymentFlavorErrorBuilder(){ + private static final String CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "Deployment Flavor cannot be added for VSPs onboarded with HEAT."; + private static final String FEATURE_GROUP_NOT_EXIST_FOR_VSP_MSG = "Invalid request, Feature Group provided does not exist for this Vsp."; + private static final String INVALID_COMPONENT_COMPUTE_ASSOCIATION_MSG = "Invalid request,for valid association please provide ComponentId for Compute Flavor"; + private static final String SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED_MSG = "Invalid Request,Same Vfc cannot be associated more than once."; + private static final String DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED_MSG = "Invalid request, Deployment Flavor with model %s already exists for Vsp with Id %s."; + private static final String DEPLOYMENT_FLAVOUR_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" + ": name : must match %s"; + private static final String INVALID_COMPUTE_FLAVOR_ID_MSG = "Invalid request, Compute Flavor provided does not exist for this VFC."; + private static final String INVALID_COMPONENT_ID_MSG = "Invalid request, Component provided does not exist for this VSP."; + private static final String INVALID_COMPONENT_COMPUTE_ASSOCIATION_ERROR_MSG = "VSP cannot be " + + "submitted with an invalid Deployment Flavor. All Deployment Flavor should have atleast a VFC included with it's required Compute needs. " + + "Please fix the Deployment Flavor %s and re-submit the VSP."; + private static final String FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR_MSG = + "VSP cannot be " + "submitted with an invalid Deployment Flavor. All Deployment Flavor should have " + + "FeatureGroup. Please fix the Deployment Flavor %s and re-submit the VSP."; + + private DeploymentFlavorErrorBuilder() { } - public static ErrorCode getAddDeploymentNotSupportedHeatOnboardErrorBuilder(){ + public static ErrorCode getAddDeploymentNotSupportedHeatOnboardErrorBuilder() { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(VendorSoftwareProductErrorCodes.CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); builder.withCategory(ErrorCategory.APPLICATION); @@ -57,7 +46,7 @@ public class DeploymentFlavorErrorBuilder { return builder.build(); } - public static ErrorCode getFeatureGroupNotexistErrorBuilder(){ + public static ErrorCode getFeatureGroupNotexistErrorBuilder() { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(VendorSoftwareProductErrorCodes.FEATURE_GROUP_NOT_EXIST_FOR_VSP); builder.withCategory(ErrorCategory.APPLICATION); @@ -65,10 +54,9 @@ public class DeploymentFlavorErrorBuilder { return builder.build(); } - public static ErrorCode getDuplicateVfcAssociationErrorBuilder(){ + public static ErrorCode getDuplicateVfcAssociationErrorBuilder() { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes - .SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED); + builder.withId(VendorSoftwareProductErrorCodes.SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED); builder.withCategory(ErrorCategory.APPLICATION); builder.withMessage(SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED_MSG); return builder.build(); @@ -82,12 +70,11 @@ public class DeploymentFlavorErrorBuilder { return builder.build(); } - public static ErrorCode getDuplicateDeploymentFlavorModelErrorBuilder(String name, - String vspId) { + public static ErrorCode getDuplicateDeploymentFlavorModelErrorBuilder(String name, String vspId) { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(VendorSoftwareProductErrorCodes.DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED); builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED_MSG,name,vspId)); + builder.withMessage(String.format(DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED_MSG, name, vspId)); return builder.build(); } @@ -123,7 +110,7 @@ public class DeploymentFlavorErrorBuilder { return builder.build(); } - public static ErrorCode getDeploymentFlavorNameFormatErrorBuilder(String pattern){ + public static ErrorCode getDeploymentFlavorNameFormatErrorBuilder(String pattern) { ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); builder.withId(VendorSoftwareProductErrorCodes.DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED); builder.withCategory(ErrorCategory.APPLICATION); diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateComputeInComponentErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateComputeInComponentErrorBuilder.java index 553ee920a4..4915912313 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateComputeInComponentErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateComputeInComponentErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; - import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.UPDATE_COMPUTE_NOT_ALLOWED; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; public class DuplicateComputeInComponentErrorBuilder { - private static final String COMPUTE_HEAT_READONLY_ATTR_MSG = - "Update of attribute %s not allowed for VSP onboarded via HEAT."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public static ErrorCode getComputeHeatReadOnlyErrorBuilder(String name) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(UPDATE_COMPUTE_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(COMPUTE_HEAT_READONLY_ATTR_MSG, name)); - return builder.build(); - } + private static final String COMPUTE_HEAT_READONLY_ATTR_MSG = "Update of attribute %s not allowed for VSP onboarded via HEAT."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + public static ErrorCode getComputeHeatReadOnlyErrorBuilder(String name) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(UPDATE_COMPUTE_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(COMPUTE_HEAT_READONLY_ATTR_MSG, name)); + return builder.build(); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateNicInComponentErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateNicInComponentErrorBuilder.java index 6d5edff169..0ff6e228eb 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateNicInComponentErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/DuplicateNicInComponentErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,18 +24,16 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class DuplicateNicInComponentErrorBuilder { - private static final String DUPLICATE_NIC_NAME_NOT_ALLOWED_MSG = - "Invalid request, NIC with name %s already exist for component with ID %s."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + private static final String DUPLICATE_NIC_NAME_NOT_ALLOWED_MSG = "Invalid request, NIC with name %s already exist for component with ID %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public DuplicateNicInComponentErrorBuilder(String nicName, String componentId ){ - builder.withId(VendorSoftwareProductErrorCodes.DUPLICATE_NIC_NAME_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(DUPLICATE_NIC_NAME_NOT_ALLOWED_MSG,nicName,componentId)); - } - public ErrorCode build() { - return builder.build(); - } + public DuplicateNicInComponentErrorBuilder(String nicName, String componentId) { + builder.withId(VendorSoftwareProductErrorCodes.DUPLICATE_NIC_NAME_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(DUPLICATE_NIC_NAME_NOT_ALLOWED_MSG, nicName, componentId)); + } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/FileCreationErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/FileCreationErrorBuilder.java index e00e145020..75388af64a 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/FileCreationErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/FileCreationErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.HEAT_PACKAGE_FILE_CREATION; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.HEAT_PACKAGE_FILE_CREATION; - public class FileCreationErrorBuilder { - private static final String HEAT_PKG_FILE_CREATION_ERROR_MSG = - "Error while trying to create heat file from the package of vendor software product " - + "with Id %s."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new File creation error builder. - * - * @param vendorSoftwareProductId the vendor software product id - */ - public FileCreationErrorBuilder(String vendorSoftwareProductId) { - builder.withId(HEAT_PACKAGE_FILE_CREATION); - builder.withCategory(ErrorCategory.SYSTEM); - builder.withMessage(String.format(HEAT_PKG_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId)); - } + private static final String HEAT_PKG_FILE_CREATION_ERROR_MSG = + "Error while trying to create heat file from the package of vendor software product " + "with Id %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new File creation error builder. + * + * @param vendorSoftwareProductId the vendor software product id + */ + public FileCreationErrorBuilder(String vendorSoftwareProductId) { + builder.withId(HEAT_PACKAGE_FILE_CREATION); + builder.withCategory(ErrorCategory.SYSTEM); + builder.withMessage(String.format(HEAT_PKG_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ImageErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ImageErrorBuilder.java index 45bad9cad9..c5beb04a47 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ImageErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/ImageErrorBuilder.java @@ -13,90 +13,89 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DUPLICATE_IMAGE_NAME_NOT_ALLOWED; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DUPLICATE_IMAGE_VERSION_NOT_ALLOWED; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.IMAGE_NAME_FORMAT_NOT_ALLOWED; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.UPDATE_IMAGE_NOT_ALLOWED; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.VFC_IMAGE_INVALID_FORMAT; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.*; - /** * The Image error builder. */ public class ImageErrorBuilder { - private static final String VFC_IMAGE_DUPLICATE_NAME_MSG = "Invalid request, Image with name %s" - + " already exists for component with ID %s."; - private static final String VFC_IMAGE_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" - + ": name : must match %s"; - private static final String IMAGE_INVALID_FORMAT_MSG = "The format value doesn't meet the " - + "expected attribute value."; + private static final String VFC_IMAGE_DUPLICATE_NAME_MSG = "Invalid request, Image with name %s" + " already exists for component with ID %s."; + private static final String VFC_IMAGE_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" + ": name : must match %s"; + private static final String IMAGE_INVALID_FORMAT_MSG = "The format value doesn't meet the " + "expected attribute value."; + private static final String IMAGE_HEAT_READONLY_ATTR_MSG = "Update of attribute %s not allowed " + "for VSP onboarded via HEAT."; + private static final String VFC_IMAGE_DUPLICATE_VERSION_MSG = + "Invalid request, Image with version %s" + " already exists for component with ID %s."; - private static final String IMAGE_HEAT_READONLY_ATTR_MSG = "Update of attribute %s not allowed " - + "for VSP onboarded via HEAT."; - private static final String VFC_IMAGE_DUPLICATE_VERSION_MSG = "Invalid request, Image with version %s" - + " already exists for component with ID %s."; - private ImageErrorBuilder() { + private ImageErrorBuilder() { + } - } + /** + * Gets duplicate image name error builder. + * + * @return the duplicate image name error builder + */ + public static ErrorCode getDuplicateImageNameErrorBuilder(String imageName, String componentId) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(DUPLICATE_IMAGE_NAME_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VFC_IMAGE_DUPLICATE_NAME_MSG, imageName, componentId)); + return builder.build(); + } - /** - * Gets duplicate image name error builder. - * - * @return the duplicate image name error builder - */ - public static ErrorCode getDuplicateImageNameErrorBuilder(String imageName, String componentId) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(DUPLICATE_IMAGE_NAME_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VFC_IMAGE_DUPLICATE_NAME_MSG, imageName, componentId )); - return builder.build(); - } + /** + * Gets duplicate image version error builder. + * + * @return the duplicate image version error builder + */ + public static ErrorCode getDuplicateImageVersionErrorBuilder(String version, String componentId) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(DUPLICATE_IMAGE_VERSION_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VFC_IMAGE_DUPLICATE_VERSION_MSG, version, componentId)); + return builder.build(); + } - /** - * Gets duplicate image version error builder. - * - * @return the duplicate image version error builder - */ - public static ErrorCode getDuplicateImageVersionErrorBuilder(String version, String componentId) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(DUPLICATE_IMAGE_VERSION_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VFC_IMAGE_DUPLICATE_VERSION_MSG, version, componentId )); - return builder.build(); - } - /** - * Gets image name format error builder. - * - * @return the image name format error builder - */ - public static ErrorCode getImageNameFormatErrorBuilder(String pattern) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(IMAGE_NAME_FORMAT_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VFC_IMAGE_NAME_FORMAT_MSG, pattern)); - return builder.build(); - } + /** + * Gets image name format error builder. + * + * @return the image name format error builder + */ + public static ErrorCode getImageNameFormatErrorBuilder(String pattern) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(IMAGE_NAME_FORMAT_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VFC_IMAGE_NAME_FORMAT_MSG, pattern)); + return builder.build(); + } - /** - * Gets invalid image format error builder. - * - * @return the invalid image format error builder - */ - public static ErrorCode getInvalidImageFormatErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VFC_IMAGE_INVALID_FORMAT); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(IMAGE_INVALID_FORMAT_MSG); - return builder.build(); - } + /** + * Gets invalid image format error builder. + * + * @return the invalid image format error builder + */ + public static ErrorCode getInvalidImageFormatErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VFC_IMAGE_INVALID_FORMAT); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(IMAGE_INVALID_FORMAT_MSG); + return builder.build(); + } - public static ErrorCode getImageHeatReadOnlyErrorBuilder(String name) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(UPDATE_IMAGE_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(IMAGE_HEAT_READONLY_ATTR_MSG, name)); - return builder.build(); - } + public static ErrorCode getImageHeatReadOnlyErrorBuilder(String name) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(UPDATE_IMAGE_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(IMAGE_HEAT_READONLY_ATTR_MSG, name)); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/InformationArtifactCreationErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/InformationArtifactCreationErrorBuilder.java index ca5b9bfcbb..e5acffe868 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/InformationArtifactCreationErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/InformationArtifactCreationErrorBuilder.java @@ -17,31 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; - import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.HEAT_PACKAGE_FILE_CREATION; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; /** * Created by Talio on 11/24/2016. */ public class InformationArtifactCreationErrorBuilder { - private static final String INFO_ARTIFACT_FILE_CREATION_ERROR_MSG = - "Error while trying to information artifact file for vendor software product with Id %s."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public InformationArtifactCreationErrorBuilder(String vendorSoftwareProductId) { - builder.withId(HEAT_PACKAGE_FILE_CREATION); - builder.withCategory(ErrorCategory.SYSTEM); - builder - .withMessage(String.format(INFO_ARTIFACT_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId)); - } + private static final String INFO_ARTIFACT_FILE_CREATION_ERROR_MSG = "Error while trying to information artifact file for vendor software product with Id %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public InformationArtifactCreationErrorBuilder(String vendorSoftwareProductId) { + builder.withId(HEAT_PACKAGE_FILE_CREATION); + builder.withCategory(ErrorCategory.SYSTEM); + builder.withMessage(String.format(INFO_ARTIFACT_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId)); + } - public ErrorCode build() { - return builder.build(); - } -} \ No newline at end of file + public ErrorCode build() { + return builder.build(); + } +} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/MonitoringUploadErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/MonitoringUploadErrorBuilder.java index eed56e1a1a..0c5fb45380 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/MonitoringUploadErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/MonitoringUploadErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,43 +17,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.MONITORING_UPLOAD_INVALID; + import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.versioning.dao.types.Version; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.MONITORING_UPLOAD_INVALID; - public class MonitoringUploadErrorBuilder extends BaseErrorBuilder { - private static final String UPLOAD_INVALID_DETAILED_MSG = - "Monitoring file uploaded for vendor software product with Id %s and version %s is invalid: %s"; + private static final String UPLOAD_INVALID_DETAILED_MSG = "Monitoring file uploaded for vendor software product with Id %s and version %s is invalid: %s"; - /** - * Instantiates a new Mib upload error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - * @param error the error - */ - public MonitoringUploadErrorBuilder(String vendorSoftwareProductId, Version version, - String error) { - getErrorCodeBuilder().withId(MONITORING_UPLOAD_INVALID); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String.format(UPLOAD_INVALID_DETAILED_MSG, - vendorSoftwareProductId, version == null ? null : version.getId(), error)); - } + /** + * Instantiates a new Mib upload error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + * @param error the error + */ + public MonitoringUploadErrorBuilder(String vendorSoftwareProductId, Version version, String error) { + getErrorCodeBuilder().withId(MONITORING_UPLOAD_INVALID); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder() + .withMessage(String.format(UPLOAD_INVALID_DETAILED_MSG, vendorSoftwareProductId, version == null ? null : version.getId(), error)); + } - /** - * Instantiates a new Mib upload error builder. - * - * @param errorMessage the error message - */ - public MonitoringUploadErrorBuilder(String errorMessage) { - getErrorCodeBuilder().withId(MONITORING_UPLOAD_INVALID); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(errorMessage); - } + /** + * Instantiates a new Mib upload error builder. + * + * @param errorMessage the error message + */ + public MonitoringUploadErrorBuilder(String errorMessage) { + getErrorCodeBuilder().withId(MONITORING_UPLOAD_INVALID); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(errorMessage); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicErrorBuilder.java index 5eb7520a38..0d63222cf5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.NIC_NAME_FORMAT_NOT_ALLOWED; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.NIC_NAME_FORMAT_NOT_ALLOWED; - /** * The NIC error builder. */ public class NicErrorBuilder { - private static final String NIC_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" - + ": name : must match %s"; - private NicErrorBuilder() { + private static final String NIC_NAME_FORMAT_MSG = "Field does not conform to predefined criteria" + ": name : must match %s"; + private NicErrorBuilder() { } /** diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicInternalNetworkErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicInternalNetworkErrorBuilder.java index 5e7d8b98e3..69fabbc89f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicInternalNetworkErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicInternalNetworkErrorBuilder.java @@ -13,54 +13,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; - import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK; import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.NETWORK_TYPE_UPDATE_NOT_ALLOWED; -public class NicInternalNetworkErrorBuilder { - private static final String NULL_NETWORKID_NOT_ALLOWED_MSG = - "Internal Networks are currently not supported for VSP created Manually, so please fix all the NIC to be of Type External and re-submit the VSP."; - - private static final String NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK_MSG = - "Invalid request, Network Description not allowed for Internal Networks"; - private static final String NETWORK_TYPE_UPDATE_NOT_ALLOWED_MSG = - "Invalid request, Network Type Update not allowed for a Nic"; - - private NicInternalNetworkErrorBuilder() { - - } - - - public static ErrorCode getNicNullNetworkIdInternalNetworkIdErrorBuilder(){ - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes.NULL_NETWORKID_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(NULL_NETWORKID_NOT_ALLOWED_MSG); - return builder.build(); - } - - - public static ErrorCode getNetworkDescriptionInternalNetworkErrorBuilder(){ - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK_MSG); - return builder.build(); - } - - - public static ErrorCode getNetworkTypeErrorBuilder(){ - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(NETWORK_TYPE_UPDATE_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(NETWORK_TYPE_UPDATE_NOT_ALLOWED_MSG); - return builder.build(); - } +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +public class NicInternalNetworkErrorBuilder { + private static final String NULL_NETWORKID_NOT_ALLOWED_MSG = "Internal Networks are currently not supported for VSP created Manually, so please fix all the NIC to be of Type External and re-submit the VSP."; + private static final String NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK_MSG = "Invalid request, Network Description not allowed for Internal Networks"; + private static final String NETWORK_TYPE_UPDATE_NOT_ALLOWED_MSG = "Invalid request, Network Type Update not allowed for a Nic"; + + private NicInternalNetworkErrorBuilder() { + } + + public static ErrorCode getNicNullNetworkIdInternalNetworkIdErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VendorSoftwareProductErrorCodes.NULL_NETWORKID_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(NULL_NETWORKID_NOT_ALLOWED_MSG); + return builder.build(); + } + + public static ErrorCode getNetworkDescriptionInternalNetworkErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK_MSG); + return builder.build(); + } + + public static ErrorCode getNetworkTypeErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(NETWORK_TYPE_UPDATE_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(NETWORK_TYPE_UPDATE_NOT_ALLOWED_MSG); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicNetworkIdNotAllowedExternalNetworkErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicNetworkIdNotAllowedExternalNetworkErrorBuilder.java index c40fdee62d..df7e9b30a7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicNetworkIdNotAllowedExternalNetworkErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NicNetworkIdNotAllowedExternalNetworkErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; public class NicNetworkIdNotAllowedExternalNetworkErrorBuilder { - private static final String NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK_MSG = - "Invalid request,NetworkId not allowed for External Networks"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public NicNetworkIdNotAllowedExternalNetworkErrorBuilder(){ - builder.withId(VendorSoftwareProductErrorCodes.NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK_MSG)); - } - public ErrorCode build() { - return builder.build(); - } + private static final String NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK_MSG = "Invalid request,NetworkId not allowed for External Networks"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public NicNetworkIdNotAllowedExternalNetworkErrorBuilder() { + builder.withId(VendorSoftwareProductErrorCodes.NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK_MSG)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NotSupportedHeatOnboardMethodErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NotSupportedHeatOnboardMethodErrorBuilder.java index 14bfe8827d..328bd87269 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NotSupportedHeatOnboardMethodErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/NotSupportedHeatOnboardMethodErrorBuilder.java @@ -13,79 +13,75 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.DELETE_IMAGE_NOT_ALLOWED; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.*; - public class NotSupportedHeatOnboardMethodErrorBuilder { - private static final String ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = - "NIC cannot be added for VSPs onboarded with HEAT."; - private static final String ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = - "Compute flavor cannot be added for VSPs onboarded with HEAT."; - private static final String IMAGE_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = - "Image cannot be added for VSPs onboarded with HEAT."; - private static final String DELETE_IMAGE_NOT_ALLOWED_MSG = - "Image cannot be deleted for VSPs onboarded with HEAT."; - private static final String DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG = - "Deployment Flavor cannot be deleted for VSPs onboarded with HEAT."; - private static final String EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG = - "Deployment Flavor cannot be edited for VSPs onboarded with HEAT."; - - private NotSupportedHeatOnboardMethodErrorBuilder() { - - } + private static final String ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "NIC cannot be added for VSPs onboarded with HEAT."; + private static final String ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "Compute flavor cannot be added for VSPs onboarded with HEAT."; + private static final String IMAGE_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG = "Image cannot be added for VSPs onboarded with HEAT."; + private static final String DELETE_IMAGE_NOT_ALLOWED_MSG = "Image cannot be deleted for VSPs onboarded with HEAT."; + private static final String DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG = "Deployment Flavor cannot be deleted for VSPs onboarded with HEAT."; + private static final String EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG = "Deployment Flavor cannot be edited for VSPs onboarded with HEAT."; - public static ErrorCode getAddNicNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); - return builder.build(); - } + private NotSupportedHeatOnboardMethodErrorBuilder() { + } - public static ErrorCode getAddComputeNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); - return builder.build(); - } + public static ErrorCode getAddNicNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); + return builder.build(); + } - public static ErrorCode getAddImageNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(IMAGE_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); - return builder.build(); - } + public static ErrorCode getAddComputeNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); + return builder.build(); + } - public static ErrorCode getDelImageNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(DELETE_IMAGE_NOT_ALLOWED); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(DELETE_IMAGE_NOT_ALLOWED_MSG); - return builder.build(); - } + public static ErrorCode getAddImageNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(IMAGE_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING_MSG); + return builder.build(); + } - public static ErrorCode getDelDeploymentFlavorNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG); - return builder.build(); - } + public static ErrorCode getDelImageNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(DELETE_IMAGE_NOT_ALLOWED); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(DELETE_IMAGE_NOT_ALLOWED_MSG); + return builder.build(); + } - public static ErrorCode getUpdateDfNotSupportedHeatOnboardMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG); - return builder.build(); - } + public static ErrorCode getDelDeploymentFlavorNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG); + return builder.build(); + } + public static ErrorCode getUpdateDfNotSupportedHeatOnboardMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_MSG); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OnboardingMethodErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OnboardingMethodErrorBuilder.java index b30455156c..c7f130dd67 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OnboardingMethodErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OnboardingMethodErrorBuilder.java @@ -13,36 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.VSP_INVALID_ONBOARDING_METHOD; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.VSP_INVALID_ONBOARDING_METHOD; - /** * The type Onboarding method error builder. */ public class OnboardingMethodErrorBuilder { - private static final String VSP_INVALID_ONBOARDING_METHOD_MSG = - "The onboardingMethod value doesn't meet the expected attribute value."; + private static final String VSP_INVALID_ONBOARDING_METHOD_MSG = "The onboardingMethod value doesn't meet the expected attribute value."; - private OnboardingMethodErrorBuilder() { - - } + private OnboardingMethodErrorBuilder() { + } - /** - * Get invalid onboarding method error builder error code. - * - * @return the error code - */ - public static ErrorCode getInvalidOnboardingMethodErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VSP_INVALID_ONBOARDING_METHOD); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(VSP_INVALID_ONBOARDING_METHOD_MSG); - return builder.build(); - } + /** + * Get invalid onboarding method error builder error code. + * + * @return the error code + */ + public static ErrorCode getInvalidOnboardingMethodErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VSP_INVALID_ONBOARDING_METHOD); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(VSP_INVALID_ONBOARDING_METHOD_MSG); + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OrchestrationTemplateNotFoundErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OrchestrationTemplateNotFoundErrorBuilder.java index 84ce956911..3c6d611389 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OrchestrationTemplateNotFoundErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/OrchestrationTemplateNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ORCHESTRATION_NOT_FOUND; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.ORCHESTRATION_NOT_FOUND; - public class OrchestrationTemplateNotFoundErrorBuilder { - private static final String ORCHESTRATION_TEMPLATE_NOT_FOUND_MESSAGE = - "Failed to get orchestration template for VSP with id %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Orchestration template not found error builder. - * - * @param vspId the vsp id - */ - public OrchestrationTemplateNotFoundErrorBuilder(String vspId) { - builder.withId(ORCHESTRATION_NOT_FOUND) - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(ORCHESTRATION_TEMPLATE_NOT_FOUND_MESSAGE, vspId)); - } + private static final String ORCHESTRATION_TEMPLATE_NOT_FOUND_MESSAGE = "Failed to get orchestration template for VSP with id %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Orchestration template not found error builder. + * + * @param vspId the vsp id + */ + public OrchestrationTemplateNotFoundErrorBuilder(String vspId) { + builder.withId(ORCHESTRATION_NOT_FOUND).withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(ORCHESTRATION_TEMPLATE_NOT_FOUND_MESSAGE, vspId)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageInvalidErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageInvalidErrorBuilder.java index ce9794aa3b..c0e4557f3a 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageInvalidErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageInvalidErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,44 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.PACKAGE_INVALID; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.PACKAGE_INVALID; - /** * The type Package invalid error builder. */ public class PackageInvalidErrorBuilder { - private static final String PACKAGE_INVALID_MSG = - "Package for vendor software product with Id %s and version %s is invalid " - + "(does not contain translated data)."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Package invalid error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public PackageInvalidErrorBuilder(String vendorSoftwareProductId, Version version) { - builder.withId(PACKAGE_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(PACKAGE_INVALID_MSG, - vendorSoftwareProductId, version == null ? null : version.toString())); - } + private static final String PACKAGE_INVALID_MSG = + "Package for vendor software product with Id %s and version %s is invalid " + "(does not contain translated data)."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Package invalid error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public PackageInvalidErrorBuilder(String vendorSoftwareProductId, Version version) { + builder.withId(PACKAGE_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(PACKAGE_INVALID_MSG, vendorSoftwareProductId, version == null ? null : version.toString())); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageNotFoundErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageNotFoundErrorBuilder.java index 54ae9ce398..ef80e4d8db 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageNotFoundErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/PackageNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,37 +24,35 @@ import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; public class PackageNotFoundErrorBuilder { - private static final String PACKAGE_VERSION_NOT_FOUND_MSG = - "Package for vendor software product with Id %s and version %s does not exist."; - private static final String PACKAGE_NOT_FOUND_MSG = - "Package for vendor software product with Id %s does not exist."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Package not found error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public PackageNotFoundErrorBuilder(String vendorSoftwareProductId, Version version) { - builder.withId(VendorSoftwareProductErrorCodes.PACKAGE_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(PACKAGE_VERSION_NOT_FOUND_MSG, - vendorSoftwareProductId, version == null ? null : version.toString())); - } + private static final String PACKAGE_VERSION_NOT_FOUND_MSG = "Package for vendor software product with Id %s and version %s does not exist."; + private static final String PACKAGE_NOT_FOUND_MSG = "Package for vendor software product with Id %s does not exist."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Package not found error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public PackageNotFoundErrorBuilder(String vendorSoftwareProductId, Version version) { + builder.withId(VendorSoftwareProductErrorCodes.PACKAGE_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(PACKAGE_VERSION_NOT_FOUND_MSG, vendorSoftwareProductId, version == null ? null : version.toString())); + } - /** - * Instantiates a new Package not found error builder. - * - * @param vendorSoftwareProductId the vendor software product id - */ - public PackageNotFoundErrorBuilder(String vendorSoftwareProductId) { - builder.withId(VendorSoftwareProductErrorCodes.PACKAGE_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(PACKAGE_NOT_FOUND_MSG, vendorSoftwareProductId)); - } + /** + * Instantiates a new Package not found error builder. + * + * @param vendorSoftwareProductId the vendor software product id + */ + public PackageNotFoundErrorBuilder(String vendorSoftwareProductId) { + builder.withId(VendorSoftwareProductErrorCodes.PACKAGE_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(PACKAGE_NOT_FOUND_MSG, vendorSoftwareProductId)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/TranslationFileCreationErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/TranslationFileCreationErrorBuilder.java index fd8acd1497..73193abeb9 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/TranslationFileCreationErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/TranslationFileCreationErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,35 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.TRANSLATION_FILE_CREATION; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.TRANSLATION_FILE_CREATION; - public class TranslationFileCreationErrorBuilder { - private static final String TRANSLATION_FILE_CREATION_ERROR_MSG = - "Error while trying to create translation file from the package of vendor software product " - + "with Id %s and version %s."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Translation file creation error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public TranslationFileCreationErrorBuilder(String vendorSoftwareProductId, Version version) { - builder.withId(TRANSLATION_FILE_CREATION); - builder.withCategory(ErrorCategory.SYSTEM); - builder.withMessage(String - .format(TRANSLATION_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId, version.toString())); - } + private static final String TRANSLATION_FILE_CREATION_ERROR_MSG = + "Error while trying to create translation file from the package of vendor software product " + "with Id %s and version %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Translation file creation error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public TranslationFileCreationErrorBuilder(String vendorSoftwareProductId, Version version) { + builder.withId(TRANSLATION_FILE_CREATION); + builder.withCategory(ErrorCategory.SYSTEM); + builder.withMessage(String.format(TRANSLATION_FILE_CREATION_ERROR_MSG, vendorSoftwareProductId, version.toString())); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/UploadInvalidErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/UploadInvalidErrorBuilder.java index f808d542f1..5f2abbfbcc 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/UploadInvalidErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/UploadInvalidErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,60 +17,52 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; -import java.util.Map; - public class UploadInvalidErrorBuilder extends BaseErrorBuilder { - private static final String UPLOAD_INVALID_DETAILED_MSG = - "File uploaded for vendor software product with Id %s and version %s is invalid: %s"; - private static final String UPLOAD_INVALID_MSG = "Uploaded file is invalid"; - /** - * Instantiates a new Upload invalid error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - * @param errors the errors - */ - public UploadInvalidErrorBuilder(String vendorSoftwareProductId, Version version, - Map> errors) { - getErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.UPLOAD_INVALID); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(UPLOAD_INVALID_DETAILED_MSG, vendorSoftwareProductId, version.toString(), - toString(errors))); - } + private static final String UPLOAD_INVALID_DETAILED_MSG = "File uploaded for vendor software product with Id %s and version %s is invalid: %s"; + private static final String UPLOAD_INVALID_MSG = "Uploaded file is invalid"; - /** - * Instantiates a new Upload invalid error builder. - */ - public UploadInvalidErrorBuilder() { - getErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.UPLOAD_INVALID); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(UPLOAD_INVALID_MSG); - } + /** + * Instantiates a new Upload invalid error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + * @param errors the errors + */ + public UploadInvalidErrorBuilder(String vendorSoftwareProductId, Version version, Map> errors) { + getErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.UPLOAD_INVALID); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(UPLOAD_INVALID_DETAILED_MSG, vendorSoftwareProductId, version.toString(), toString(errors))); + } - private String toString(Map> errors) { - StringBuilder sb = new StringBuilder(); - errors.entrySet().stream() - .forEach(entry -> singleErrorToString(sb, entry.getKey(), entry.getValue())); - return sb.toString(); - } + /** + * Instantiates a new Upload invalid error builder. + */ + public UploadInvalidErrorBuilder() { + getErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.UPLOAD_INVALID); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(UPLOAD_INVALID_MSG); + } - private void singleErrorToString(StringBuilder sb, String fileName, List errors) { - sb.append(System.lineSeparator()); - sb.append(fileName); - sb.append(sb.append(": ")); - errors.stream().forEach( - error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("], ")); - } + private String toString(Map> errors) { + StringBuilder sb = new StringBuilder(); + errors.entrySet().stream().forEach(entry -> singleErrorToString(sb, entry.getKey(), entry.getValue())); + return sb.toString(); + } + private void singleErrorToString(StringBuilder sb, String fileName, List errors) { + sb.append(System.lineSeparator()); + sb.append(fileName); + sb.append(sb.append(": ")); + errors.stream().forEach(error -> sb.append(error.getMessage()).append("[").append(error.getLevel()).append("], ")); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductInvalidErrorBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductInvalidErrorBuilder.java index c3a2862e39..1555bd77ee 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductInvalidErrorBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductInvalidErrorBuilder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -21,69 +20,59 @@ import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.versioning.dao.types.Version; public class VendorSoftwareProductInvalidErrorBuilder { - private static final String VSP_INVALID_MSG = - "Vendor software product with Id %s and version %s is invalid - does not contain " - + "service model."; - private static final String VSP_INVALID_MISSING_DEPLOYMENT_FLAVOR_MSG = "VSP has to have a " - + "minimum of one Deployment Flavor defined for being able to be instantiated.Please add a " - + "Deployment Flavor and re-submit the VSP."; - private static final String CANDIDATE_DATA_NOT_PROCESSED_OR_ABORTED = "Uploaded network package" - + " file %s was not processed/aborted."; - private static final String INVALID_PROCESSED_CANDIDATE = "Uploaded network package file %s" - + " is invalid and need to be aborted"; - private VendorSoftwareProductInvalidErrorBuilder() { + private static final String VSP_INVALID_MSG = + "Vendor software product with Id %s and version %s is invalid - does not contain " + "service model."; + private static final String VSP_INVALID_MISSING_DEPLOYMENT_FLAVOR_MSG = + "VSP has to have a " + "minimum of one Deployment Flavor defined for being able to be instantiated.Please add a " + + "Deployment Flavor and re-submit the VSP."; + private static final String CANDIDATE_DATA_NOT_PROCESSED_OR_ABORTED = "Uploaded network package" + " file %s was not processed/aborted."; + private static final String INVALID_PROCESSED_CANDIDATE = "Uploaded network package file %s" + " is invalid and need to be aborted"; - } + private VendorSoftwareProductInvalidErrorBuilder() { + } - /** - * Instantiates a new Vendor software product invalid error builder. - * - * @param vendorSoftwareProductId the vendor software product id - * @param version the version - */ - public static ErrorCode vendorSoftwareProductMissingServiceModelErrorBuilder(String - vendorSoftwareProductId, - Version version) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes.VSP_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder - .withMessage(String.format(VSP_INVALID_MSG, vendorSoftwareProductId, version.getId())); - return builder.build(); - } + /** + * Instantiates a new Vendor software product invalid error builder. + * + * @param vendorSoftwareProductId the vendor software product id + * @param version the version + */ + public static ErrorCode vendorSoftwareProductMissingServiceModelErrorBuilder(String vendorSoftwareProductId, Version version) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VendorSoftwareProductErrorCodes.VSP_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VSP_INVALID_MSG, vendorSoftwareProductId, version.getId())); + return builder.build(); + } - /** - * Instantiates a new Vendor software product invalid error builder. - */ - public static ErrorCode vspMissingDeploymentFlavorErrorBuilder() { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(VendorSoftwareProductErrorCodes.VSP_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder - .withMessage(VSP_INVALID_MISSING_DEPLOYMENT_FLAVOR_MSG); - return builder.build(); - } + /** + * Instantiates a new Vendor software product invalid error builder. + */ + public static ErrorCode vspMissingDeploymentFlavorErrorBuilder() { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(VendorSoftwareProductErrorCodes.VSP_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(VSP_INVALID_MISSING_DEPLOYMENT_FLAVOR_MSG); + return builder.build(); + } - public static ErrorCode candidateDataNotProcessedOrAbortedErrorBuilder(String fileName) { - ErrorCode.ErrorCodeBuilder builder = getErrorCodeBuilder(VendorSoftwareProductErrorCodes - .VSP_INVALID, ErrorCategory.APPLICATION); - builder.withMessage(String.format(CANDIDATE_DATA_NOT_PROCESSED_OR_ABORTED, fileName)); - return builder.build(); - } + public static ErrorCode candidateDataNotProcessedOrAbortedErrorBuilder(String fileName) { + ErrorCode.ErrorCodeBuilder builder = getErrorCodeBuilder(VendorSoftwareProductErrorCodes.VSP_INVALID, ErrorCategory.APPLICATION); + builder.withMessage(String.format(CANDIDATE_DATA_NOT_PROCESSED_OR_ABORTED, fileName)); + return builder.build(); + } - public static ErrorCode invalidProcessedCandidate(String fileName) { - ErrorCode.ErrorCodeBuilder builder = getErrorCodeBuilder(VendorSoftwareProductErrorCodes - .VSP_INVALID, ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_PROCESSED_CANDIDATE, fileName)); - return builder.build(); - } + public static ErrorCode invalidProcessedCandidate(String fileName) { + ErrorCode.ErrorCodeBuilder builder = getErrorCodeBuilder(VendorSoftwareProductErrorCodes.VSP_INVALID, ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_PROCESSED_CANDIDATE, fileName)); + return builder.build(); + } - public static ErrorCode.ErrorCodeBuilder getErrorCodeBuilder(String errorCode, ErrorCategory - errorCategory) { - ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - builder.withId(errorCode); - builder.withCategory(errorCategory); - return builder; - } + public static ErrorCode.ErrorCodeBuilder getErrorCodeBuilder(String errorCode, ErrorCategory errorCategory) { + ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + builder.withId(errorCode); + builder.withCategory(errorCategory); + return builder; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/exception/OnboardPackageException.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/exception/OnboardPackageException.java index 2e88357e0b..4f487f8b50 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/exception/OnboardPackageException.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/exception/OnboardPackageException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.exception; public class OnboardPackageException extends Exception { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerFactoryImpl.java index 8d8dce878e..bd7ee1ee97 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManager; @@ -25,18 +24,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.ComponentDependencyModelManagerFa import org.openecomp.sdc.vendorsoftwareproduct.ComponentManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; -public class ComponentDependencyModelManagerFactoryImpl extends - ComponentDependencyModelManagerFactory { - - private static final ComponentDependencyModelManager INSTANCE = - new ComponentDependencyModelManagerImpl( - ComponentManagerFactory.getInstance().createInterface(), - ComponentDependencyModelDaoFactory.getInstance().createInterface() - ); +public class ComponentDependencyModelManagerFactoryImpl extends ComponentDependencyModelManagerFactory { - @Override - public ComponentDependencyModelManager createInterface() { - return INSTANCE; - } + private static final ComponentDependencyModelManager INSTANCE = new ComponentDependencyModelManagerImpl( + ComponentManagerFactory.getInstance().createInterface(), ComponentDependencyModelDaoFactory.getInstance().createInterface()); + @Override + public ComponentDependencyModelManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerImpl.java index 596ce5010f..71b3e4b672 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentDependencyModelManagerImpl.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.CoreException; @@ -29,84 +29,68 @@ import org.openecomp.sdc.vendorsoftwareproduct.errors.ComponentDependencyModelEr import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public class ComponentDependencyModelManagerImpl implements ComponentDependencyModelManager { - private ComponentManager componentManager; - private ComponentDependencyModelDao componentDependencyModelDao; - - public ComponentDependencyModelManagerImpl( - ComponentManager componentManager, ComponentDependencyModelDao componentDependencyModelDao) { - this.componentManager = componentManager; - this.componentDependencyModelDao = componentDependencyModelDao; - } - - @Override - public Collection list(String vspId, Version version) { - return componentDependencyModelDao - .list(new ComponentDependencyModelEntity(vspId, version, null)); - } + private ComponentManager componentManager; + private ComponentDependencyModelDao componentDependencyModelDao; - @Override - public ComponentDependencyModelEntity createComponentDependency(ComponentDependencyModelEntity - entity, String vspId, - Version version) { + public ComponentDependencyModelManagerImpl(ComponentManager componentManager, ComponentDependencyModelDao componentDependencyModelDao) { + this.componentManager = componentManager; + this.componentDependencyModelDao = componentDependencyModelDao; + } - validateComponentDependency(entity); - entity.setId(CommonMethods.nextUuId()); - componentDependencyModelDao.create(entity); - return entity; - } + @Override + public Collection list(String vspId, Version version) { + return componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null)); + } - private void validateComponentDependency(ComponentDependencyModelEntity entity) { - if (!StringUtils.isEmpty(entity.getSourceComponentId())) { - componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), - entity.getSourceComponentId()); - if (entity.getSourceComponentId().equals(entity.getTargetComponentId())) { - ErrorCode errorCode = - ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder(); - throw new CoreException(errorCode); - } - } else { - ErrorCode errorCode = ComponentDependencyModelErrorBuilder - .getNoSourceComponentErrorBuilder(); - throw new CoreException(errorCode); + @Override + public ComponentDependencyModelEntity createComponentDependency(ComponentDependencyModelEntity entity, String vspId, Version version) { + validateComponentDependency(entity); + entity.setId(CommonMethods.nextUuId()); + componentDependencyModelDao.create(entity); + return entity; } - if (!StringUtils.isEmpty(entity.getTargetComponentId())) { - componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), - entity.getTargetComponentId()); + private void validateComponentDependency(ComponentDependencyModelEntity entity) { + if (!StringUtils.isEmpty(entity.getSourceComponentId())) { + componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), entity.getSourceComponentId()); + if (entity.getSourceComponentId().equals(entity.getTargetComponentId())) { + ErrorCode errorCode = ComponentDependencyModelErrorBuilder.getSourceTargetComponentEqualErrorBuilder(); + throw new CoreException(errorCode); + } + } else { + ErrorCode errorCode = ComponentDependencyModelErrorBuilder.getNoSourceComponentErrorBuilder(); + throw new CoreException(errorCode); + } + if (!StringUtils.isEmpty(entity.getTargetComponentId())) { + componentManager.validateComponentExistence(entity.getVspId(), entity.getVersion(), entity.getTargetComponentId()); + } } - } - @Override - public void delete(String vspId, Version version, String dependencyId) { - ComponentDependencyModelEntity componentDependencyEntity = getComponentDependency(vspId, - version, dependencyId); - if (componentDependencyEntity != null) { - componentDependencyModelDao.delete(componentDependencyEntity); + @Override + public void delete(String vspId, Version version, String dependencyId) { + ComponentDependencyModelEntity componentDependencyEntity = getComponentDependency(vspId, version, dependencyId); + if (componentDependencyEntity != null) { + componentDependencyModelDao.delete(componentDependencyEntity); + } } - } - @Override - public void update(ComponentDependencyModelEntity entity) { - getComponentDependency(entity.getVspId(), entity.getVersion(), entity.getId()); - validateComponentDependency(entity); - componentDependencyModelDao.update(entity); - } + @Override + public void update(ComponentDependencyModelEntity entity) { + getComponentDependency(entity.getVspId(), entity.getVersion(), entity.getId()); + validateComponentDependency(entity); + componentDependencyModelDao.update(entity); + } - @Override - public ComponentDependencyModelEntity get(String vspId, Version version, String dependencyId) { - return getComponentDependency(vspId, version, dependencyId); - } + @Override + public ComponentDependencyModelEntity get(String vspId, Version version, String dependencyId) { + return getComponentDependency(vspId, version, dependencyId); + } - private ComponentDependencyModelEntity getComponentDependency(String vspId, Version version, - String dependencyId) { - ComponentDependencyModelEntity retrieved = componentDependencyModelDao.get( - new ComponentDependencyModelEntity(vspId, version, dependencyId)); - VersioningUtil.validateEntityExistence(retrieved, new ComponentDependencyModelEntity( - vspId, version, dependencyId), VspDetails.ENTITY_TYPE); - return retrieved; - } + private ComponentDependencyModelEntity getComponentDependency(String vspId, Version version, String dependencyId) { + ComponentDependencyModelEntity retrieved = componentDependencyModelDao.get(new ComponentDependencyModelEntity(vspId, version, dependencyId)); + VersioningUtil.validateEntityExistence(retrieved, new ComponentDependencyModelEntity(vspId, version, dependencyId), VspDetails.ENTITY_TYPE); + return retrieved; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerFactoryImpl.java index 133ebdb50d..526aea13a4 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.ComponentManager; @@ -28,16 +27,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; public class ComponentManagerFactoryImpl extends ComponentManagerFactory { - private static final ComponentManager INSTANCE = - new ComponentManagerImpl( - ComponentDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - NicManagerFactory.getInstance().createInterface(), - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface() - ); - @Override - public ComponentManager createInterface() { - return INSTANCE; - } + private static final ComponentManager INSTANCE = new ComponentManagerImpl(ComponentDaoFactory.getInstance().createInterface(), + CompositionEntityDataManagerFactory.getInstance().createInterface(), NicManagerFactory.getInstance().createInterface(), + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); + + @Override + public ComponentManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImpl.java index ca8757dd11..a4527f5030 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComponentManagerImpl.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.COMPUTE_TYPE_PREFIX; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.common.errors.CoreException; @@ -42,220 +47,174 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.COMPUTE_TYPE_PREFIX; - public class ComponentManagerImpl implements ComponentManager { - private final ComponentDao componentDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final NicManager nicManager; - private final VendorSoftwareProductInfoDao vspInfoDao; - - public ComponentManagerImpl(ComponentDao componentDao, - CompositionEntityDataManager compositionEntityDataManager, - NicManager nicManager, - VendorSoftwareProductInfoDao vspInfoDao) { - this.componentDao = componentDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.nicManager = nicManager; - this.vspInfoDao = vspInfoDao; - } - @Override - public Collection listComponents(String vspId, Version version) { - return componentDao.list(new ComponentEntity(vspId, version, null)); - } - - @Override - public void deleteComponents(String vspId, Version version) { - if (!vspInfoDao.isManual(vspId, version)) { - throw new CoreException( - new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + private final ComponentDao componentDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final NicManager nicManager; + private final VendorSoftwareProductInfoDao vspInfoDao; + + public ComponentManagerImpl(ComponentDao componentDao, CompositionEntityDataManager compositionEntityDataManager, NicManager nicManager, + VendorSoftwareProductInfoDao vspInfoDao) { + this.componentDao = componentDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.nicManager = nicManager; + this.vspInfoDao = vspInfoDao; } - } - - @Override - public ComponentEntity createComponent(ComponentEntity component) { - final String vfcAddNotAllowedInHeatOnboardingMsg = - "VFCs cannot be added for VSPs onboarded with HEAT."; - ComponentEntity createdComponent; - if (!vspInfoDao.isManual(component.getVspId(), component.getVersion())) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder() - .withId(VendorSoftwareProductErrorCodes.VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING) - .withMessage(vfcAddNotAllowedInHeatOnboardingMsg).build()); - } else { - validateComponentManual(component); - updateComponentName(component); - createdComponent = compositionEntityDataManager.createComponent(component, true); + @Override + public Collection listComponents(String vspId, Version version) { + return componentDao.list(new ComponentEntity(vspId, version, null)); } - return createdComponent; - } - private void updateComponentName(ComponentEntity component) { - ComponentData data = component.getComponentCompositionData(); - data.setName(COMPUTE_TYPE_PREFIX + data.getDisplayName()); - component.setComponentCompositionData(data); - } - - private void validateComponentManual(ComponentEntity component) { - final String vspVfcCountExceedMsg = "Creation of only one VFC per " - + "VSP allowed."; - - final String vspVfcDuplicateNameMsg = "VFC with specified name " - + "already present in given VSP."; - - Collection vspComponentList = - listComponents(component.getVspId(), component.getVersion()); - if (!vspComponentList.isEmpty()) { - //1707 release only supports 1 VFC in VSP (manual creation) - throw new CoreException( - new ErrorCode.ErrorCodeBuilder() - .withId(VendorSoftwareProductErrorCodes.VSP_VFC_COUNT_EXCEED) - .withMessage(vspVfcCountExceedMsg).build()); + @Override + public void deleteComponents(String vspId, Version version) { + if (!vspInfoDao.isManual(vspId, version)) { + throw new CoreException(new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + } } - if (!isVfcNameUnique(vspComponentList, - component.getComponentCompositionData().getDisplayName())) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder() - .withId(VendorSoftwareProductErrorCodes.VSP_VFC_DUPLICATE_NAME) - .withMessage(vspVfcDuplicateNameMsg).build()); - } - } - private boolean isVfcNameUnique(Collection component, String displayName) { - for (ComponentEntity comp : component) { - if (comp.getComponentCompositionData().getDisplayName().equalsIgnoreCase(displayName)) { - return false; - } + @Override + public ComponentEntity createComponent(ComponentEntity component) { + final String vfcAddNotAllowedInHeatOnboardingMsg = "VFCs cannot be added for VSPs onboarded with HEAT."; + ComponentEntity createdComponent; + if (!vspInfoDao.isManual(component.getVspId(), component.getVersion())) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING) + .withMessage(vfcAddNotAllowedInHeatOnboardingMsg).build()); + } else { + validateComponentManual(component); + updateComponentName(component); + createdComponent = compositionEntityDataManager.createComponent(component, true); + } + return createdComponent; } - return true; - } - - @Override - public CompositionEntityValidationData updateComponent(ComponentEntity component) { - ComponentEntity retrieved = - getValidatedComponent(component.getVspId(), component.getVersion(), component.getId()); - boolean isManual = vspInfoDao.isManual(component.getVspId(), component.getVersion()); - if (isManual) { - validateComponentUpdateManual(retrieved); + private void updateComponentName(ComponentEntity component) { + ComponentData data = component.getComponentCompositionData(); + data.setName(COMPUTE_TYPE_PREFIX + data.getDisplayName()); + component.setComponentCompositionData(data); } - ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); - schemaInput.setManual(isManual); - schemaInput.setComponent(retrieved.getComponentCompositionData()); - - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(component, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - if (isManual) { - updateComponentName(component); - } - componentDao.update(component); + private void validateComponentManual(ComponentEntity component) { + final String vspVfcCountExceedMsg = "Creation of only one VFC per " + "VSP allowed."; + final String vspVfcDuplicateNameMsg = "VFC with specified name " + "already present in given VSP."; + Collection vspComponentList = listComponents(component.getVspId(), component.getVersion()); + if (!vspComponentList.isEmpty()) { + //1707 release only supports 1 VFC in VSP (manual creation) + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.VSP_VFC_COUNT_EXCEED).withMessage(vspVfcCountExceedMsg) + .build()); + } + if (!isVfcNameUnique(vspComponentList, component.getComponentCompositionData().getDisplayName())) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.VSP_VFC_DUPLICATE_NAME).withMessage(vspVfcDuplicateNameMsg) + .build()); + } } - return validationData; - } - private void validateComponentUpdateManual(ComponentEntity component) { - Collection vspComponentList = - listComponents(component.getVspId(), component.getVersion()); - //VFC name should be unique within VSP - //Removing VFC with same ID from list to avoid self compare - for (ComponentEntity ce : vspComponentList) { - if (ce.getId().equals(component.getId())) { - vspComponentList.remove(ce); - break; - } + private boolean isVfcNameUnique(Collection component, String displayName) { + for (ComponentEntity comp : component) { + if (comp.getComponentCompositionData().getDisplayName().equalsIgnoreCase(displayName)) { + return false; + } + } + return true; } - if (!isVfcNameUnique(vspComponentList, component.getComponentCompositionData() - .getDisplayName())) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder() - .withId(VendorSoftwareProductErrorCodes.VSP_VFC_DUPLICATE_NAME) - .withMessage("VFC with specified name already present in given VSP.").build()); + @Override + public CompositionEntityValidationData updateComponent(ComponentEntity component) { + ComponentEntity retrieved = getValidatedComponent(component.getVspId(), component.getVersion(), component.getId()); + boolean isManual = vspInfoDao.isManual(component.getVspId(), component.getVersion()); + if (isManual) { + validateComponentUpdateManual(retrieved); + } + ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); + schemaInput.setManual(isManual); + schemaInput.setComponent(retrieved.getComponentCompositionData()); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(component, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + if (isManual) { + updateComponentName(component); + } + componentDao.update(component); + } + return validationData; } - } - - @Override - public CompositionEntityResponse getComponent(String vspId, Version version, - String componentId) { - ComponentEntity componentEntity = getValidatedComponent(vspId, version, componentId); - ComponentData component = componentEntity.getComponentCompositionData(); - - ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - schemaInput.setComponent(component); - - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(componentId); - response.setData(component); - response.setSchema(getComponentCompositionSchema(schemaInput)); - return response; - } - @Override - public void deleteComponent(String vspId, Version version, String componentId) { - if (!vspInfoDao.isManual(vspId, version)) { - throw new CoreException( - new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + private void validateComponentUpdateManual(ComponentEntity component) { + Collection vspComponentList = listComponents(component.getVspId(), component.getVersion()); + //VFC name should be unique within VSP + + //Removing VFC with same ID from list to avoid self compare + for (ComponentEntity ce : vspComponentList) { + if (ce.getId().equals(component.getId())) { + vspComponentList.remove(ce); + break; + } + } + if (!isVfcNameUnique(vspComponentList, component.getComponentCompositionData().getDisplayName())) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.VSP_VFC_DUPLICATE_NAME) + .withMessage("VFC with specified name already present in given VSP.").build()); + } } - } - @Override - public QuestionnaireResponse getQuestionnaire(String vspId, Version version, - String componentId) { - QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); - ComponentEntity component = componentDao.getQuestionnaireData(vspId, version, componentId); - VersioningUtil - .validateEntityExistence(component, new ComponentEntity(vspId, version, componentId), - VspDetails.ENTITY_TYPE); + @Override + public CompositionEntityResponse getComponent(String vspId, Version version, String componentId) { + ComponentEntity componentEntity = getValidatedComponent(vspId, version, componentId); + ComponentData component = componentEntity.getComponentCompositionData(); + ComponentCompositionSchemaInput schemaInput = new ComponentCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + schemaInput.setComponent(component); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(componentId); + response.setData(component); + response.setSchema(getComponentCompositionSchema(schemaInput)); + return response; + } - questionnaireResponse.setData(component.getQuestionnaireData()); - List nicNames = nicManager.listNics(vspId, version, componentId).stream() - .map(nic -> nic.getNicCompositionData().getName()).collect(Collectors.toList()); - questionnaireResponse.setSchema(getComponentQuestionnaireSchema( - new ComponentQuestionnaireSchemaInput(nicNames, questionnaireResponse.getData() == null - ? null : JsonUtil.json2Object(questionnaireResponse.getData(), Map.class), - null, false))); - return questionnaireResponse; - } + @Override + public void deleteComponent(String vspId, Version version, String componentId) { + if (!vspInfoDao.isManual(vspId, version)) { + throw new CoreException(new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + } + } - @Override - public void updateQuestionnaire(String vspId, Version version, String componentId, - String questionnaireData) { - validateComponentExistence(vspId, version, componentId); + @Override + public QuestionnaireResponse getQuestionnaire(String vspId, Version version, String componentId) { + QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); + ComponentEntity component = componentDao.getQuestionnaireData(vspId, version, componentId); + VersioningUtil.validateEntityExistence(component, new ComponentEntity(vspId, version, componentId), VspDetails.ENTITY_TYPE); + questionnaireResponse.setData(component.getQuestionnaireData()); + List nicNames = nicManager.listNics(vspId, version, componentId).stream().map(nic -> nic.getNicCompositionData().getName()) + .collect(Collectors.toList()); + questionnaireResponse.setSchema(getComponentQuestionnaireSchema(new ComponentQuestionnaireSchemaInput(nicNames, + questionnaireResponse.getData() == null ? null : JsonUtil.json2Object(questionnaireResponse.getData(), Map.class), null, false))); + return questionnaireResponse; + } - componentDao.updateQuestionnaireData(vspId, version, componentId, questionnaireData); - } + @Override + public void updateQuestionnaire(String vspId, Version version, String componentId, String questionnaireData) { + validateComponentExistence(vspId, version, componentId); + componentDao.updateQuestionnaireData(vspId, version, componentId, questionnaireData); + } - @Override - public void validateComponentExistence(String vspId, Version version, String componentId) { - getValidatedComponent(vspId, version, componentId); - } + @Override + public void validateComponentExistence(String vspId, Version version, String componentId) { + getValidatedComponent(vspId, version, componentId); + } - private ComponentEntity getValidatedComponent(String vspId, Version version, String componentId) { - ComponentEntity retrieved = componentDao.get(new ComponentEntity(vspId, version, componentId)); - VersioningUtil - .validateEntityExistence(retrieved, new ComponentEntity(vspId, version, componentId), - VspDetails.ENTITY_TYPE); - return retrieved; - } + private ComponentEntity getValidatedComponent(String vspId, Version version, String componentId) { + ComponentEntity retrieved = componentDao.get(new ComponentEntity(vspId, version, componentId)); + VersioningUtil.validateEntityExistence(retrieved, new ComponentEntity(vspId, version, componentId), VspDetails.ENTITY_TYPE); + return retrieved; + } - protected String getComponentCompositionSchema(ComponentCompositionSchemaInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.component, schemaInput); - } + protected String getComponentCompositionSchema(ComponentCompositionSchemaInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.component, schemaInput); + } - protected String getComponentQuestionnaireSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.component, - schemaInput); - } + protected String getComponentQuestionnaireSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.component, schemaInput); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerFactoryImpl.java index 209fecc0da..ffe774ebfb 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.*; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; public class CompositionEntityDataManagerFactoryImpl extends CompositionEntityDataManagerFactory { - @Override - public CompositionEntityDataManager createInterface() { - // this class is stateful! it must be recreated from scratch on every use!!! - return new CompositionEntityDataManagerImpl( - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - ComponentDaoFactory.getInstance().createInterface(), - NicDaoFactory.getInstance().createInterface(), - NetworkDaoFactory.getInstance().createInterface(), - ImageDaoFactory.getInstance().createInterface(), - ComputeDaoFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface()); - } + @Override + public CompositionEntityDataManager createInterface() { + // this class is stateful! it must be recreated from scratch on every use!!! + return new CompositionEntityDataManagerImpl(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), + ComponentDaoFactory.getInstance().createInterface(), NicDaoFactory.getInstance().createInterface(), + NetworkDaoFactory.getInstance().createInterface(), ImageDaoFactory.getInstance().createInterface(), + ComputeDaoFactory.getInstance().createInterface(), DeploymentFlavorDaoFactory.getInstance().createInterface()); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImpl.java index e9c75319f5..d239615cab 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/CompositionEntityDataManagerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import java.util.ArrayList; @@ -72,535 +71,434 @@ import org.openecomp.sdc.versioning.dao.types.Version; public class CompositionEntityDataManagerImpl implements CompositionEntityDataManager { - private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR = - "COMPOSITION_ENTITY_DATA_MANAGER_ERR"; - private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG = - "Invalid input: %s may not be null"; - private static final String MISSING_OR_INVALID_QUESTIONNAIRE_MSG = - "Data is missing/invalid for this %s. Please refill and resubmit."; - - private static final Logger logger = - LoggerFactory.getLogger(CompositionEntityDataManagerImpl.class); - private Map entities = new HashMap<>(); - private Map nonDynamicSchemas = - new EnumMap<>(CompositionEntityType.class); - private List roots = new ArrayList<>(); - - private VendorSoftwareProductInfoDao vspInfoDao; - private ComponentDao componentDao; - private NicDao nicDao; - private NetworkDao networkDao; - private ImageDao imageDao; - private ComputeDao computeDao; - private DeploymentFlavorDao deploymentFlavorDao; - - public CompositionEntityDataManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, - ComponentDao componentDao, - NicDao nicDao, NetworkDao networkDao, - ImageDao imageDao, ComputeDao computeDao, - DeploymentFlavorDao deploymentFlavorDao) { - this.vspInfoDao = vspInfoDao; - this.componentDao = componentDao; - this.nicDao = nicDao; - this.networkDao = networkDao; - this.imageDao = imageDao; - this.computeDao = computeDao; - this.deploymentFlavorDao = deploymentFlavorDao; - } - - /** - * Validate entity composition entity validation data. - * - * @param entity the entity - * @param schemaTemplateContext the schema template context - * @param schemaTemplateInput the schema template input - * @return the composition entity validation data - */ - @Override - public CompositionEntityValidationData validateEntity(CompositionEntity entity, - SchemaTemplateContext schemaTemplateContext, - SchemaTemplateInput schemaTemplateInput) { - if (entity == null) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) - .build()); - } - if (schemaTemplateContext == null) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "schema template context")) - .build()); - } - - CompositionEntityValidationData validationData = - new CompositionEntityValidationData(entity.getType(), entity.getId()); - String json = - schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() - : entity.getQuestionnaireData(); - validationData.setErrors(JsonUtil.validate( - json == null ? JsonUtil.object2Json(new Object()) : json, - generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); - return validationData; - } - - /** - * Add entity. - * - * @param entity the entity - * @param schemaTemplateInput the schema template input - */ - @Override - public void addEntity(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput) { - if (entity == null) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) - .build()); - } - entities.put(entity.getCompositionEntityId(), - new CompositionEntityData(entity, schemaTemplateInput)); - } - - /** - * Validate entities questionnaire map. - * - * @return the map - */ - @Override - public Map> validateEntitiesQuestionnaire() { - Map> errorsByEntityId = new HashMap<>(); - entities.forEach((key, value) -> { - Collection errors = validateQuestionnaire(value); - if (errors != null) { - errorsByEntityId.put(key, errors); - } - }); - return errorsByEntityId; - } - - /** - * Build trees. - */ - @Override - public void buildTrees() { - Map entitiesValidationData = - new HashMap<>(); - entities.forEach((key, value) -> addValidationDataEntity(entitiesValidationData, key, - value.entity)); - } - - public Collection getTrees() { - return roots; - } - - @Override - public void saveCompositionData(String vspId, Version version, CompositionData compositionData) { - if (Objects.isNull(compositionData)) { - return; - } - - Map networkIdByName = saveNetworks(vspId, version, compositionData); - saveComponents(vspId, version, compositionData, networkIdByName); - } - - @Override - public Set getAllErrorsByVsp(String vspId) { - Set entitiesWithErrors = new HashSet<>(); - for (CompositionEntityValidationData root : roots) { - if (root.getEntityId().equals(vspId)) { - getEntityListWithErrors(root, entitiesWithErrors); - break; - } - } - - if (CollectionUtils.isNotEmpty(entitiesWithErrors)) { - updateValidationCompositionEntityName(entitiesWithErrors); - return entitiesWithErrors; - } - - return new HashSet<>(); - } - - private void saveComponents(String vspId, Version version, CompositionData compositionData, - Map networkIdByName) { - if (CollectionUtils.isNotEmpty(compositionData.getComponents())) { - for (Component component : compositionData.getComponents()) { - ComponentEntity componentEntity = new ComponentEntity(vspId, version, null); - componentEntity.setComponentCompositionData(component.getData()); - - String componentId = createComponent(componentEntity, false).getId(); - - saveImagesByComponent(vspId, version, component, componentId); - saveComputesFlavorByComponent(vspId, version, component, componentId); - - saveNicsByComponent(vspId, version, networkIdByName, component, componentId); - } - } - } - - private void saveNicsByComponent(String vspId, Version version, - Map networkIdByName, Component component, - String componentId) { - if (CollectionUtils.isNotEmpty(component.getNics())) { - for (Nic nic : component.getNics()) { - if (nic.getNetworkName() != null && MapUtils.isNotEmpty(networkIdByName)) { - nic.setNetworkId(networkIdByName.get(nic.getNetworkName())); + private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR = "COMPOSITION_ENTITY_DATA_MANAGER_ERR"; + private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG = "Invalid input: %s may not be null"; + private static final String MISSING_OR_INVALID_QUESTIONNAIRE_MSG = "Data is missing/invalid for this %s. Please refill and resubmit."; + private static final Logger logger = LoggerFactory.getLogger(CompositionEntityDataManagerImpl.class); + private Map entities = new HashMap<>(); + private Map nonDynamicSchemas = new EnumMap<>(CompositionEntityType.class); + private List roots = new ArrayList<>(); + private VendorSoftwareProductInfoDao vspInfoDao; + private ComponentDao componentDao; + private NicDao nicDao; + private NetworkDao networkDao; + private ImageDao imageDao; + private ComputeDao computeDao; + private DeploymentFlavorDao deploymentFlavorDao; + + public CompositionEntityDataManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, ComponentDao componentDao, NicDao nicDao, NetworkDao networkDao, + ImageDao imageDao, ComputeDao computeDao, DeploymentFlavorDao deploymentFlavorDao) { + this.vspInfoDao = vspInfoDao; + this.componentDao = componentDao; + this.nicDao = nicDao; + this.networkDao = networkDao; + this.imageDao = imageDao; + this.computeDao = computeDao; + this.deploymentFlavorDao = deploymentFlavorDao; + } + + /** + * Validate entity composition entity validation data. + * + * @param entity the entity + * @param schemaTemplateContext the schema template context + * @param schemaTemplateInput the schema template input + * @return the composition entity validation data + */ + @Override + public CompositionEntityValidationData validateEntity(CompositionEntity entity, SchemaTemplateContext schemaTemplateContext, + SchemaTemplateInput schemaTemplateInput) { + if (entity == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR) + .withMessage(String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")).build()); + } + if (schemaTemplateContext == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR) + .withMessage(String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "schema template context")).build()); } - nic.setNetworkName(null); - //For heat flow set network type to be internal by default for NIC - nic.setNetworkType(NetworkType.Internal); + CompositionEntityValidationData validationData = new CompositionEntityValidationData(entity.getType(), entity.getId()); + String json = schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() : entity.getQuestionnaireData(); + validationData.setErrors(JsonUtil.validate(json == null ? JsonUtil.object2Json(new Object()) : json, + generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); + return validationData; + } - NicEntity nicEntity = new NicEntity(vspId, version, componentId, null); - nicEntity.setNicCompositionData(nic); - createNic(nicEntity); - } + /** + * Add entity. + * + * @param entity the entity + * @param schemaTemplateInput the schema template input + */ + @Override + public void addEntity(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput) { + if (entity == null) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR) + .withMessage(String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")).build()); + } + entities.put(entity.getCompositionEntityId(), new CompositionEntityData(entity, schemaTemplateInput)); } - } - private Map saveNetworks(String vspId, Version version, - CompositionData compositionData) { - Map networkIdByName = new HashMap<>(); - if (CollectionUtils.isNotEmpty(compositionData.getNetworks())) { - for (Network network : compositionData.getNetworks()) { + /** + * Validate entities questionnaire map. + * + * @return the map + */ + @Override + public Map> validateEntitiesQuestionnaire() { + Map> errorsByEntityId = new HashMap<>(); + entities.forEach((key, value) -> { + Collection errors = validateQuestionnaire(value); + if (errors != null) { + errorsByEntityId.put(key, errors); + } + }); + return errorsByEntityId; + } - NetworkEntity networkEntity = new NetworkEntity(vspId, version, null); - networkEntity.setNetworkCompositionData(network); + /** + * Build trees. + */ + @Override + public void buildTrees() { + Map entitiesValidationData = new HashMap<>(); + entities.forEach((key, value) -> addValidationDataEntity(entitiesValidationData, key, value.entity)); + } - if (network.getName() != null) { - networkIdByName.put(network.getName(), createNetwork(networkEntity).getId()); - } - } + public Collection getTrees() { + return roots; } - return networkIdByName; - } - private NetworkEntity createNetwork(NetworkEntity network) { - //network.setId(CommonMethods.nextUuId()); will be set by the dao - networkDao.create(network); - return network; - } + @Override + public void saveCompositionData(String vspId, Version version, CompositionData compositionData) { + if (Objects.isNull(compositionData)) { + return; + } + Map networkIdByName = saveNetworks(vspId, version, compositionData); + saveComponents(vspId, version, compositionData, networkIdByName); + } - @Override - public ComponentEntity createComponent(ComponentEntity component, boolean isManualVsp) { - //component.setId(CommonMethods.nextUuId()); will be set by the dao - ComponentQuestionnaireSchemaInput schemaInput = new ComponentQuestionnaireSchemaInput(null, - null, component.getComponentCompositionData().getDisplayName(), isManualVsp); - String questionnarieData = new JsonSchemaDataGenerator(generateSchema(SchemaTemplateContext.questionnaire, - CompositionEntityType.component, schemaInput)).generateData(); - component.setQuestionnaireData(questionnarieData); + @Override + public Set getAllErrorsByVsp(String vspId) { + Set entitiesWithErrors = new HashSet<>(); + for (CompositionEntityValidationData root : roots) { + if (root.getEntityId().equals(vspId)) { + getEntityListWithErrors(root, entitiesWithErrors); + break; + } + } + if (CollectionUtils.isNotEmpty(entitiesWithErrors)) { + updateValidationCompositionEntityName(entitiesWithErrors); + return entitiesWithErrors; + } + return new HashSet<>(); + } - componentDao.create(component); - return component; - } + private void saveComponents(String vspId, Version version, CompositionData compositionData, Map networkIdByName) { + if (CollectionUtils.isNotEmpty(compositionData.getComponents())) { + for (Component component : compositionData.getComponents()) { + ComponentEntity componentEntity = new ComponentEntity(vspId, version, null); + componentEntity.setComponentCompositionData(component.getData()); + String componentId = createComponent(componentEntity, false).getId(); + saveImagesByComponent(vspId, version, component, componentId); + saveComputesFlavorByComponent(vspId, version, component, componentId); + saveNicsByComponent(vspId, version, networkIdByName, component, componentId); + } + } + } - @Override - public NicEntity createNic(NicEntity nic) { - //nic.setId(CommonMethods.nextUuId()); will be set by the dao - nic.setQuestionnaireData( - new JsonSchemaDataGenerator( - generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)) - .generateData()); + private void saveNicsByComponent(String vspId, Version version, Map networkIdByName, Component component, String componentId) { + if (CollectionUtils.isNotEmpty(component.getNics())) { + for (Nic nic : component.getNics()) { + if (nic.getNetworkName() != null && MapUtils.isNotEmpty(networkIdByName)) { + nic.setNetworkId(networkIdByName.get(nic.getNetworkName())); + } + nic.setNetworkName(null); + //For heat flow set network type to be internal by default for NIC + nic.setNetworkType(NetworkType.Internal); + NicEntity nicEntity = new NicEntity(vspId, version, componentId, null); + nicEntity.setNicCompositionData(nic); + createNic(nicEntity); + } + } + } - nicDao.create(nic); - return nic; - } + private Map saveNetworks(String vspId, Version version, CompositionData compositionData) { + Map networkIdByName = new HashMap<>(); + if (CollectionUtils.isNotEmpty(compositionData.getNetworks())) { + for (Network network : compositionData.getNetworks()) { + NetworkEntity networkEntity = new NetworkEntity(vspId, version, null); + networkEntity.setNetworkCompositionData(network); + if (network.getName() != null) { + networkIdByName.put(network.getName(), createNetwork(networkEntity).getId()); + } + } + } + return networkIdByName; + } + private NetworkEntity createNetwork(NetworkEntity network) { + //network.setId(CommonMethods.nextUuId()); will be set by the dao + networkDao.create(network); + return network; + } - public void addErrorsToTrees(Map> errors) { - roots.forEach(root -> addErrorsToTree(root, null, errors)); - } + @Override + public ComponentEntity createComponent(ComponentEntity component, boolean isManualVsp) { + //component.setId(CommonMethods.nextUuId()); will be set by the dao + ComponentQuestionnaireSchemaInput schemaInput = new ComponentQuestionnaireSchemaInput(null, null, + component.getComponentCompositionData().getDisplayName(), isManualVsp); + String questionnarieData = new JsonSchemaDataGenerator( + generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, schemaInput)).generateData(); + component.setQuestionnaireData(questionnarieData); + componentDao.create(component); + return component; + } - /* * - * get a flat list of all questionnaire entities that have validation errors - * */ - public Set getEntityListWithErrors() { - Set treeAsList = new HashSet<>(); + @Override + public NicEntity createNic(NicEntity nic) { + //nic.setId(CommonMethods.nextUuId()); will be set by the dao + nic.setQuestionnaireData( + new JsonSchemaDataGenerator(generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)).generateData()); + nicDao.create(nic); + return nic; + } - for (CompositionEntityValidationData entity : roots) { - if (CollectionUtils.isNotEmpty(entity.getErrors())) { - addNodeWithErrors(entity, treeAsList); - } - getEntityListWithErrors(entity, treeAsList); + public void addErrorsToTrees(Map> errors) { + roots.forEach(root -> addErrorsToTree(root, null, errors)); } - updateValidationCompositionEntityName(treeAsList); - return treeAsList; - } + /* * + * get a flat list of all questionnaire entities that have validation errors + * */ + public Set getEntityListWithErrors() { + Set treeAsList = new HashSet<>(); + for (CompositionEntityValidationData entity : roots) { + if (CollectionUtils.isNotEmpty(entity.getErrors())) { + addNodeWithErrors(entity, treeAsList); + } + getEntityListWithErrors(entity, treeAsList); + } + updateValidationCompositionEntityName(treeAsList); + return treeAsList; + } - private void getEntityListWithErrors(CompositionEntityValidationData entity, - Set compositionSet) { - if (CollectionUtils.isNotEmpty(entity.getErrors())) { - addNodeWithErrors(entity, compositionSet); + private void getEntityListWithErrors(CompositionEntityValidationData entity, Set compositionSet) { + if (CollectionUtils.isNotEmpty(entity.getErrors())) { + addNodeWithErrors(entity, compositionSet); + } + if (CollectionUtils.isEmpty(entity.getSubEntitiesValidationData())) { + return; + } + for (CompositionEntityValidationData child : entity.getSubEntitiesValidationData()) { + getEntityListWithErrors(child, compositionSet); + } } - if (CollectionUtils.isEmpty(entity.getSubEntitiesValidationData())) { - return; + private void addNodeWithErrors(CompositionEntityValidationData node, Set entitiesWithErrors) { + CompositionEntityValidationData compositionNodeToAdd = new CompositionEntityValidationData(node.getEntityType(), node.getEntityId()); + compositionNodeToAdd.setErrors(node.getErrors()); + compositionNodeToAdd.setSubEntitiesValidationData(null); + entitiesWithErrors.add(compositionNodeToAdd); } - for (CompositionEntityValidationData child : entity.getSubEntitiesValidationData()) { - getEntityListWithErrors(child, compositionSet); + public void removeNodesWithoutErrors() { + roots.forEach(root -> removeNodesWithoutErrors(root, null)); } - } + private CompositionEntityData getCompositionEntityDataById(CompositionEntityValidationData entity) { + for (Map.Entry entityEntry : entities.entrySet()) { + if (entityEntry.getKey().getId().equals(entity.getEntityId())) { + return entityEntry.getValue(); + } + } + return null; + } - private void addNodeWithErrors(CompositionEntityValidationData node, - Set entitiesWithErrors) { - CompositionEntityValidationData compositionNodeToAdd = new CompositionEntityValidationData(node - .getEntityType(), node.getEntityId()); - compositionNodeToAdd.setErrors(node.getErrors()); - compositionNodeToAdd.setSubEntitiesValidationData(null); + private void updateValidationCompositionEntityName(Set compositionSet) { + for (CompositionEntityValidationData entity : compositionSet) { + String compositionData = getCompositionDataAsString(entity); + if (entity.getEntityType().equals(CompositionEntityType.vsp) || Objects.nonNull(compositionData)) { + entity.setEntityName(getEntityNameByEntityType(compositionData, entity)); + } + } + } - entitiesWithErrors.add(compositionNodeToAdd); - } + private String getCompositionDataAsString(CompositionEntityValidationData entity) { + CompositionEntityData compositionEntityData = getCompositionEntityDataById(entity); + return compositionEntityData == null ? null : compositionEntityData.entity.getCompositionData(); + } - public void removeNodesWithoutErrors() { - roots.forEach(root -> removeNodesWithoutErrors(root, null)); - } + private String getEntityNameByEntityType(String compositionData, CompositionEntityValidationData entity) { + switch (entity.getEntityType()) { + case component: + ComponentData component = JsonUtil.json2Object(compositionData, ComponentData.class); + return component.getDisplayName(); + case nic: + Nic nic = JsonUtil.json2Object(compositionData, Nic.class); + return nic.getName(); + case network: + Network network = JsonUtil.json2Object(compositionData, Network.class); + return network.getName(); + case image: + Image image = JsonUtil.json2Object(compositionData, Image.class); + return image.getFileName(); + case compute: + ComputeData compute = JsonUtil.json2Object(compositionData, ComputeData.class); + return compute.getName(); + case vsp: + CompositionEntityData vspEntity = getCompositionEntityDataById(entity); + if (Objects.isNull(vspEntity)) { + return null; + } + VspQuestionnaireEntity vspQuestionnaireEntity = (VspQuestionnaireEntity) vspEntity.entity; + VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), vspQuestionnaireEntity.getVersion())); + return vspDetails.getName(); + default: + return null; + } + } + private void removeNodesWithoutErrors(CompositionEntityValidationData node, CompositionEntityValidationData parent) { + if (Objects.isNull(node)) { + return; + } + if (hasChildren(node)) { + Collection subNodes = new ArrayList<>(node.getSubEntitiesValidationData()); + subNodes.forEach(subNode -> removeNodesWithoutErrors(subNode, node)); + node.setSubEntitiesValidationData(subNodes); + if (canNodeGetRemovedFromValidationDataTree(node)) { + removeNodeFromChildren(parent, node); + } + } else if (canNodeGetRemovedFromValidationDataTree(node)) { + removeNodeFromChildren(parent, node); + } + } - private CompositionEntityData getCompositionEntityDataById(CompositionEntityValidationData - entity) { - for (Map.Entry entityEntry : entities - .entrySet()) { - if (entityEntry.getKey().getId().equals(entity.getEntityId())) { - return entityEntry.getValue(); - } + private void removeNodeFromChildren(CompositionEntityValidationData parent, CompositionEntityValidationData childToRemove) { + if (!Objects.isNull(parent)) { + parent.getSubEntitiesValidationData().remove(childToRemove); + } } - return null; - } + private boolean hasChildren(CompositionEntityValidationData node) { + return !CollectionUtils.isEmpty(node.getSubEntitiesValidationData()); + } - private void updateValidationCompositionEntityName(Set - compositionSet) { - for (CompositionEntityValidationData entity : compositionSet) { - String compositionData = getCompositionDataAsString(entity); - if (entity.getEntityType().equals(CompositionEntityType.vsp) || - Objects.nonNull(compositionData)) { - entity.setEntityName(getEntityNameByEntityType(compositionData, entity)); - } + private boolean canNodeGetRemovedFromValidationDataTree(CompositionEntityValidationData node) { + return !hasChildren(node) && CollectionUtils.isEmpty(node.getErrors()); } - } - private String getCompositionDataAsString(CompositionEntityValidationData entity) { - CompositionEntityData compositionEntityData = getCompositionEntityDataById(entity); - return compositionEntityData == null ? null : compositionEntityData.entity.getCompositionData(); - } + private void addValidationDataEntity(Map entitiesValidationData, + CompositionEntityId entityId, CompositionEntity entity) { + if (entitiesValidationData.containsKey(entityId)) { + return; + } + CompositionEntityValidationData validationData = new CompositionEntityValidationData(entity.getType(), entity.getId()); + entitiesValidationData.put(entityId, validationData); + CompositionEntityId parentEntityId = entityId.getParentId(); + if (parentEntityId == null) { + roots.add(validationData); + } else { + CompositionEntityData parentEntity = entities.get(parentEntityId); + if (parentEntity == null) { + roots.add(validationData); + } else { + addValidationDataEntity(entitiesValidationData, parentEntityId, parentEntity.entity); + entitiesValidationData.get(parentEntityId).addSubEntityValidationData(validationData); + } + } + } + private void addErrorsToTree(CompositionEntityValidationData node, CompositionEntityId parentNodeId, + Map> errors) { + if (node == null) { + return; + } + CompositionEntityId nodeId = new CompositionEntityId(node.getEntityId(), parentNodeId); + node.setErrors(errors.get(nodeId)); + if (node.getSubEntitiesValidationData() != null) { + node.getSubEntitiesValidationData().forEach(subNode -> addErrorsToTree(subNode, nodeId, errors)); + } + } - private String getEntityNameByEntityType(String compositionData, - CompositionEntityValidationData entity) { - switch (entity.getEntityType()) { - case component: - ComponentData component = JsonUtil.json2Object(compositionData, ComponentData.class); - return component.getDisplayName(); + private Collection validateQuestionnaire(CompositionEntityData compositionEntityData) { + logger.debug(String.format("validateQuestionnaire start: " + "[entity.type]=%s, [entity.id]=%s, [entity.questionnaireString]=%s", + compositionEntityData.entity.getType().name(), compositionEntityData.entity.getCompositionEntityId().toString(), + compositionEntityData.entity.getQuestionnaireData())); + if (Objects.isNull(compositionEntityData.entity.getQuestionnaireData()) || !JsonUtil + .isValidJson(compositionEntityData.entity.getQuestionnaireData())) { + return Collections.singletonList(String.format(MISSING_OR_INVALID_QUESTIONNAIRE_MSG, compositionEntityData.entity.getType())); + } + return JsonUtil.validate(compositionEntityData.entity.getQuestionnaireData() == null ? JsonUtil.object2Json(new Object()) + : compositionEntityData.entity.getQuestionnaireData(), + getSchema(compositionEntityData.entity.getType(), SchemaTemplateContext.questionnaire, compositionEntityData.schemaTemplateInput)); + } - case nic: - Nic nic = JsonUtil.json2Object(compositionData, Nic.class); - return nic.getName(); + private String getSchema(CompositionEntityType compositionEntityType, SchemaTemplateContext schemaTemplateContext, + SchemaTemplateInput schemaTemplateInput) { + return schemaTemplateInput == null ? nonDynamicSchemas + .computeIfAbsent(compositionEntityType, k -> generateSchema(schemaTemplateContext, compositionEntityType, null)) + : generateSchema(schemaTemplateContext, compositionEntityType, schemaTemplateInput); + } - case network: - Network network = JsonUtil.json2Object(compositionData, Network.class); - return network.getName(); + // make the method private + protected String generateSchema(SchemaTemplateContext schemaTemplateContext, CompositionEntityType compositionEntityType, + SchemaTemplateInput schemaTemplateInput) { + return SchemaGenerator.generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); + } + // todo - make SchemaGenerator non static and mock it in UT instead of mocking this method (and - case image: - Image image = JsonUtil.json2Object(compositionData, Image.class); - return image.getFileName(); + @Override + public DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor) { + deploymentFlavor.setId(CommonMethods.nextUuId()); + deploymentFlavorDao.create(deploymentFlavor); + return deploymentFlavor; + } - case compute: - ComputeData compute = JsonUtil.json2Object(compositionData, ComputeData.class); - return compute.getName(); + @Override + public ImageEntity createImage(ImageEntity image) { + image.setId(CommonMethods.nextUuId()); + image.setQuestionnaireData( + new JsonSchemaDataGenerator(SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) + .generateData()); + imageDao.create(image); + return image; + } - case vsp: - CompositionEntityData vspEntity = getCompositionEntityDataById(entity); - if (Objects.isNull(vspEntity)) { - return null; + public void saveComputesFlavorByComponent(String vspId, Version version, Component component, String componentId) { + if (CollectionUtils.isNotEmpty(component.getCompute())) { + for (ComputeData flavor : component.getCompute()) { + ComputeEntity computeEntity = new ComputeEntity(vspId, version, componentId, null); + computeEntity.setComputeCompositionData(flavor); + computeEntity.setQuestionnaireData( + new JsonSchemaDataGenerator(SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, null)) + .generateData()); + computeDao.create(computeEntity); + } } - VspQuestionnaireEntity vspQuestionnaireEntity = (VspQuestionnaireEntity) vspEntity.entity; - VspDetails vspDetails = - vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), - vspQuestionnaireEntity.getVersion())); - return vspDetails.getName(); - default: - return null; - } - } - - private void removeNodesWithoutErrors(CompositionEntityValidationData node, - CompositionEntityValidationData parent) { - - if (Objects.isNull(node)) { - return; } - if (hasChildren(node)) { - Collection subNodes = - new ArrayList<>(node.getSubEntitiesValidationData()); - subNodes.forEach(subNode -> removeNodesWithoutErrors(subNode, node)); - node.setSubEntitiesValidationData(subNodes); - - if (canNodeGetRemovedFromValidationDataTree(node)) { - removeNodeFromChildren(parent, node); - } - } else if (canNodeGetRemovedFromValidationDataTree(node)) { - removeNodeFromChildren(parent, node); + public void saveImagesByComponent(String vspId, Version version, Component component, String componentId) { + if (CollectionUtils.isNotEmpty(component.getImages())) { + for (Image img : component.getImages()) { + ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, null); + imageEntity.setImageCompositionData(img); + createImage(imageEntity); + } + } } - } - private void removeNodeFromChildren(CompositionEntityValidationData parent, - CompositionEntityValidationData childToRemove) { - if (!Objects.isNull(parent)) { - parent.getSubEntitiesValidationData().remove(childToRemove); - } - } + private static class CompositionEntityData { - private boolean hasChildren(CompositionEntityValidationData node) { - return !CollectionUtils.isEmpty(node.getSubEntitiesValidationData()); - } - - private boolean canNodeGetRemovedFromValidationDataTree(CompositionEntityValidationData node) { - return !hasChildren(node) && CollectionUtils.isEmpty(node.getErrors()); - } - - - private void addValidationDataEntity( - Map entitiesValidationData, - CompositionEntityId entityId, CompositionEntity entity) { - if (entitiesValidationData.containsKey(entityId)) { - return; - } - - CompositionEntityValidationData validationData = - new CompositionEntityValidationData(entity.getType(), entity.getId()); - entitiesValidationData.put(entityId, validationData); - - CompositionEntityId parentEntityId = entityId.getParentId(); - if (parentEntityId == null) { - roots.add(validationData); - } else { - CompositionEntityData parentEntity = entities.get(parentEntityId); - if (parentEntity == null) { - roots.add(validationData); - } else { - addValidationDataEntity(entitiesValidationData, parentEntityId, parentEntity.entity); - entitiesValidationData.get(parentEntityId).addSubEntityValidationData(validationData); - } - } - } - - private void addErrorsToTree(CompositionEntityValidationData node, - CompositionEntityId parentNodeId, - Map> errors) { - if (node == null) { - return; - } - CompositionEntityId nodeId = new CompositionEntityId(node.getEntityId(), parentNodeId); - node.setErrors(errors.get(nodeId)); - - if (node.getSubEntitiesValidationData() != null) { - node.getSubEntitiesValidationData() - .forEach(subNode -> addErrorsToTree(subNode, nodeId, errors)); - } - } - - private Collection validateQuestionnaire(CompositionEntityData compositionEntityData) { - logger.debug(String.format("validateQuestionnaire start: " + - "[entity.type]=%s, [entity.id]=%s, [entity.questionnaireString]=%s", - compositionEntityData.entity.getType().name(), - compositionEntityData.entity.getCompositionEntityId().toString(), - compositionEntityData.entity.getQuestionnaireData())); - - if (Objects.isNull(compositionEntityData.entity.getQuestionnaireData()) || - !JsonUtil.isValidJson(compositionEntityData.entity.getQuestionnaireData())) { - return Collections.singletonList(String - .format(MISSING_OR_INVALID_QUESTIONNAIRE_MSG, compositionEntityData.entity.getType())); - } - - return JsonUtil.validate( - compositionEntityData.entity.getQuestionnaireData() == null - ? JsonUtil.object2Json(new Object()) - : compositionEntityData.entity.getQuestionnaireData(), - getSchema(compositionEntityData.entity.getType(), SchemaTemplateContext.questionnaire, - compositionEntityData.schemaTemplateInput)); - } - - private String getSchema(CompositionEntityType compositionEntityType, - SchemaTemplateContext schemaTemplateContext, - SchemaTemplateInput schemaTemplateInput) { - return schemaTemplateInput == null - ? nonDynamicSchemas.computeIfAbsent(compositionEntityType, - k -> generateSchema(schemaTemplateContext, compositionEntityType, null)) - : generateSchema(schemaTemplateContext, compositionEntityType, schemaTemplateInput); - } - - private static class CompositionEntityData { - private CompositionEntity entity; - private SchemaTemplateInput schemaTemplateInput; - - CompositionEntityData(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput) { - this.entity = entity; - this.schemaTemplateInput = schemaTemplateInput; - } - - } - - // todo - make SchemaGenerator non static and mock it in UT instead of mocking this method (and - // make the method private - protected String generateSchema(SchemaTemplateContext schemaTemplateContext, - CompositionEntityType compositionEntityType, - SchemaTemplateInput schemaTemplateInput) { - return SchemaGenerator - .generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); - } - - @Override - public DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor) { - deploymentFlavor.setId(CommonMethods.nextUuId()); - deploymentFlavorDao.create(deploymentFlavor); - return deploymentFlavor; - } - - @Override - public ImageEntity createImage(ImageEntity image) { - image.setId(CommonMethods.nextUuId()); - - image.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) - .generateData()); - - imageDao.create(image); - return image; - } - - public void saveComputesFlavorByComponent(String vspId, Version version, Component component, - String componentId) { - if (CollectionUtils.isNotEmpty(component.getCompute())) { - for (ComputeData flavor : component.getCompute()) { - ComputeEntity computeEntity = new ComputeEntity(vspId, version, componentId, null); - computeEntity.setComputeCompositionData(flavor); - computeEntity.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, - null)).generateData()); - - computeDao.create(computeEntity); - } - } - } - - public void saveImagesByComponent(String vspId, Version version, Component component, String - componentId) { - if (CollectionUtils.isNotEmpty(component.getImages())) { - for (Image img : component.getImages()) { - ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, null); - imageEntity.setImageCompositionData(img); - createImage(imageEntity); - } - } - } + private CompositionEntity entity; + private SchemaTemplateInput schemaTemplateInput; + CompositionEntityData(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput) { + this.entity = entity; + this.schemaTemplateInput = schemaTemplateInput; + } + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerFactoryImpl.java index 4a1b1c1cff..c0b6fda818 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; @@ -29,15 +28,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoF public class ComputeManagerFactoryImpl extends ComputeManagerFactory { - private static final ComputeManager INSTANCE = - new ComputeManagerImpl( - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - ComputeDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface()); + private static final ComputeManager INSTANCE = new ComputeManagerImpl(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), + ComputeDaoFactory.getInstance().createInterface(), CompositionEntityDataManagerFactory.getInstance().createInterface(), + DeploymentFlavorDaoFactory.getInstance().createInterface()); - @Override - public ComputeManager createInterface() { - return INSTANCE; - } + @Override + public ComputeManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImpl.java index 8bddeaeef4..6c319ca866 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ComputeManagerImpl.java @@ -13,10 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.dao.UniqueValueDaoFactory; import org.openecomp.core.util.UniqueValueUtil; @@ -38,279 +41,223 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGe import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ListComputeResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.*; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.ComputeCompositionSchemaInput; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.*; - public class ComputeManagerImpl implements ComputeManager { - private final ComputeDao computeDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final VendorSoftwareProductInfoDao vspInfoDao; - private final DeploymentFlavorDao deploymentFlavorDao; - - public ComputeManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, - ComputeDao computeDao, - CompositionEntityDataManager compositionEntityDataManager, - DeploymentFlavorDao deploymentFlavorDao) { - this.computeDao = computeDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.vspInfoDao = vspInfoDao; - this.deploymentFlavorDao = deploymentFlavorDao; - } - - @Override - public ComputeEntity createCompute(ComputeEntity compute) { - if (!vspInfoDao.isManual(compute.getVspId(), compute.getVersion())) { - ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder - .getAddComputeNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(onboardingMethodUpdateErrorCode); - } else { - validateUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), - compute.getComputeCompositionData().getName()); - compute.setQuestionnaireData( - new JsonSchemaDataGenerator(getComputeQuestionnaireSchema(null)).generateData()); - computeDao.create(compute); - createUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), - compute.getComputeCompositionData().getName()); + private final ComputeDao computeDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final VendorSoftwareProductInfoDao vspInfoDao; + private final DeploymentFlavorDao deploymentFlavorDao; + + public ComputeManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, ComputeDao computeDao, + CompositionEntityDataManager compositionEntityDataManager, DeploymentFlavorDao deploymentFlavorDao) { + this.computeDao = computeDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.vspInfoDao = vspInfoDao; + this.deploymentFlavorDao = deploymentFlavorDao; } - return compute; - } + @Override + public ComputeEntity createCompute(ComputeEntity compute) { + if (!vspInfoDao.isManual(compute.getVspId(), compute.getVersion())) { + ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder + .getAddComputeNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(onboardingMethodUpdateErrorCode); + } else { + validateUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), compute.getComputeCompositionData().getName()); + compute.setQuestionnaireData(new JsonSchemaDataGenerator(getComputeQuestionnaireSchema(null)).generateData()); + computeDao.create(compute); + createUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), compute.getComputeCompositionData().getName()); + } + return compute; + } - @Override - public Collection listComputes(String vspId, Version version, - String componentId) { - Collection computes = - computeDao.list(new ComputeEntity(vspId, version, componentId, null)); - return getListComputeResponse(vspId, version, computes); - } - - private Collection getListComputeResponse(String vspId, Version version, - Collection computes) { - Set vspComputes = getComputeAssociatedWithDepFlavors(vspId, version); - Collection computeResponse = new ArrayList<>(); - for (ComputeEntity computeEntity : computes) { - ListComputeResponse response = new ListComputeResponse(); - response.setComputeEntity(computeEntity); - if (vspComputes.contains(computeEntity.getId())) { - response.setAssociatedWithDeploymentFlavor(true); - } else { - response.setAssociatedWithDeploymentFlavor(false); - } - computeResponse.add(response); + @Override + public Collection listComputes(String vspId, Version version, String componentId) { + Collection computes = computeDao.list(new ComputeEntity(vspId, version, componentId, null)); + return getListComputeResponse(vspId, version, computes); } - return computeResponse; - } - private Set getComputeAssociatedWithDepFlavors(String vspId, Version version) { - final Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - Set vspComputes = new HashSet<>(); - for (DeploymentFlavorEntity entity : deploymentFlavorEntities) { - final List componentComputeAssociations = - entity.getDeploymentFlavorCompositionData().getComponentComputeAssociations(); - if (componentComputeAssociations != null && !componentComputeAssociations.isEmpty()) { - for (ComponentComputeAssociation association : componentComputeAssociations) { - vspComputes.add(association.getComputeFlavorId()); + private Collection getListComputeResponse(String vspId, Version version, Collection computes) { + Set vspComputes = getComputeAssociatedWithDepFlavors(vspId, version); + Collection computeResponse = new ArrayList<>(); + for (ComputeEntity computeEntity : computes) { + ListComputeResponse response = new ListComputeResponse(); + response.setComputeEntity(computeEntity); + if (vspComputes.contains(computeEntity.getId())) { + response.setAssociatedWithDeploymentFlavor(true); + } else { + response.setAssociatedWithDeploymentFlavor(false); + } + computeResponse.add(response); } - } + return computeResponse; } - return vspComputes; - } - @Override - public CompositionEntityResponse getCompute(String vspId, Version version, - String componentId, - String computeFlavorId) { - ComputeEntity computeEntity = getValidatedCompute(vspId, version, componentId, computeFlavorId); - ComputeData compute = computeEntity.getComputeCompositionData(); - - ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - schemaInput.setCompute(compute); - - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(computeFlavorId); - response.setData(compute); - response.setSchema(getComputeCompositionSchema(schemaInput)); - return response; - } - - private ComputeEntity getValidatedCompute(String vspId, Version version, String componentId, - String computeFlavorId) { - ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId, version, componentId, - computeFlavorId)); - VersioningUtil - .validateEntityExistence(retrieved, new ComputeEntity(vspId, version, componentId, - computeFlavorId), VspDetails.ENTITY_TYPE); - return retrieved; - } - - @Override - public QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String - componentId, String computeId) { - QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); - ComputeEntity computeQuestionnaire = - computeDao.getQuestionnaireData(vspId, version, componentId, computeId); - VersioningUtil - .validateEntityExistence(computeQuestionnaire, - new ComputeEntity(vspId, version, componentId, computeId), VspDetails.ENTITY_TYPE); - questionnaireResponse.setData(computeQuestionnaire.getQuestionnaireData()); - questionnaireResponse.setSchema(getComputeQuestionnaireSchema(null)); - return questionnaireResponse; - } - - - @Override - public void updateComputeQuestionnaire(String vspId, Version version, String componentId, - String computeId, String questionnaireData) { - ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId, version, componentId, - computeId)); - VersioningUtil.validateEntityExistence(retrieved, new ComputeEntity(vspId, version, - componentId, computeId), VspDetails.ENTITY_TYPE); - - computeDao.updateQuestionnaireData(vspId, version, componentId, computeId, questionnaireData); - } + private Set getComputeAssociatedWithDepFlavors(String vspId, Version version) { + final Collection deploymentFlavorEntities = deploymentFlavorDao + .list(new DeploymentFlavorEntity(vspId, version, null)); + Set vspComputes = new HashSet<>(); + for (DeploymentFlavorEntity entity : deploymentFlavorEntities) { + final List componentComputeAssociations = entity.getDeploymentFlavorCompositionData() + .getComponentComputeAssociations(); + if (componentComputeAssociations != null && !componentComputeAssociations.isEmpty()) { + for (ComponentComputeAssociation association : componentComputeAssociations) { + vspComputes.add(association.getComputeFlavorId()); + } + } + } + return vspComputes; + } - @Override - public CompositionEntityValidationData updateCompute(ComputeEntity compute) { - ComputeEntity retrieved = - getComputeEntity(compute.getVspId(), compute.getVersion(), compute.getComponentId(), - compute.getId()); + @Override + public CompositionEntityResponse getCompute(String vspId, Version version, String componentId, String computeFlavorId) { + ComputeEntity computeEntity = getValidatedCompute(vspId, version, componentId, computeFlavorId); + ComputeData compute = computeEntity.getComputeCompositionData(); + ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + schemaInput.setCompute(compute); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(computeFlavorId); + response.setData(compute); + response.setSchema(getComputeCompositionSchema(schemaInput)); + return response; + } - boolean manual = vspInfoDao.isManual(compute.getVspId(), compute.getVersion()); + private ComputeEntity getValidatedCompute(String vspId, Version version, String componentId, String computeFlavorId) { + ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId, version, componentId, computeFlavorId)); + VersioningUtil.validateEntityExistence(retrieved, new ComputeEntity(vspId, version, componentId, computeFlavorId), VspDetails.ENTITY_TYPE); + return retrieved; + } - ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); - schemaInput.setManual(manual); - schemaInput.setCompute(retrieved.getComputeCompositionData()); + @Override + public QuestionnaireResponse getComputeQuestionnaire(String vspId, Version version, String componentId, String computeId) { + QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); + ComputeEntity computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, computeId); + VersioningUtil + .validateEntityExistence(computeQuestionnaire, new ComputeEntity(vspId, version, componentId, computeId), VspDetails.ENTITY_TYPE); + questionnaireResponse.setData(computeQuestionnaire.getQuestionnaireData()); + questionnaireResponse.setSchema(getComputeQuestionnaireSchema(null)); + return questionnaireResponse; + } - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(compute, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - updateUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), - retrieved.getComputeCompositionData().getName(), - compute.getComputeCompositionData().getName()); - computeDao.update(compute); + @Override + public void updateComputeQuestionnaire(String vspId, Version version, String componentId, String computeId, String questionnaireData) { + ComputeEntity retrieved = computeDao.get(new ComputeEntity(vspId, version, componentId, computeId)); + VersioningUtil.validateEntityExistence(retrieved, new ComputeEntity(vspId, version, componentId, computeId), VspDetails.ENTITY_TYPE); + computeDao.updateQuestionnaireData(vspId, version, componentId, computeId, questionnaireData); } - return validationData; - } - private ComputeEntity getComputeEntity(String vspId, Version version, String componentId, - String computeId) { - ComputeEntity computeEntity = - computeDao.get(new ComputeEntity(vspId, version, componentId, computeId)); - VersioningUtil - .validateEntityExistence(computeEntity, new ComputeEntity(vspId, version, componentId, - computeId), VspDetails.ENTITY_TYPE); - return computeEntity; - } + @Override + public CompositionEntityValidationData updateCompute(ComputeEntity compute) { + ComputeEntity retrieved = getComputeEntity(compute.getVspId(), compute.getVersion(), compute.getComponentId(), compute.getId()); + boolean manual = vspInfoDao.isManual(compute.getVspId(), compute.getVersion()); + ComputeCompositionSchemaInput schemaInput = new ComputeCompositionSchemaInput(); + schemaInput.setManual(manual); + schemaInput.setCompute(retrieved.getComputeCompositionData()); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(compute, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + updateUniqueName(compute.getVspId(), compute.getVersion(), compute.getComponentId(), retrieved.getComputeCompositionData().getName(), + compute.getComputeCompositionData().getName()); + computeDao.update(compute); + } + return validationData; + } - @Override - public void deleteCompute(String vspId, Version version, String componentId, - String computeFlavorId) { - final String vspCompositionEditNotAllowedMsg = - "Composition entities may not be created / deleted for Vendor Software Product " - + "whose entities were uploaded"; - if (!vspInfoDao.isManual(vspId, version)) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder() - .withId(VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED) - .withMessage(vspCompositionEditNotAllowedMsg).build()); + private ComputeEntity getComputeEntity(String vspId, Version version, String componentId, String computeId) { + ComputeEntity computeEntity = computeDao.get(new ComputeEntity(vspId, version, componentId, computeId)); + VersioningUtil.validateEntityExistence(computeEntity, new ComputeEntity(vspId, version, componentId, computeId), VspDetails.ENTITY_TYPE); + return computeEntity; } - ComputeEntity retrieved = getValidatedCompute(vspId, version, componentId, computeFlavorId); - if (retrieved != null) { - deleteComputeFromDeploymentFlavors(vspId, version, computeFlavorId); - computeDao.delete(new ComputeEntity(vspId, version, componentId, computeFlavorId)); - deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), - retrieved.getComputeCompositionData().getName()); + + @Override + public void deleteCompute(String vspId, Version version, String componentId, String computeFlavorId) { + final String vspCompositionEditNotAllowedMsg = + "Composition entities may not be created / deleted for Vendor Software Product " + "whose entities were uploaded"; + if (!vspInfoDao.isManual(vspId, version)) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(VendorSoftwareProductErrorCodes.VSP_COMPOSITION_EDIT_NOT_ALLOWED) + .withMessage(vspCompositionEditNotAllowedMsg).build()); + } + ComputeEntity retrieved = getValidatedCompute(vspId, version, componentId, computeFlavorId); + if (retrieved != null) { + deleteComputeFromDeploymentFlavors(vspId, version, computeFlavorId); + computeDao.delete(new ComputeEntity(vspId, version, componentId, computeFlavorId)); + deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), + retrieved.getComputeCompositionData().getName()); + } } - } - private void deleteComputeFromDeploymentFlavors(String vspId, Version version, - String computeFlavorId) { - Collection listDF = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - for (DeploymentFlavorEntity df : listDF) { - DeploymentFlavorEntity deploymentFlavorEntity = removeComputeFromDF(df, computeFlavorId); - if (deploymentFlavorEntity != null) { - deploymentFlavorDao.update(deploymentFlavorEntity); - } + private void deleteComputeFromDeploymentFlavors(String vspId, Version version, String computeFlavorId) { + Collection listDF = deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); + for (DeploymentFlavorEntity df : listDF) { + DeploymentFlavorEntity deploymentFlavorEntity = removeComputeFromDF(df, computeFlavorId); + if (deploymentFlavorEntity != null) { + deploymentFlavorDao.update(deploymentFlavorEntity); + } + } } - } - private DeploymentFlavorEntity removeComputeFromDF(DeploymentFlavorEntity df, - String computeFlavorId) { - DeploymentFlavor flavor = df.getDeploymentFlavorCompositionData(); - List associations = flavor.getComponentComputeAssociations(); - if (associations != null) { - List updatedAssociations = new ArrayList<>(); - for (ComponentComputeAssociation ca : associations) { - if (ca.getComputeFlavorId() != null && ca.getComputeFlavorId().equals(computeFlavorId)) { - ComponentComputeAssociation updateCaremoveCompute = new ComponentComputeAssociation(); - updateCaremoveCompute.setComponentId(ca.getComponentId()); - updatedAssociations.add(updateCaremoveCompute); - } else { - updatedAssociations.add(ca); + private DeploymentFlavorEntity removeComputeFromDF(DeploymentFlavorEntity df, String computeFlavorId) { + DeploymentFlavor flavor = df.getDeploymentFlavorCompositionData(); + List associations = flavor.getComponentComputeAssociations(); + if (associations != null) { + List updatedAssociations = new ArrayList<>(); + for (ComponentComputeAssociation ca : associations) { + if (ca.getComputeFlavorId() != null && ca.getComputeFlavorId().equals(computeFlavorId)) { + ComponentComputeAssociation updateCaremoveCompute = new ComponentComputeAssociation(); + updateCaremoveCompute.setComponentId(ca.getComponentId()); + updatedAssociations.add(updateCaremoveCompute); + } else { + updatedAssociations.add(ca); + } + } + flavor.setComponentComputeAssociations(updatedAssociations); + df.setDeploymentFlavorCompositionData(flavor); + return df; } - } - flavor.setComponentComputeAssociations(updatedAssociations); - df.setDeploymentFlavorCompositionData(flavor); - return df; + return null; } - return null; - } - protected String getComputeCompositionSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.compute, schemaInput); - } + protected String getComputeCompositionSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.compute, schemaInput); + } - protected String getComputeQuestionnaireSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, schemaInput); - } + protected String getComputeQuestionnaireSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, schemaInput); + } - protected void validateUniqueName(String vspId, Version version, String componentId, - String name) { - UniqueValueUtil uniqueValueUtil = - new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); - uniqueValueUtil.validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, - vspId, version.getId(), componentId, name); - } + protected void validateUniqueName(String vspId, Version version, String componentId, String name) { + UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + uniqueValueUtil.validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, version.getId(), componentId, name); + } - protected void createUniqueName(String vspId, Version version, String componentId, String name) { - UniqueValueUtil uniqueValueUtil = - new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); - uniqueValueUtil - .createUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, - version.getId(), componentId, name); - } + protected void createUniqueName(String vspId, Version version, String componentId, String name) { + UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + uniqueValueUtil.createUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, version.getId(), componentId, name); + } - protected void updateUniqueName(String vspId, Version version, String componentId, - String oldName, String newName) { - UniqueValueUtil uniqueValueUtil = - new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); - uniqueValueUtil - .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, oldName, - newName, vspId, version.getId(), componentId); - } + protected void updateUniqueName(String vspId, Version version, String componentId, String oldName, String newName) { + UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + uniqueValueUtil + .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, oldName, newName, vspId, version.getId(), componentId); + } - protected void deleteUniqueValue(String vspId, Version version, String componentId, String name) { - UniqueValueUtil uniqueValueUtil = - new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); - if (componentId == null) { - uniqueValueUtil - .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, - version.getId(), name); + protected void deleteUniqueValue(String vspId, Version version, String componentId, String name) { + UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + if (componentId == null) { + uniqueValueUtil.deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, version.getId(), name); + } + uniqueValueUtil.deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, version.getId(), componentId, name); } - uniqueValueUtil - .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.COMPUTE_NAME, vspId, - version.getId(), componentId, name); - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerFactoryImpl.java index dde07d43b7..fc2db3a478 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerFactoryImpl.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; - import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.DeploymentFlavorManager; import org.openecomp.sdc.vendorsoftwareproduct.DeploymentFlavorManagerFactory; @@ -27,16 +25,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoF public class DeploymentFlavorManagerFactoryImpl extends DeploymentFlavorManagerFactory { - private static final DeploymentFlavorManager INSTANCE = new DeploymentFlavorManagerImpl( - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - ComputeDaoFactory.getInstance().createInterface(), - ComponentDaoFactory.getInstance().createInterface() - ); + private static final DeploymentFlavorManager INSTANCE = new DeploymentFlavorManagerImpl( + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), DeploymentFlavorDaoFactory.getInstance().createInterface(), + CompositionEntityDataManagerFactory.getInstance().createInterface(), ComputeDaoFactory.getInstance().createInterface(), + ComponentDaoFactory.getInstance().createInterface()); - @Override - public DeploymentFlavorManager createInterface() { - return INSTANCE; - } + @Override + public DeploymentFlavorManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImpl.java index 69d8a364db..e3f8f04bb1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/DeploymentFlavorManagerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import java.util.ArrayList; @@ -21,7 +20,6 @@ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.common.errors.CoreException; @@ -49,292 +47,218 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.*; - public class DeploymentFlavorManagerImpl implements DeploymentFlavorManager { - private final VendorSoftwareProductInfoDao vspInfoDao; - private final DeploymentFlavorDao deploymentFlavorDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final ComputeDao computeDao; - private final ComponentDao componentDao; - - public DeploymentFlavorManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, - DeploymentFlavorDao deploymentFlavorDao, - CompositionEntityDataManager compositionEntityDataManager, - ComputeDao computeDao, ComponentDao componentDao) { - this.vspInfoDao = vspInfoDao; - this.deploymentFlavorDao = deploymentFlavorDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.computeDao = computeDao; - this.componentDao = componentDao; - - } - @Override - public Collection listDeploymentFlavors(String vspId, Version version) { - return deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - } + private final VendorSoftwareProductInfoDao vspInfoDao; + private final DeploymentFlavorDao deploymentFlavorDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final ComputeDao computeDao; + private final ComponentDao componentDao; + + public DeploymentFlavorManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, DeploymentFlavorDao deploymentFlavorDao, + CompositionEntityDataManager compositionEntityDataManager, ComputeDao computeDao, ComponentDao componentDao) { + this.vspInfoDao = vspInfoDao; + this.deploymentFlavorDao = deploymentFlavorDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.computeDao = computeDao; + this.componentDao = componentDao; + } - @Override - public DeploymentFlavorEntity createDeploymentFlavor( - DeploymentFlavorEntity deploymentFlavorEntity) { - DeploymentFlavorEntity createDeploymentFlavor; - if (!vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion())) { - ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder - .getAddDeploymentNotSupportedHeatOnboardErrorBuilder(); - throw new CoreException(deploymentFlavorErrorBuilder); - } else { - validateDeploymentFlavor(deploymentFlavorEntity, deploymentFlavorEntity.getVersion()); - createDeploymentFlavor = - compositionEntityDataManager.createDeploymentFlavor(deploymentFlavorEntity); + @Override + public Collection listDeploymentFlavors(String vspId, Version version) { + return deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); } - return createDeploymentFlavor; - } - private void validateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity, - Version version) { - //Validation for unique model. - Collection listDeploymentFlavors = - listDeploymentFlavors(deploymentFlavorEntity.getVspId(), - version); - isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); + @Override + public DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity) { + DeploymentFlavorEntity createDeploymentFlavor; + if (!vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion())) { + ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder.getAddDeploymentNotSupportedHeatOnboardErrorBuilder(); + throw new CoreException(deploymentFlavorErrorBuilder); + } else { + validateDeploymentFlavor(deploymentFlavorEntity, deploymentFlavorEntity.getVersion()); + createDeploymentFlavor = compositionEntityDataManager.createDeploymentFlavor(deploymentFlavorEntity); + } + return createDeploymentFlavor; + } - List featureGroups = - getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), version); - String featureGroup = deploymentFlavorEntity.getDeploymentFlavorCompositionData() - .getFeatureGroupId(); - if (featureGroup != null && featureGroup.trim().length() > 0 - && (isEmpty(featureGroups) || (!(validFeatureGroup(featureGroups, featureGroup))))) { - ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder - .getFeatureGroupNotexistErrorBuilder(); - throw new CoreException(deploymentFlavorErrorBuilder); + private void validateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity, Version version) { + //Validation for unique model. + Collection listDeploymentFlavors = listDeploymentFlavors(deploymentFlavorEntity.getVspId(), version); + isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); + List featureGroups = getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), version); + String featureGroup = deploymentFlavorEntity.getDeploymentFlavorCompositionData().getFeatureGroupId(); + if (featureGroup != null && featureGroup.trim().length() > 0 && (isEmpty(featureGroups) || (!(validFeatureGroup(featureGroups, + featureGroup))))) { + ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder.getFeatureGroupNotexistErrorBuilder(); + throw new CoreException(deploymentFlavorErrorBuilder); + } + validateComponentComputeAssociation(deploymentFlavorEntity, version); } - validateComponentComputeAssociation(deploymentFlavorEntity, version); - } - private void isDeploymentFlavorModelDuplicate(DeploymentFlavorEntity deploymentFlavorEntity, - Collection listDeploymentFlavors) { - listDeploymentFlavors.forEach(deploymentFlavor -> { - if (deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel().equalsIgnoreCase( - deploymentFlavor.getDeploymentFlavorCompositionData().getModel())) { - ErrorCode deploymentFlavorModelErrorBuilder = DeploymentFlavorErrorBuilder - .getDuplicateDeploymentFlavorModelErrorBuilder( - deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel(), - deploymentFlavorEntity.getVspId()); - throw new CoreException(deploymentFlavorModelErrorBuilder); - } - }); - } + private void isDeploymentFlavorModelDuplicate(DeploymentFlavorEntity deploymentFlavorEntity, + Collection listDeploymentFlavors) { + listDeploymentFlavors.forEach(deploymentFlavor -> { + if (deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel() + .equalsIgnoreCase(deploymentFlavor.getDeploymentFlavorCompositionData().getModel())) { + ErrorCode deploymentFlavorModelErrorBuilder = DeploymentFlavorErrorBuilder + .getDuplicateDeploymentFlavorModelErrorBuilder(deploymentFlavorEntity.getDeploymentFlavorCompositionData().getModel(), + deploymentFlavorEntity.getVspId()); + throw new CoreException(deploymentFlavorModelErrorBuilder); + } + }); + } - private List getFeatureGroupListForVsp(String vspId, Version version) { - final VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - return vspDetails.getFeatureGroups(); - } + private List getFeatureGroupListForVsp(String vspId, Version version) { + final VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); + return vspDetails.getFeatureGroups(); + } - private boolean isEmpty(Collection coll) { - return coll == null || coll.isEmpty(); - } + private boolean isEmpty(Collection coll) { + return coll == null || coll.isEmpty(); + } - private boolean validFeatureGroup(List featureGroups, String featureGroupId) { - Iterator iterator = featureGroups.iterator(); - boolean valid = false; - while (iterator.hasNext()) { - String fgId = iterator.next().trim(); - if (fgId.equals(featureGroupId)) { - valid = true; - break; - } else { - valid = false; - } + private boolean validFeatureGroup(List featureGroups, String featureGroupId) { + Iterator iterator = featureGroups.iterator(); + boolean valid = false; + while (iterator.hasNext()) { + String fgId = iterator.next().trim(); + if (fgId.equals(featureGroupId)) { + valid = true; + break; + } else { + valid = false; + } + } + return valid; } - return valid; - } - private void validateComponentComputeAssociation(DeploymentFlavorEntity deploymentFlavorEntity, - Version version) { - List componentComputeAssociationList = - deploymentFlavorEntity.getDeploymentFlavorCompositionData().getComponentComputeAssociations(); + private void validateComponentComputeAssociation(DeploymentFlavorEntity deploymentFlavorEntity, Version version) { + List componentComputeAssociationList = deploymentFlavorEntity.getDeploymentFlavorCompositionData() + .getComponentComputeAssociations(); List vfcList = new ArrayList<>(); if (!isEmpty(componentComputeAssociationList)) { componentComputeAssociationList.forEach( - componentComputeAssociation -> validateComponentComputeAssocoationList(deploymentFlavorEntity, - version, - vfcList, componentComputeAssociation)); + componentComputeAssociation -> validateComponentComputeAssocoationList(deploymentFlavorEntity, version, vfcList, + componentComputeAssociation)); Map frequencyMapping = CollectionUtils.getCardinalityMap(vfcList); - for (Integer vfcCount : frequencyMapping.values()) { if (vfcCount != 1) { - ErrorCode duplicateVfcAssociationErrorBuilder = - DeploymentFlavorErrorBuilder.getDuplicateVfcAssociationErrorBuilder(); + ErrorCode duplicateVfcAssociationErrorBuilder = DeploymentFlavorErrorBuilder.getDuplicateVfcAssociationErrorBuilder(); throw new CoreException(duplicateVfcAssociationErrorBuilder); } } } } - private void validateComponentComputeAssocoationList( - DeploymentFlavorEntity deploymentFlavorEntity, - Version version, - List vfcList, - ComponentComputeAssociation componentComputeAssociation) { - if ((componentComputeAssociation.getComponentId() == null || componentComputeAssociation - .getComponentId().trim().length() == 0) - && (componentComputeAssociation - .getComputeFlavorId() != null && componentComputeAssociation - .getComputeFlavorId().trim().length() > 0)) { - ErrorCode invalidAssociationErrorBuilder = DeploymentFlavorErrorBuilder - .getInvalidAssociationErrorBuilder(); + private void validateComponentComputeAssocoationList(DeploymentFlavorEntity deploymentFlavorEntity, Version version, List vfcList, + ComponentComputeAssociation componentComputeAssociation) { + if ((componentComputeAssociation.getComponentId() == null || componentComputeAssociation.getComponentId().trim().length() == 0) && ( + componentComputeAssociation.getComputeFlavorId() != null && componentComputeAssociation.getComputeFlavorId().trim().length() > 0)) { + ErrorCode invalidAssociationErrorBuilder = DeploymentFlavorErrorBuilder.getInvalidAssociationErrorBuilder(); throw new CoreException(invalidAssociationErrorBuilder); - } else if (componentComputeAssociation.getComponentId() != null - && componentComputeAssociation.getComponentId().trim().length() > 0) { - validateComponentAssociation(deploymentFlavorEntity, - version, componentComputeAssociation); - - validateComponentComputeAssociationFlavour(deploymentFlavorEntity, - version, componentComputeAssociation); + } else if (componentComputeAssociation.getComponentId() != null && componentComputeAssociation.getComponentId().trim().length() > 0) { + validateComponentAssociation(deploymentFlavorEntity, version, componentComputeAssociation); + validateComponentComputeAssociationFlavour(deploymentFlavorEntity, version, componentComputeAssociation); vfcList.add(componentComputeAssociation.getComponentId()); } } private void validateComponentAssociation(DeploymentFlavorEntity deploymentFlavorEntity, Version version, ComponentComputeAssociation componentComputeAssociation) { - if (StringUtils.isNotBlank(componentComputeAssociation.getComponentId())) { - ComponentEntity componentEntity = - componentDao.get(new ComponentEntity(deploymentFlavorEntity.getVspId(), version, - componentComputeAssociation.getComponentId())); + ComponentEntity componentEntity = componentDao + .get(new ComponentEntity(deploymentFlavorEntity.getVspId(), version, componentComputeAssociation.getComponentId())); if (componentEntity == null) { - ErrorCode invalidComputeIdErrorBuilder = - DeploymentFlavorErrorBuilder.getInvalidComponentIdErrorBuilder(); + ErrorCode invalidComputeIdErrorBuilder = DeploymentFlavorErrorBuilder.getInvalidComponentIdErrorBuilder(); throw new CoreException(invalidComputeIdErrorBuilder); } } } - private void validateComponentComputeAssociationFlavour( - DeploymentFlavorEntity deploymentFlavorEntity, - Version version, - ComponentComputeAssociation componentComputeAssociation) { - if (componentComputeAssociation - .getComputeFlavorId() != null && componentComputeAssociation - .getComputeFlavorId().trim().length() > 0) { - ComputeEntity computeFlavor = computeDao.get(new ComputeEntity(deploymentFlavorEntity - .getVspId(), version, componentComputeAssociation.getComponentId(), - componentComputeAssociation.getComputeFlavorId())); - if (computeFlavor == null) { - ErrorCode invalidComputeIdErrorBuilder = DeploymentFlavorErrorBuilder - .getInvalidComputeIdErrorBuilder(); - throw new CoreException(invalidComputeIdErrorBuilder); - } + private void validateComponentComputeAssociationFlavour(DeploymentFlavorEntity deploymentFlavorEntity, Version version, + ComponentComputeAssociation componentComputeAssociation) { + if (componentComputeAssociation.getComputeFlavorId() != null && componentComputeAssociation.getComputeFlavorId().trim().length() > 0) { + ComputeEntity computeFlavor = computeDao.get( + new ComputeEntity(deploymentFlavorEntity.getVspId(), version, componentComputeAssociation.getComponentId(), + componentComputeAssociation.getComputeFlavorId())); + if (computeFlavor == null) { + ErrorCode invalidComputeIdErrorBuilder = DeploymentFlavorErrorBuilder.getInvalidComputeIdErrorBuilder(); + throw new CoreException(invalidComputeIdErrorBuilder); + } + } } - } - - @Override - public CompositionEntityResponse getDeploymentFlavor(String vspId, - Version version, - String deploymentFlavorId) { - DeploymentFlavorEntity deploymentFlavorEntity = - getValidatedDeploymentFlavor(vspId, version, deploymentFlavorId); - DeploymentFlavor deploymentFlavor = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); - DeploymentFlavorCompositionSchemaInput schemaInput = new - DeploymentFlavorCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - schemaInput.setDeploymentFlavor(deploymentFlavor); - List featureGroups = - getFeatureGroupListForVsp(vspId, version); - schemaInput.setFeatureGroupIds(featureGroups); - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(deploymentFlavorId); - response.setSchema(SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.deployment, - schemaInput)); - response.setData(deploymentFlavor); - return response; - } - - private DeploymentFlavorEntity getValidatedDeploymentFlavor(String vspId, Version version, String - deploymentFlavorId) { - DeploymentFlavorEntity retrieved = deploymentFlavorDao.get(new DeploymentFlavorEntity(vspId, - version, deploymentFlavorId)); - VersioningUtil - .validateEntityExistence(retrieved, new DeploymentFlavorEntity(vspId, version, - deploymentFlavorId), VspDetails.ENTITY_TYPE); - return retrieved; - } - @Override - public CompositionEntityResponse getDeploymentFlavorSchema(String vspId, - Version version) { - DeploymentFlavorCompositionSchemaInput schemaInput = - new DeploymentFlavorCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - List featureGroups = - getFeatureGroupListForVsp(vspId, version); - schemaInput.setFeatureGroupIds(featureGroups); - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setSchema(SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.deployment, - schemaInput)); - return response; - } - - @Override - public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { - DeploymentFlavorEntity deploymentFlavorEntity = - getValidatedDeploymentFlavor(vspId, version, deploymentFlavorId); - if (!vspInfoDao.isManual(vspId, version)) { - final ErrorCode deleteDeploymentFlavorErrorBuilder = - NotSupportedHeatOnboardMethodErrorBuilder - .getDelDeploymentFlavorNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(deleteDeploymentFlavorErrorBuilder); + @Override + public CompositionEntityResponse getDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { + DeploymentFlavorEntity deploymentFlavorEntity = getValidatedDeploymentFlavor(vspId, version, deploymentFlavorId); + DeploymentFlavor deploymentFlavor = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + DeploymentFlavorCompositionSchemaInput schemaInput = new DeploymentFlavorCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + schemaInput.setDeploymentFlavor(deploymentFlavor); + List featureGroups = getFeatureGroupListForVsp(vspId, version); + schemaInput.setFeatureGroupIds(featureGroups); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(deploymentFlavorId); + response.setSchema(SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.deployment, schemaInput)); + response.setData(deploymentFlavor); + return response; } - if (deploymentFlavorEntity != null) { - deploymentFlavorDao.delete(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); + private DeploymentFlavorEntity getValidatedDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { + DeploymentFlavorEntity retrieved = deploymentFlavorDao.get(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); + VersioningUtil.validateEntityExistence(retrieved, new DeploymentFlavorEntity(vspId, version, deploymentFlavorId), VspDetails.ENTITY_TYPE); + return retrieved; } - } - @Override - public CompositionEntityValidationData updateDeploymentFlavor( - DeploymentFlavorEntity deploymentFlavorEntity) { - if (!vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), - deploymentFlavorEntity.getVersion())) { - final ErrorCode updateDeploymentFlavorErrorBuilder = - NotSupportedHeatOnboardMethodErrorBuilder - .getUpdateDfNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(updateDeploymentFlavorErrorBuilder); + @Override + public CompositionEntityResponse getDeploymentFlavorSchema(String vspId, Version version) { + DeploymentFlavorCompositionSchemaInput schemaInput = new DeploymentFlavorCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + List featureGroups = getFeatureGroupListForVsp(vspId, version); + schemaInput.setFeatureGroupIds(featureGroups); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setSchema(SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.deployment, schemaInput)); + return response; } - DeploymentFlavorEntity retrieved = - getValidatedDeploymentFlavor(deploymentFlavorEntity.getVspId(), - deploymentFlavorEntity.getVersion(), - deploymentFlavorEntity.getId()); - - - Collection listDeploymentFlavors = listDeploymentFlavors( - deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion()); - listDeploymentFlavors.remove(retrieved); - isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); - validateComponentComputeAssociation(deploymentFlavorEntity, - deploymentFlavorEntity.getVersion()); - - DeploymentFlavorCompositionSchemaInput schemaInput = new - DeploymentFlavorCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), - deploymentFlavorEntity.getVersion())); - schemaInput.setDeploymentFlavor(retrieved.getDeploymentFlavorCompositionData()); + @Override + public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { + DeploymentFlavorEntity deploymentFlavorEntity = getValidatedDeploymentFlavor(vspId, version, deploymentFlavorId); + if (!vspInfoDao.isManual(vspId, version)) { + final ErrorCode deleteDeploymentFlavorErrorBuilder = NotSupportedHeatOnboardMethodErrorBuilder + .getDelDeploymentFlavorNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(deleteDeploymentFlavorErrorBuilder); + } + if (deploymentFlavorEntity != null) { + deploymentFlavorDao.delete(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); + } + } - List featureGroups = - getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), + @Override + public CompositionEntityValidationData updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity) { + if (!vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion())) { + final ErrorCode updateDeploymentFlavorErrorBuilder = NotSupportedHeatOnboardMethodErrorBuilder + .getUpdateDfNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(updateDeploymentFlavorErrorBuilder); + } + DeploymentFlavorEntity retrieved = getValidatedDeploymentFlavor(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion(), + deploymentFlavorEntity.getId()); + Collection listDeploymentFlavors = listDeploymentFlavors(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion()); - schemaInput.setFeatureGroupIds(featureGroups); - - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(deploymentFlavorEntity, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - deploymentFlavorDao.update(deploymentFlavorEntity); + listDeploymentFlavors.remove(retrieved); + isDeploymentFlavorModelDuplicate(deploymentFlavorEntity, listDeploymentFlavors); + validateComponentComputeAssociation(deploymentFlavorEntity, deploymentFlavorEntity.getVersion()); + DeploymentFlavorCompositionSchemaInput schemaInput = new DeploymentFlavorCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion())); + schemaInput.setDeploymentFlavor(retrieved.getDeploymentFlavorCompositionData()); + List featureGroups = getFeatureGroupListForVsp(deploymentFlavorEntity.getVspId(), deploymentFlavorEntity.getVersion()); + schemaInput.setFeatureGroupIds(featureGroups); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(deploymentFlavorEntity, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + deploymentFlavorDao.update(deploymentFlavorEntity); + } + return validationData; } - return validationData; - } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerFactoryImpl.java index 5972d49614..061e344a92 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; - import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.ImageManager; import org.openecomp.sdc.vendorsoftwareproduct.ImageManagerFactory; @@ -29,16 +27,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoF public class ImageManagerFactoryImpl extends ImageManagerFactory { - private static final ImageManager INSTANCE = - new ImageManagerImpl( - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - ImageDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface() - ); - - @Override - public ImageManager createInterface() { - return INSTANCE; - } + private static final ImageManager INSTANCE = new ImageManagerImpl(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), + ImageDaoFactory.getInstance().createInterface(), CompositionEntityDataManagerFactory.getInstance().createInterface()); + @Override + public ImageManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImpl.java index 1e547d33ce..c4245d742d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ImageManagerImpl.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; - +import java.util.Collection; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.common.errors.CoreException; @@ -44,215 +44,166 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.stream.Collectors; - public class ImageManagerImpl implements ImageManager { - private final VendorSoftwareProductInfoDao vspInfoDao; - private final ImageDao imageDao; - private final CompositionEntityDataManager compositionEntityDataManager; - public ImageManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, - ImageDao imageDao, - CompositionEntityDataManager compositionEntityDataManager) { - this.vspInfoDao = vspInfoDao; - this.imageDao = imageDao; - this.compositionEntityDataManager = compositionEntityDataManager; - } + private final VendorSoftwareProductInfoDao vspInfoDao; + private final ImageDao imageDao; + private final CompositionEntityDataManager compositionEntityDataManager; - @Override - public ImageEntity createImage(ImageEntity imageEntity) { - boolean isManual = vspInfoDao.isManual(imageEntity.getVspId(), imageEntity.getVersion()); - if (!isManual) { - ErrorCode errorCode = NotSupportedHeatOnboardMethodErrorBuilder - .getAddImageNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(errorCode); + public ImageManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, ImageDao imageDao, CompositionEntityDataManager compositionEntityDataManager) { + this.vspInfoDao = vspInfoDao; + this.imageDao = imageDao; + this.compositionEntityDataManager = compositionEntityDataManager; } - compositionEntityDataManager.createImage(imageEntity); - return imageEntity; - } - - @Override - public Collection listImages(String vspId, Version version, String componentId) { - return imageDao.list(new ImageEntity(vspId, version, componentId, null)); - } - - @Override - public CompositionEntityResponse getImageSchema(String vspId) { - CompositionEntityResponse response = new CompositionEntityResponse<>(); - ImageCompositionSchemaInput inputSchema = new ImageCompositionSchemaInput(); - Image image = new Image(); - inputSchema.setImage(image); - response.setSchema(getImageCompositionSchema(inputSchema)); - return response; - } - @Override - public CompositionEntityResponse getImage(String vspId, Version version, String - componentId, String imageId) { - ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); - - Image image = imageEntity.getImageCompositionData(); - - ImageCompositionSchemaInput schemaInput = new ImageCompositionSchemaInput(); - schemaInput.setImage(image); - - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(imageId); - response.setData(image); - response.setSchema(getImageCompositionSchema(schemaInput)); - return response; - } - - @Override - public QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String - componentId, String imageId) { - QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); - - ImageEntity retrieved = imageDao.getQuestionnaireData(vspId, version, componentId, imageId); - VersioningUtil.validateEntityExistence(retrieved, new ImageEntity(vspId, version, componentId, - imageId), ComponentEntity.ENTITY_TYPE); - questionnaireResponse.setData(retrieved.getQuestionnaireData()); - questionnaireResponse.setSchema(getImageQuestionnaireSchema(null)); - return questionnaireResponse; - } - - @Override - public void deleteImage(String vspId, Version version, String componentId, String imageId) { - ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); - if (!vspInfoDao.isManual(vspId, version)) { - final ErrorCode deleteImageErrorBuilder = - NotSupportedHeatOnboardMethodErrorBuilder - .getDelImageNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(deleteImageErrorBuilder); + @Override + public ImageEntity createImage(ImageEntity imageEntity) { + boolean isManual = vspInfoDao.isManual(imageEntity.getVspId(), imageEntity.getVersion()); + if (!isManual) { + ErrorCode errorCode = NotSupportedHeatOnboardMethodErrorBuilder.getAddImageNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(errorCode); + } + compositionEntityDataManager.createImage(imageEntity); + return imageEntity; } - if (imageEntity != null) { - imageDao.delete(new ImageEntity(vspId, version, componentId, imageId)); - } - } - private void validateHeatVspImageUpdate(String name, String value, String retrievedValue) { - if (value != null && !value.equals(retrievedValue)) { - final ErrorCode updateHeatImageErrorBuilder = - ImageErrorBuilder.getImageHeatReadOnlyErrorBuilder(name); - throw new CoreException(updateHeatImageErrorBuilder); + @Override + public Collection listImages(String vspId, Version version, String componentId) { + return imageDao.list(new ImageEntity(vspId, version, componentId, null)); } - } - - @Override - public CompositionEntityValidationData updateImage(ImageEntity image) { - boolean isManual = vspInfoDao.isManual(image.getVspId(), image.getVersion()); - ImageEntity retrieved = - getImageEntity(image.getVspId(), image.getVersion(), image.getComponentId(), - image.getId()); - Collection vfcImageList = listImages(image.getVspId(), - image.getVersion(), image.getComponentId()); - - //Set to null so that retrieved object is equal to one in list and gets removed. - retrieved.setQuestionnaireData(null); - vfcImageList.remove(retrieved); - - - ImageCompositionSchemaInput schemaInput = new ImageCompositionSchemaInput(); - schemaInput.setManual(isManual); - schemaInput.setImage(retrieved.getImageCompositionData()); - - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(image, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - imageDao.update(image); + @Override + public CompositionEntityResponse getImageSchema(String vspId) { + CompositionEntityResponse response = new CompositionEntityResponse<>(); + ImageCompositionSchemaInput inputSchema = new ImageCompositionSchemaInput(); + Image image = new Image(); + inputSchema.setImage(image); + response.setSchema(getImageCompositionSchema(inputSchema)); + return response; } - return validationData; - } - @Override - public void updateImageQuestionnaire(String vspId, Version version, String componentId, String - imageId, String questionnaireData) { - getImageEntity(vspId, version, componentId, imageId); - - - final ImageDetails image = JsonUtil.json2Object(questionnaireData, ImageDetails.class); - final String format = image.getFormat(); - try { - if (format != null) { - ImageFormat.valueOf(format); - } - } catch (IllegalArgumentException exception) { - ErrorCode errorCode = ImageErrorBuilder.getInvalidImageFormatErrorBuilder(); - throw new CoreException(errorCode, exception); + @Override + public CompositionEntityResponse getImage(String vspId, Version version, String componentId, String imageId) { + ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); + Image image = imageEntity.getImageCompositionData(); + ImageCompositionSchemaInput schemaInput = new ImageCompositionSchemaInput(); + schemaInput.setImage(image); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(imageId); + response.setData(image); + response.setSchema(getImageCompositionSchema(schemaInput)); + return response; } - //Validate Format is read only for HEAT Onboarding - if (!vspInfoDao.isManual(vspId, version)) { - final QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, - componentId, imageId); - final String data = imageQuestionnaire.getData(); - if (data != null) { - String retrievedFormat = JsonUtil.json2Object(data, ImageDetails.class).getFormat(); - validateHeatVspImageUpdate("format", format, retrievedFormat); - } + @Override + public QuestionnaireResponse getImageQuestionnaire(String vspId, Version version, String componentId, String imageId) { + QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); + ImageEntity retrieved = imageDao.getQuestionnaireData(vspId, version, componentId, imageId); + VersioningUtil.validateEntityExistence(retrieved, new ImageEntity(vspId, version, componentId, imageId), ComponentEntity.ENTITY_TYPE); + questionnaireResponse.setData(retrieved.getQuestionnaireData()); + questionnaireResponse.setSchema(getImageQuestionnaireSchema(null)); + return questionnaireResponse; } - if (!isImageVersionUnique(vspId, version, componentId, imageId, image)) { - ErrorCode errorCode = ImageErrorBuilder.getDuplicateImageVersionErrorBuilder(image - .getVersion(), componentId); - throw new CoreException(errorCode); + @Override + public void deleteImage(String vspId, Version version, String componentId, String imageId) { + ImageEntity imageEntity = getImageEntity(vspId, version, componentId, imageId); + if (!vspInfoDao.isManual(vspId, version)) { + final ErrorCode deleteImageErrorBuilder = NotSupportedHeatOnboardMethodErrorBuilder + .getDelImageNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(deleteImageErrorBuilder); + } + if (imageEntity != null) { + imageDao.delete(new ImageEntity(vspId, version, componentId, imageId)); + } } - imageDao.updateQuestionnaireData(vspId, version, componentId, imageId, questionnaireData); - } - - private boolean isImageVersionUnique(String vspId, Version version, String componentId, - String imageId, - ImageDetails image) { - boolean isPresent = true; - if (image != null && image.getVersion() != null) { - Collection imageEntities = - imageDao.list(new ImageEntity(vspId, version, componentId, null)); - if (CollectionUtils.isNotEmpty(imageEntities)) { - imageEntities = - imageEntities.stream().filter(imageEntity -> image.getVersion().trim().equalsIgnoreCase( - getImageVersion(vspId, version, componentId, imageEntity)) - && !imageEntity.getId().equals(imageId)).collect(Collectors.toList()); - - isPresent = CollectionUtils.isEmpty(imageEntities); - } + private void validateHeatVspImageUpdate(String name, String value, String retrievedValue) { + if (value != null && !value.equals(retrievedValue)) { + final ErrorCode updateHeatImageErrorBuilder = ImageErrorBuilder.getImageHeatReadOnlyErrorBuilder(name); + throw new CoreException(updateHeatImageErrorBuilder); + } } - return isPresent; - } - - private String getImageVersion(String vspId, Version version, String componentId, - ImageEntity imageEntity) { - QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, - componentId, imageEntity.getId()); - ImageDetails imageDetails = - JsonUtil.json2Object(imageQuestionnaire.getData(), ImageDetails.class); + @Override + public CompositionEntityValidationData updateImage(ImageEntity image) { + boolean isManual = vspInfoDao.isManual(image.getVspId(), image.getVersion()); + ImageEntity retrieved = getImageEntity(image.getVspId(), image.getVersion(), image.getComponentId(), image.getId()); + Collection vfcImageList = listImages(image.getVspId(), image.getVersion(), image.getComponentId()); + //Set to null so that retrieved object is equal to one in list and gets removed. + retrieved.setQuestionnaireData(null); + vfcImageList.remove(retrieved); + ImageCompositionSchemaInput schemaInput = new ImageCompositionSchemaInput(); + schemaInput.setManual(isManual); + schemaInput.setImage(retrieved.getImageCompositionData()); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(image, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + imageDao.update(image); + } + return validationData; + } - return imageDetails == null ? null - : imageDetails.getVersion() != null ? imageDetails.getVersion().trim() : null; - } + @Override + public void updateImageQuestionnaire(String vspId, Version version, String componentId, String imageId, String questionnaireData) { + getImageEntity(vspId, version, componentId, imageId); + final ImageDetails image = JsonUtil.json2Object(questionnaireData, ImageDetails.class); + final String format = image.getFormat(); + try { + if (format != null) { + ImageFormat.valueOf(format); + } + } catch (IllegalArgumentException exception) { + ErrorCode errorCode = ImageErrorBuilder.getInvalidImageFormatErrorBuilder(); + throw new CoreException(errorCode, exception); + } + //Validate Format is read only for HEAT Onboarding + if (!vspInfoDao.isManual(vspId, version)) { + final QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, componentId, imageId); + final String data = imageQuestionnaire.getData(); + if (data != null) { + String retrievedFormat = JsonUtil.json2Object(data, ImageDetails.class).getFormat(); + validateHeatVspImageUpdate("format", format, retrievedFormat); + } + } + if (!isImageVersionUnique(vspId, version, componentId, imageId, image)) { + ErrorCode errorCode = ImageErrorBuilder.getDuplicateImageVersionErrorBuilder(image.getVersion(), componentId); + throw new CoreException(errorCode); + } + imageDao.updateQuestionnaireData(vspId, version, componentId, imageId, questionnaireData); + } - private ImageEntity getImageEntity(String vspId, Version version, String componentId, - String imageId) { + private boolean isImageVersionUnique(String vspId, Version version, String componentId, String imageId, ImageDetails image) { + boolean isPresent = true; + if (image != null && image.getVersion() != null) { + Collection imageEntities = imageDao.list(new ImageEntity(vspId, version, componentId, null)); + if (CollectionUtils.isNotEmpty(imageEntities)) { + imageEntities = imageEntities.stream().filter( + imageEntity -> image.getVersion().trim().equalsIgnoreCase(getImageVersion(vspId, version, componentId, imageEntity)) + && !imageEntity.getId().equals(imageId)).collect(Collectors.toList()); + isPresent = CollectionUtils.isEmpty(imageEntities); + } + } + return isPresent; + } - ImageEntity imageEntity = imageDao.get(new ImageEntity(vspId, version, componentId, imageId)); + private String getImageVersion(String vspId, Version version, String componentId, ImageEntity imageEntity) { + QuestionnaireResponse imageQuestionnaire = getImageQuestionnaire(vspId, version, componentId, imageEntity.getId()); + ImageDetails imageDetails = JsonUtil.json2Object(imageQuestionnaire.getData(), ImageDetails.class); + return imageDetails == null ? null : imageDetails.getVersion() != null ? imageDetails.getVersion().trim() : null; + } - VersioningUtil.validateEntityExistence(imageEntity, new ImageEntity(vspId, version, componentId, - imageId), VspDetails.ENTITY_TYPE); - return imageEntity; - } + private ImageEntity getImageEntity(String vspId, Version version, String componentId, String imageId) { + ImageEntity imageEntity = imageDao.get(new ImageEntity(vspId, version, componentId, imageId)); + VersioningUtil.validateEntityExistence(imageEntity, new ImageEntity(vspId, version, componentId, imageId), VspDetails.ENTITY_TYPE); + return imageEntity; + } - protected String getImageCompositionSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.image, - schemaInput); - } + protected String getImageCompositionSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.image, schemaInput); + } - protected String getImageQuestionnaireSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, - schemaInput); - } + protected String getImageQuestionnaireSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, schemaInput); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImpl.java index 58cb2cf2d6..e7697aad35 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ManualVspToscaManagerImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.generator.core.services.ManualVspToscaGenerationService; import org.openecomp.sdc.generator.datatypes.tosca.DeploymentFlavorModel; @@ -29,84 +31,73 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.ManualVspDataCollectionS import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; -import java.util.Map; -import java.util.Optional; - public class ManualVspToscaManagerImpl implements ManualVspToscaManager { - private static final Logger LOGGER = LoggerFactory.getLogger(ManualVspToscaManagerImpl.class); - - private final ManualVspDataCollectionService - manualVspDataCollectionService = new ManualVspDataCollectionService(); - - @Override - public VspModelInfo gatherVspInformation(String vspId, Version version) { - VspModelInfo vspModelInfo = new VspModelInfo(); - //Get Release Vendor Name - Optional releaseVendor; - try { - releaseVendor = manualVspDataCollectionService.getReleaseVendor(vspId, version); - } catch (Exception ex) { - releaseVendor = Optional.empty(); - LOGGER.error("Failed to get release vendor: {}", ex.getMessage(), ex); - } - releaseVendor.ifPresent(vspModelInfo::setReleaseVendor); - - //Get Allowed Deployment flavors information - Map allowedFlavors; - try { - allowedFlavors = manualVspDataCollectionService.getAllowedFlavors(vspId, version); - } catch (Exception ex) { - allowedFlavors = null; - LOGGER.error("Failed to get allowed flavours: {}", ex.getMessage(), ex); - } - if (MapUtils.isNotEmpty(allowedFlavors)) { - vspModelInfo.setAllowedFlavors(allowedFlavors); - } - - //Get VFC Image information - Map> vspComponentImages; - try { - vspComponentImages = - manualVspDataCollectionService.getVspComponentImages(vspId, version); - } catch (Exception ex) { - vspComponentImages = null; - LOGGER.error("Failed to get VSP components Images: {}", ex.getMessage(), ex); - } - if (MapUtils.isNotEmpty(vspComponentImages)) { - vspModelInfo.setMultiFlavorVfcImages(vspComponentImages); - } + private static final Logger LOGGER = LoggerFactory.getLogger(ManualVspToscaManagerImpl.class); + private final ManualVspDataCollectionService manualVspDataCollectionService = new ManualVspDataCollectionService(); - //Get VFC component information - Map vspComponents; - try { - vspComponents = manualVspDataCollectionService.getVspComponents(vspId, version); - } catch (Exception ex) { - vspComponents = null; - LOGGER.error("Failed to get VSP components: {}", ex.getMessage(), ex); - } - if (MapUtils.isNotEmpty(vspComponents)) { - vspModelInfo.setComponents(vspComponents); + @Override + public VspModelInfo gatherVspInformation(String vspId, Version version) { + VspModelInfo vspModelInfo = new VspModelInfo(); + //Get Release Vendor Name + Optional releaseVendor; + try { + releaseVendor = manualVspDataCollectionService.getReleaseVendor(vspId, version); + } catch (Exception ex) { + releaseVendor = Optional.empty(); + LOGGER.error("Failed to get release vendor: {}", ex.getMessage(), ex); + } + releaseVendor.ifPresent(vspModelInfo::setReleaseVendor); + //Get Allowed Deployment flavors information + Map allowedFlavors; + try { + allowedFlavors = manualVspDataCollectionService.getAllowedFlavors(vspId, version); + } catch (Exception ex) { + allowedFlavors = null; + LOGGER.error("Failed to get allowed flavours: {}", ex.getMessage(), ex); + } + if (MapUtils.isNotEmpty(allowedFlavors)) { + vspModelInfo.setAllowedFlavors(allowedFlavors); + } + //Get VFC Image information + Map> vspComponentImages; + try { + vspComponentImages = manualVspDataCollectionService.getVspComponentImages(vspId, version); + } catch (Exception ex) { + vspComponentImages = null; + LOGGER.error("Failed to get VSP components Images: {}", ex.getMessage(), ex); + } + if (MapUtils.isNotEmpty(vspComponentImages)) { + vspModelInfo.setMultiFlavorVfcImages(vspComponentImages); + } + //Get VFC component information + Map vspComponents; + try { + vspComponents = manualVspDataCollectionService.getVspComponents(vspId, version); + } catch (Exception ex) { + vspComponents = null; + LOGGER.error("Failed to get VSP components: {}", ex.getMessage(), ex); + } + if (MapUtils.isNotEmpty(vspComponents)) { + vspModelInfo.setComponents(vspComponents); + } + //Get VSP component nic information + Map> vspComponentNics; + try { + vspComponentNics = manualVspDataCollectionService.getVspComponentNics(vspId, version); + } catch (Exception ex) { + vspComponentNics = null; + LOGGER.error("Failed to get VSP component NIC data: {}", ex.getMessage(), ex); + } + if (MapUtils.isNotEmpty(vspComponentNics)) { + vspModelInfo.setNics(vspComponentNics); + } + return vspModelInfo; } - //Get VSP component nic information - Map> vspComponentNics; - try { - vspComponentNics = manualVspDataCollectionService.getVspComponentNics(vspId, version); - } catch (Exception ex) { - vspComponentNics = null; - LOGGER.error("Failed to get VSP component NIC data: {}", ex.getMessage(), ex); + @Override + public ToscaServiceModel generateToscaModel(VspModelInfo vspModelInfo) { + ManualVspToscaGenerationService vspToscaGenerator = new ManualVspToscaGenerationService(); + return vspToscaGenerator.createManualVspToscaServiceModel(vspModelInfo); } - if (MapUtils.isNotEmpty(vspComponentNics)) { - vspModelInfo.setNics(vspComponentNics); - } - return vspModelInfo; - } - - @Override - public ToscaServiceModel generateToscaModel(VspModelInfo vspModelInfo) { - ManualVspToscaGenerationService vspToscaGenerator = new ManualVspToscaGenerationService(); - return vspToscaGenerator.createManualVspToscaServiceModel(vspModelInfo); - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerFactoryImpl.java index eed566de43..123de3dbd5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager; @@ -25,11 +24,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.MonitoringUploadDaoFactory; public class MonitoringUploadsManagerFactoryImpl extends MonitoringUploadsManagerFactory { - private static final MonitoringUploadsManager INSTANCE = - new MonitoringUploadsManagerImpl(MonitoringUploadDaoFactory.getInstance().createInterface()); - @Override - public MonitoringUploadsManager createInterface() { - return INSTANCE; - } + private static final MonitoringUploadsManager INSTANCE = new MonitoringUploadsManagerImpl( + MonitoringUploadDaoFactory.getInstance().createInterface()); + + @Override + public MonitoringUploadsManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImpl.java index 03ca76fd21..c4fed30e8e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/MonitoringUploadsManagerImpl.java @@ -13,9 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.utilities.CommonMethods; @@ -39,171 +49,117 @@ import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.*; - -import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; - public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager { - private final ComponentArtifactDao componentArtifactDao; - - MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao) { - this.componentArtifactDao = componentArtifactDao; + private final ComponentArtifactDao componentArtifactDao; - componentArtifactDao.registerVersioning( - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); - } - - @Override - public void delete(String vspId, Version version, String componentId, - MonitoringUploadType monitoringUploadType) { - ComponentMonitoringUploadEntity componentMonitoringUploadEntity = - setValuesForComponentArtifactEntityUpload(vspId, version, null, componentId, null, - monitoringUploadType, null); - Optional retrieved = componentArtifactDao.getByType( - componentMonitoringUploadEntity); - - if (!retrieved.isPresent()) { - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - componentMonitoringUploadEntity.getEntityType(), - monitoringUploadType.name(), - VspDetails.ENTITY_TYPE, - componentMonitoringUploadEntity.getFirstClassCitizenId(), - version).build()); + MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao) { + this.componentArtifactDao = componentArtifactDao; + componentArtifactDao.registerVersioning(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); } - componentArtifactDao.delete(retrieved.get()); - } - - @Override - public void upload(InputStream object, String filename, String vspId, - Version version, String componentId, - MonitoringUploadType type) { - if (object == null) { - throw new CoreException(new MonitoringUploadErrorBuilder( - getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), - "zip")).build()); - } else { - Map> errors = new HashMap<>(); - try { - byte[] uploadedFileData = FileUtils.toByteArray(object); - final FileContentHandler upload = - validateZip(vspId, version, uploadedFileData, errors); - if (type.equals(MonitoringUploadType.VES_EVENTS)) { - validateVesEventUpload(upload, errors); - } - if (MapUtils.isNotEmpty(errors)) { - throw new CoreException( - new MonitoringUploadErrorBuilder( - errors.values().iterator().next().get(0).getMessage()) - .build()); + @Override + public void delete(String vspId, Version version, String componentId, MonitoringUploadType monitoringUploadType) { + ComponentMonitoringUploadEntity componentMonitoringUploadEntity = setValuesForComponentArtifactEntityUpload(vspId, version, null, componentId, + null, monitoringUploadType, null); + Optional retrieved = componentArtifactDao.getByType(componentMonitoringUploadEntity); + if (!retrieved.isPresent()) { + throw new CoreException( + new VersionableSubEntityNotFoundErrorBuilder(componentMonitoringUploadEntity.getEntityType(), monitoringUploadType.name(), + VspDetails.ENTITY_TYPE, componentMonitoringUploadEntity.getFirstClassCitizenId(), version).build()); } - - createArtifactInDatabase(vspId, version, filename, componentId, type, - uploadedFileData); - - } catch (Exception exception) { - throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build()); - } + componentArtifactDao.delete(retrieved.get()); } - } - private void validateVesEventUpload(FileContentHandler upload, - Map> errors) { - if (!CommonUtil.validateAllFilesYml(upload)) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, - Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage())); - throw new CoreException( - new MonitoringUploadErrorBuilder( - Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage()) - .build()); + @Override + public void upload(InputStream object, String filename, String vspId, Version version, String componentId, MonitoringUploadType type) { + if (object == null) { + throw new CoreException( + new MonitoringUploadErrorBuilder(getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), "zip")) + .build()); + } else { + Map> errors = new HashMap<>(); + try { + byte[] uploadedFileData = FileUtils.toByteArray(object); + final FileContentHandler upload = validateZip(vspId, version, uploadedFileData, errors); + if (type.equals(MonitoringUploadType.VES_EVENTS)) { + validateVesEventUpload(upload, errors); + } + if (MapUtils.isNotEmpty(errors)) { + throw new CoreException(new MonitoringUploadErrorBuilder(errors.values().iterator().next().get(0).getMessage()).build()); + } + createArtifactInDatabase(vspId, version, filename, componentId, type, uploadedFileData); + } catch (Exception exception) { + throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build()); + } + } } - } - - private void createArtifactInDatabase(String vspId, Version version, String filename, - String componentId, - MonitoringUploadType type, - byte[] uploadedFileData) { - String artifactId = CommonMethods.nextUuId(); - ComponentMonitoringUploadEntity componentMonitoringUploadEntity = - setValuesForComponentArtifactEntityUpload(vspId, version, filename, componentId, - artifactId, type, uploadedFileData); - componentArtifactDao.create(componentMonitoringUploadEntity); - } - - @Override - public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId) { - ComponentMonitoringUploadEntity current = - new ComponentMonitoringUploadEntity(vspId, version, componentId, null); - return setMonitoringUploadStatusValues(current); - } - - private MonitoringUploadStatus setMonitoringUploadStatusValues( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - MonitoringUploadStatus monitoringUploadStatus = new MonitoringUploadStatus(); - - Collection artifactNames = - componentArtifactDao.list(componentMonitoringUploadEntity); - Map artifactTypeToFilename = - VendorSoftwareProductUtils.mapArtifactsByType(artifactNames); - - if (MapUtils.isNotEmpty(artifactTypeToFilename)) { - if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_TRAP)) { - monitoringUploadStatus - .setSnmpTrap(artifactTypeToFilename.get(MonitoringUploadType.SNMP_TRAP)); - } - if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_POLL)) { - monitoringUploadStatus - .setSnmpPoll(artifactTypeToFilename.get(MonitoringUploadType.SNMP_POLL)); - } - if (artifactTypeToFilename.containsKey(MonitoringUploadType.VES_EVENTS)) { - monitoringUploadStatus - .setVesEvent(artifactTypeToFilename.get(MonitoringUploadType.VES_EVENTS)); - } + private void validateVesEventUpload(FileContentHandler upload, Map> errors) { + if (!CommonUtil.validateAllFilesYml(upload)) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage())); + throw new CoreException(new MonitoringUploadErrorBuilder(Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage()).build()); + } } - return monitoringUploadStatus; - } - - private ComponentMonitoringUploadEntity setValuesForComponentArtifactEntityUpload( - String vspId, Version version, String filename, String componentId, String artifactId, - MonitoringUploadType monitoringUploadType, byte[] uploadedFileData) { - - ComponentMonitoringUploadEntity - entity = new ComponentMonitoringUploadEntity(); + private void createArtifactInDatabase(String vspId, Version version, String filename, String componentId, MonitoringUploadType type, + byte[] uploadedFileData) { + String artifactId = CommonMethods.nextUuId(); + ComponentMonitoringUploadEntity componentMonitoringUploadEntity = setValuesForComponentArtifactEntityUpload(vspId, version, filename, + componentId, artifactId, type, uploadedFileData); + componentArtifactDao.create(componentMonitoringUploadEntity); + } - entity.setVspId(vspId); - entity.setVersion(version); - entity.setComponentId(componentId); - entity.setId(artifactId); - entity.setType(monitoringUploadType); - entity.setArtifactName(filename); + @Override + public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId) { + ComponentMonitoringUploadEntity current = new ComponentMonitoringUploadEntity(vspId, version, componentId, null); + return setMonitoringUploadStatusValues(current); + } - if (Objects.nonNull(uploadedFileData)) { - entity.setArtifact(ByteBuffer.wrap(uploadedFileData)); + private MonitoringUploadStatus setMonitoringUploadStatusValues(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + MonitoringUploadStatus monitoringUploadStatus = new MonitoringUploadStatus(); + Collection artifactNames = componentArtifactDao.list(componentMonitoringUploadEntity); + Map artifactTypeToFilename = VendorSoftwareProductUtils.mapArtifactsByType(artifactNames); + if (MapUtils.isNotEmpty(artifactTypeToFilename)) { + if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_TRAP)) { + monitoringUploadStatus.setSnmpTrap(artifactTypeToFilename.get(MonitoringUploadType.SNMP_TRAP)); + } + if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_POLL)) { + monitoringUploadStatus.setSnmpPoll(artifactTypeToFilename.get(MonitoringUploadType.SNMP_POLL)); + } + if (artifactTypeToFilename.containsKey(MonitoringUploadType.VES_EVENTS)) { + monitoringUploadStatus.setVesEvent(artifactTypeToFilename.get(MonitoringUploadType.VES_EVENTS)); + } + } + return monitoringUploadStatus; } - return entity; - } + private ComponentMonitoringUploadEntity setValuesForComponentArtifactEntityUpload(String vspId, Version version, String filename, + String componentId, String artifactId, + MonitoringUploadType monitoringUploadType, + byte[] uploadedFileData) { + ComponentMonitoringUploadEntity entity = new ComponentMonitoringUploadEntity(); + entity.setVspId(vspId); + entity.setVersion(version); + entity.setComponentId(componentId); + entity.setId(artifactId); + entity.setType(monitoringUploadType); + entity.setArtifactName(filename); + if (Objects.nonNull(uploadedFileData)) { + entity.setArtifact(ByteBuffer.wrap(uploadedFileData)); + } + return entity; + } - private FileContentHandler validateZip(String vspId, Version version, byte[] uploadedFileData, - Map> errors) { - FileContentHandler contentMap; - try { - contentMap = - CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData); - VendorSoftwareProductUtils.validateContentZipData(contentMap, errors); - } catch (IOException exception) { - throw new CoreException( - new MonitoringUploadErrorBuilder(vspId, version, - Messages.INVALID_ZIP_FILE.getErrorMessage()) - .build()); + private FileContentHandler validateZip(String vspId, Version version, byte[] uploadedFileData, Map> errors) { + FileContentHandler contentMap; + try { + contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData); + VendorSoftwareProductUtils.validateContentZipData(contentMap, errors); + } catch (IOException exception) { + throw new CoreException(new MonitoringUploadErrorBuilder(vspId, version, Messages.INVALID_ZIP_FILE.getErrorMessage()).build()); + } + return contentMap; } - return contentMap; - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerFactoryImpl.java index 77501db298..83676a79e7 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; @@ -27,14 +26,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; public class NetworkManagerFactoryImpl extends NetworkManagerFactory { - private static final NetworkManager INSTANCE = - new NetworkManagerImpl( - NetworkDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); - @Override - public NetworkManager createInterface() { - return INSTANCE; - } + private static final NetworkManager INSTANCE = new NetworkManagerImpl(NetworkDaoFactory.getInstance().createInterface(), + CompositionEntityDataManagerFactory.getInstance().createInterface(), VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); + + @Override + public NetworkManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImpl.java index 3d278d6934..7f50526fed 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NetworkManagerImpl.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import java.util.Collection; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManager; @@ -35,88 +35,74 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public class NetworkManagerImpl implements NetworkManager { - private final NetworkDao networkDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final VendorSoftwareProductInfoDao vspInfoDao; - public NetworkManagerImpl(NetworkDao networkDao, - CompositionEntityDataManager compositionEntityDataManager, - VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao) { - this.networkDao = networkDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.vspInfoDao = vendorSoftwareProductInfoDao; - } + private final NetworkDao networkDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final VendorSoftwareProductInfoDao vspInfoDao; - @Override - public Collection listNetworks(String vspId, Version version) { - return networkDao.list(new NetworkEntity(vspId, version, null)); - } - - @Override - public NetworkEntity createNetwork(NetworkEntity network) { - if (!vspInfoDao.isManual(network.getVspId(), network.getVersion())) { - throw new CoreException( - new CompositionEditNotAllowedErrorBuilder(network.getVspId(), network.getVersion()) - .build()); + public NetworkManagerImpl(NetworkDao networkDao, CompositionEntityDataManager compositionEntityDataManager, + VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao) { + this.networkDao = networkDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.vspInfoDao = vendorSoftwareProductInfoDao; } - return null; - } - - @Override - public CompositionEntityValidationData updateNetwork(NetworkEntity network) { - NetworkEntity retrieved = getValidatedNetwork(network.getVspId(), network.getVersion(), network.getId()); - - NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(network.getVspId(), network.getVersion())); - schemaInput.setNetwork(retrieved.getNetworkCompositionData()); - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(network, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - networkDao.update(network); + @Override + public Collection listNetworks(String vspId, Version version) { + return networkDao.list(new NetworkEntity(vspId, version, null)); } - return validationData; - } - @Override - public CompositionEntityResponse getNetwork(String vspId, Version version, - String networkId) { - NetworkEntity networkEntity = getValidatedNetwork(vspId, version, networkId); - Network network = networkEntity.getNetworkCompositionData(); - - NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - schemaInput.setNetwork(network); - - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(networkId); - response.setData(network); - response.setSchema(getCompositionSchema(schemaInput)); - return response; - } + @Override + public NetworkEntity createNetwork(NetworkEntity network) { + if (!vspInfoDao.isManual(network.getVspId(), network.getVersion())) { + throw new CoreException(new CompositionEditNotAllowedErrorBuilder(network.getVspId(), network.getVersion()).build()); + } + return null; + } + @Override + public CompositionEntityValidationData updateNetwork(NetworkEntity network) { + NetworkEntity retrieved = getValidatedNetwork(network.getVspId(), network.getVersion(), network.getId()); + NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(network.getVspId(), network.getVersion())); + schemaInput.setNetwork(retrieved.getNetworkCompositionData()); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(network, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + networkDao.update(network); + } + return validationData; + } - private NetworkEntity getValidatedNetwork(String vspId, Version version, String networkId) { - NetworkEntity retrieved = networkDao.get(new NetworkEntity(vspId, version, networkId)); - VersioningUtil.validateEntityExistence(retrieved, new NetworkEntity(vspId, version, networkId), - VspDetails.ENTITY_TYPE); - return retrieved; - } + @Override + public CompositionEntityResponse getNetwork(String vspId, Version version, String networkId) { + NetworkEntity networkEntity = getValidatedNetwork(vspId, version, networkId); + Network network = networkEntity.getNetworkCompositionData(); + NetworkCompositionSchemaInput schemaInput = new NetworkCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + schemaInput.setNetwork(network); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(networkId); + response.setData(network); + response.setSchema(getCompositionSchema(schemaInput)); + return response; + } - @Override - public void deleteNetwork(String vspId, Version version, String networkId) { - if (!vspInfoDao.isManual(vspId, version)) { - throw new CoreException( - new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + private NetworkEntity getValidatedNetwork(String vspId, Version version, String networkId) { + NetworkEntity retrieved = networkDao.get(new NetworkEntity(vspId, version, networkId)); + VersioningUtil.validateEntityExistence(retrieved, new NetworkEntity(vspId, version, networkId), VspDetails.ENTITY_TYPE); + return retrieved; } - } + @Override + public void deleteNetwork(String vspId, Version version, String networkId) { + if (!vspInfoDao.isManual(vspId, version)) { + throw new CoreException(new CompositionEditNotAllowedErrorBuilder(vspId, version).build()); + } + } - protected String getCompositionSchema(NetworkCompositionSchemaInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.network, schemaInput); - } + protected String getCompositionSchema(NetworkCompositionSchemaInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.network, schemaInput); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerFactoryImpl.java index 234dc09ebe..5dd5ccbc9c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; @@ -28,15 +27,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; public class NicManagerFactoryImpl extends NicManagerFactory { - private static final NicManager INSTANCE = - new NicManagerImpl( - NicDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), - NetworkManagerFactory.getInstance().createInterface(), - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); - @Override - public NicManager createInterface() { - return INSTANCE; - } + private static final NicManager INSTANCE = new NicManagerImpl(NicDaoFactory.getInstance().createInterface(), + CompositionEntityDataManagerFactory.getInstance().createInterface(), NetworkManagerFactory.getInstance().createInterface(), + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); + + @Override + public NicManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImpl.java index 0ed58a7703..0cf85d3acd 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/NicManagerImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import java.util.Collection; +import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; @@ -28,7 +30,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.errors.*; +import org.openecomp.sdc.vendorsoftwareproduct.errors.DeleteNicErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.DuplicateNicInComponentErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.NicErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.NicInternalNetworkErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.NicNetworkIdNotAllowedExternalNetworkErrorBuilder; +import org.openecomp.sdc.vendorsoftwareproduct.errors.NotSupportedHeatOnboardMethodErrorBuilder; import org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator.SchemaGenerator; import org.openecomp.sdc.vendorsoftwareproduct.types.CompositionEntityResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.QuestionnaireResponse; @@ -42,202 +49,162 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.Map; -import java.util.stream.Collectors; - public class NicManagerImpl implements NicManager { - private final NicDao nicDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final NetworkManager networkManager; - private final VendorSoftwareProductInfoDao vspInfoDao; - - public NicManagerImpl(NicDao nicDao, - CompositionEntityDataManager compositionEntityDataManager, - NetworkManager networkManager, - VendorSoftwareProductInfoDao vspInfoDao) { - this.nicDao = nicDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.networkManager = networkManager; - this.vspInfoDao = vspInfoDao; - } - - @Override - public Collection listNics(String vspId, Version version, String componentId) { - Collection nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); - - if (!nics.isEmpty()) { - Map networksNameById = listNetworksNameById(vspId, version); - nics.forEach(nicEntity -> { - Nic nic = nicEntity.getNicCompositionData(); - nic.setNetworkName(networksNameById.get(nic.getNetworkId())); - nicEntity.setNicCompositionData(nic); - }); + + private final NicDao nicDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final NetworkManager networkManager; + private final VendorSoftwareProductInfoDao vspInfoDao; + + public NicManagerImpl(NicDao nicDao, CompositionEntityDataManager compositionEntityDataManager, NetworkManager networkManager, + VendorSoftwareProductInfoDao vspInfoDao) { + this.nicDao = nicDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.networkManager = networkManager; + this.vspInfoDao = vspInfoDao; } - return nics; - } - - private Map listNetworksNameById(String vspId, Version version) { - Collection networks = networkManager.listNetworks(vspId, version); - return networks.stream().collect(Collectors.toMap(NetworkEntity::getId, - networkEntity -> networkEntity.getNetworkCompositionData().getName())); - } - - @Override - public NicEntity createNic(NicEntity nic) { - NicEntity createdNic; - if (!vspInfoDao.isManual(nic.getVspId(), nic.getVersion())) { - ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder - .getAddNicNotSupportedHeatOnboardMethodErrorBuilder(); - throw new CoreException(onboardingMethodUpdateErrorCode); - } else { - validateNic(nic); - createdNic = compositionEntityDataManager.createNic(nic); + + @Override + public Collection listNics(String vspId, Version version, String componentId) { + Collection nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); + if (!nics.isEmpty()) { + Map networksNameById = listNetworksNameById(vspId, version); + nics.forEach(nicEntity -> { + Nic nic = nicEntity.getNicCompositionData(); + nic.setNetworkName(networksNameById.get(nic.getNetworkId())); + nicEntity.setNicCompositionData(nic); + }); + } + return nics; } - return createdNic; - } - - - private void validateNic(NicEntity nic) { - Collection listNics = listNics(nic.getVspId(), nic.getVersion(), nic - .getComponentId()); - String networkId = nic.getNicCompositionData().getNetworkId(); - NetworkType networkType = nic.getNicCompositionData().getNetworkType(); - String networkDescription = nic.getNicCompositionData().getNetworkDescription(); - - if (!nic.getNicCompositionData().getName() - .matches(VendorSoftwareProductConstants.NAME_PATTERN)) { - ErrorCode errorCode = NicErrorBuilder - .getNicNameFormatErrorBuilder(VendorSoftwareProductConstants.NAME_PATTERN); - throw new CoreException(errorCode); + + private Map listNetworksNameById(String vspId, Version version) { + Collection networks = networkManager.listNetworks(vspId, version); + return networks.stream() + .collect(Collectors.toMap(NetworkEntity::getId, networkEntity -> networkEntity.getNetworkCompositionData().getName())); } - validateNics(nic, listNics); + @Override + public NicEntity createNic(NicEntity nic) { + NicEntity createdNic; + if (!vspInfoDao.isManual(nic.getVspId(), nic.getVersion())) { + ErrorCode onboardingMethodUpdateErrorCode = NotSupportedHeatOnboardMethodErrorBuilder + .getAddNicNotSupportedHeatOnboardMethodErrorBuilder(); + throw new CoreException(onboardingMethodUpdateErrorCode); + } else { + validateNic(nic); + createdNic = compositionEntityDataManager.createNic(nic); + } + return createdNic; + } + + private void validateNic(NicEntity nic) { + Collection listNics = listNics(nic.getVspId(), nic.getVersion(), nic.getComponentId()); + String networkId = nic.getNicCompositionData().getNetworkId(); + NetworkType networkType = nic.getNicCompositionData().getNetworkType(); + String networkDescription = nic.getNicCompositionData().getNetworkDescription(); + if (!nic.getNicCompositionData().getName().matches(VendorSoftwareProductConstants.NAME_PATTERN)) { + ErrorCode errorCode = NicErrorBuilder.getNicNameFormatErrorBuilder(VendorSoftwareProductConstants.NAME_PATTERN); + throw new CoreException(errorCode); + } + validateNics(nic, listNics); + if (networkType.equals(NetworkType.Internal)) { + validateInternalNetworkType(nic, networkId, networkDescription); + } else if (networkType.equals(NetworkType.External) && !(networkId == null || networkId.isEmpty())) { + final ErrorCode nicNetworkIdNotAllowedExternalNetworkErrorBuilder = new NicNetworkIdNotAllowedExternalNetworkErrorBuilder().build(); + throw new CoreException(nicNetworkIdNotAllowedExternalNetworkErrorBuilder); + } + } - if (networkType.equals(NetworkType.Internal)) { - validateInternalNetworkType(nic, networkId, networkDescription); + private void validateInternalNetworkType(NicEntity nic, String networkId, String networkDescription) { + if (!(networkId == null || networkId.isEmpty())) { + networkManager.getNetwork(nic.getVspId(), nic.getVersion(), networkId); + } + if (!(networkDescription == null || networkDescription.isEmpty())) { + final ErrorCode nicNetworkDescriptionErrorBuilder = NicInternalNetworkErrorBuilder.getNetworkDescriptionInternalNetworkErrorBuilder(); + throw new CoreException(nicNetworkDescriptionErrorBuilder); + } + } + + private void validateNics(NicEntity nic, Collection listNics) { + listNics.forEach(nicEntity -> { + Nic nicdata = nicEntity.getNicCompositionData(); + if (nic.getNicCompositionData().getName().equalsIgnoreCase(nicdata.getName())) { + final ErrorCode duplicateNicInComponentErrorBuilder = new DuplicateNicInComponentErrorBuilder(nic.getNicCompositionData().getName(), + nic.getComponentId()).build(); + throw new CoreException(duplicateNicInComponentErrorBuilder); + } + }); + } - } else if (networkType.equals(NetworkType.External) - && !(networkId == null || networkId.isEmpty())) { - final ErrorCode nicNetworkIdNotAllowedExternalNetworkErrorBuilder = - new NicNetworkIdNotAllowedExternalNetworkErrorBuilder().build(); - throw new CoreException(nicNetworkIdNotAllowedExternalNetworkErrorBuilder); + @Override + public CompositionEntityResponse getNic(String vspId, Version version, String componentId, String nicId) { + NicEntity nicEntity = getValidatedNic(vspId, version, componentId, nicId); + Nic nic = nicEntity.getNicCompositionData(); + NicCompositionSchemaInput schemaInput = new NicCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(vspId, version)); + schemaInput.setNic(nic); + Map networksNameById = listNetworksNameById(vspId, version); + nic.setNetworkName(networksNameById.get(nic.getNetworkId())); + schemaInput.setNetworkIds(networksNameById.keySet()); + CompositionEntityResponse response = new CompositionEntityResponse<>(); + response.setId(nicId); + response.setData(nic); + response.setSchema(getNicCompositionSchema(schemaInput)); + return response; } - } - private void validateInternalNetworkType(NicEntity nic, String networkId, - String networkDescription) { - if (!(networkId == null || networkId.isEmpty())) { - networkManager.getNetwork(nic.getVspId(), nic.getVersion(), networkId); + private NicEntity getValidatedNic(String vspId, Version version, String componentId, String nicId) { + NicEntity retrieved = nicDao.get(new NicEntity(vspId, version, componentId, nicId)); + VersioningUtil.validateEntityExistence(retrieved, new NicEntity(vspId, version, componentId, nicId), VspDetails.ENTITY_TYPE); + return retrieved; } - if (!(networkDescription == null || networkDescription.isEmpty())) { - final ErrorCode nicNetworkDescriptionErrorBuilder = - NicInternalNetworkErrorBuilder.getNetworkDescriptionInternalNetworkErrorBuilder(); - throw new CoreException(nicNetworkDescriptionErrorBuilder); + @Override + public void deleteNic(String vspId, Version version, String componentId, String nicId) { + if (!vspInfoDao.isManual(vspId, version)) { + final ErrorCode deleteNicErrorBuilder = DeleteNicErrorBuilder.getDeleteNicForHeatOnboardedVspErrorBuilder(); + throw new CoreException(deleteNicErrorBuilder); + } + NicEntity nicEntity = getValidatedNic(vspId, version, componentId, nicId); + nicDao.delete(nicEntity); } - } - - private void validateNics(NicEntity nic, Collection listNics) { - listNics.forEach(nicEntity -> { - Nic nicdata = nicEntity.getNicCompositionData(); - if (nic.getNicCompositionData().getName().equalsIgnoreCase(nicdata.getName())) { - final ErrorCode duplicateNicInComponentErrorBuilder = - new DuplicateNicInComponentErrorBuilder(nic.getNicCompositionData().getName(), - nic.getComponentId()).build(); - throw new CoreException(duplicateNicInComponentErrorBuilder); - } - - }); - } - - @Override - public CompositionEntityResponse getNic(String vspId, Version version, String componentId, - String nicId) { - NicEntity nicEntity = getValidatedNic(vspId, version, componentId, nicId); - Nic nic = nicEntity.getNicCompositionData(); - - NicCompositionSchemaInput schemaInput = new NicCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(vspId, version)); - schemaInput.setNic(nic); - Map networksNameById = listNetworksNameById(vspId, version); - nic.setNetworkName(networksNameById.get(nic.getNetworkId())); - schemaInput.setNetworkIds(networksNameById.keySet()); - - CompositionEntityResponse response = new CompositionEntityResponse<>(); - response.setId(nicId); - response.setData(nic); - response.setSchema(getNicCompositionSchema(schemaInput)); - return response; - } - - - private NicEntity getValidatedNic(String vspId, Version version, String componentId, - String nicId) { - NicEntity retrieved = nicDao.get(new NicEntity(vspId, version, componentId, nicId)); - VersioningUtil - .validateEntityExistence(retrieved, new NicEntity(vspId, version, componentId, nicId), - VspDetails.ENTITY_TYPE); - return retrieved; - } - - @Override - public void deleteNic(String vspId, Version version, String componentId, String nicId) { - if (!vspInfoDao.isManual(vspId, version)) { - final ErrorCode deleteNicErrorBuilder = - DeleteNicErrorBuilder.getDeleteNicForHeatOnboardedVspErrorBuilder(); - throw new CoreException(deleteNicErrorBuilder); + + @Override + public CompositionEntityValidationData updateNic(NicEntity nic) { + NicEntity retrieved = getValidatedNic(nic.getVspId(), nic.getVersion(), nic.getComponentId(), nic.getId()); + NicCompositionSchemaInput schemaInput = new NicCompositionSchemaInput(); + schemaInput.setManual(vspInfoDao.isManual(nic.getVspId(), nic.getVersion())); + schemaInput.setNic(retrieved.getNicCompositionData()); + CompositionEntityValidationData validationData = compositionEntityDataManager + .validateEntity(nic, SchemaTemplateContext.composition, schemaInput); + if (CollectionUtils.isEmpty(validationData.getErrors())) { + nicDao.update(nic); + } + return validationData; } - NicEntity nicEntity = getValidatedNic(vspId, version, componentId, nicId); - nicDao.delete(nicEntity); - } + @Override + public QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, String componentId, String nicId) { + QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); + NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, version, componentId, nicId); + VersioningUtil.validateEntityExistence(nicQuestionnaire, new NicEntity(vspId, version, componentId, nicId), VspDetails.ENTITY_TYPE); + questionnaireResponse.setData(nicQuestionnaire.getQuestionnaireData()); + questionnaireResponse.setSchema(getNicQuestionnaireSchema(null)); + return questionnaireResponse; + } - @Override - public CompositionEntityValidationData updateNic(NicEntity nic) { - NicEntity retrieved = - getValidatedNic(nic.getVspId(), nic.getVersion(), nic.getComponentId(), nic.getId()); + @Override + public void updateNicQuestionnaire(String vspId, Version version, String componentId, String nicId, String questionnaireData) { + getNic(vspId, version, componentId, nicId); + nicDao.updateQuestionnaireData(vspId, version, componentId, nicId, questionnaireData); + } - NicCompositionSchemaInput schemaInput = new NicCompositionSchemaInput(); - schemaInput.setManual(vspInfoDao.isManual(nic.getVspId(), nic.getVersion())); - schemaInput.setNic(retrieved.getNicCompositionData()); + protected String getNicQuestionnaireSchema(SchemaTemplateInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, schemaInput); + } - CompositionEntityValidationData validationData = compositionEntityDataManager - .validateEntity(nic, SchemaTemplateContext.composition, schemaInput); - if (CollectionUtils.isEmpty(validationData.getErrors())) { - nicDao.update(nic); + protected String getNicCompositionSchema(NicCompositionSchemaInput schemaInput) { + return SchemaGenerator.generate(SchemaTemplateContext.composition, CompositionEntityType.nic, schemaInput); } - return validationData; - } - - @Override - public QuestionnaireResponse getNicQuestionnaire(String vspId, Version version, - String componentId, String nicId) { - QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); - NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, version, componentId, nicId); - VersioningUtil.validateEntityExistence(nicQuestionnaire, - new NicEntity(vspId, version, componentId, nicId), VspDetails.ENTITY_TYPE); - - questionnaireResponse.setData(nicQuestionnaire.getQuestionnaireData()); - questionnaireResponse.setSchema(getNicQuestionnaireSchema(null)); - return questionnaireResponse; - } - - @Override - public void updateNicQuestionnaire(String vspId, Version version, String componentId, - String nicId, String questionnaireData) { - getNic(vspId, version, componentId, nicId); - - nicDao.updateQuestionnaireData(vspId, version, componentId, nicId, questionnaireData); - } - - protected String getNicQuestionnaireSchema(SchemaTemplateInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, schemaInput); - } - - protected String getNicCompositionSchema(NicCompositionSchemaInput schemaInput) { - return SchemaGenerator - .generate(SchemaTemplateContext.composition, CompositionEntityType.nic, schemaInput); - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java index ae0283b568..03b2654f2f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager; @@ -21,17 +20,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateMan import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; -public class OrchestrationTemplateCandidateManagerFactoryImpl extends - OrchestrationTemplateCandidateManagerFactory { +public class OrchestrationTemplateCandidateManagerFactoryImpl extends OrchestrationTemplateCandidateManagerFactory { - private static final OrchestrationTemplateCandidateManager INSTANCE = - new OrchestrationTemplateCandidateManagerImpl( - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - CandidateServiceFactory.getInstance().createInterface() - ); + private static final OrchestrationTemplateCandidateManager INSTANCE = new OrchestrationTemplateCandidateManagerImpl( + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), CandidateServiceFactory.getInstance().createInterface()); - @Override - public OrchestrationTemplateCandidateManager createInterface() { - return INSTANCE; - } + @Override + public OrchestrationTemplateCandidateManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java index d4c7151c17..7e576789d5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/OrchestrationTemplateCandidateManagerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import java.io.IOException; @@ -47,108 +46,83 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; -public class OrchestrationTemplateCandidateManagerImpl - implements OrchestrationTemplateCandidateManager { - - private final VendorSoftwareProductInfoDao vspInfoDao; - private final CandidateService candidateService; +public class OrchestrationTemplateCandidateManagerImpl implements OrchestrationTemplateCandidateManager { - public OrchestrationTemplateCandidateManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, - CandidateService candidateService - ) { - this.vspInfoDao = vspInfoDao; - this.candidateService = candidateService; - } + private final VendorSoftwareProductInfoDao vspInfoDao; + private final CandidateService candidateService; - @Override - public UploadFileResponse upload(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo) { - final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); - final OrchestrationTemplateFileHandler orchestrationTemplateFileHandler = - OrchestrationUploadFactory.createOrchestrationTemplateFileHandler(onboardPackageInfo.getPackageType()); - - final UploadFileResponse uploadFileResponse = - orchestrationTemplateFileHandler.upload(vspDetails, onboardPackageInfo, candidateService); - uploadFileResponse.setNetworkPackageName(onboardPackage.getFilename()); - return uploadFileResponse; - } + public OrchestrationTemplateCandidateManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, CandidateService candidateService) { + this.vspInfoDao = vspInfoDao; + this.candidateService = candidateService; + } - @Override - public OrchestrationTemplateActionResponse process(String vspId, Version version) { - OrchestrationTemplateCandidateData candidate = - candidateService.getOrchestrationTemplateCandidate(vspId, version) - .orElseThrow(() -> new CoreException( - new OrchestrationTemplateNotFoundErrorBuilder(vspId).build())); + @Override + public UploadFileResponse upload(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo) { + final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); + final OrchestrationTemplateFileHandler orchestrationTemplateFileHandler = OrchestrationUploadFactory + .createOrchestrationTemplateFileHandler(onboardPackageInfo.getPackageType()); + final UploadFileResponse uploadFileResponse = orchestrationTemplateFileHandler.upload(vspDetails, onboardPackageInfo, candidateService); + uploadFileResponse.setNetworkPackageName(onboardPackage.getFilename()); + return uploadFileResponse; + } - return OrchestrationProcessFactory.getInstance(candidate.getFileSuffix()) - .map(processor -> processor.process(getVspDetails(vspId, version), candidate)) - .orElse(new OrchestrationTemplateActionResponse()); - } + @Override + public OrchestrationTemplateActionResponse process(String vspId, Version version) { + OrchestrationTemplateCandidateData candidate = candidateService.getOrchestrationTemplateCandidate(vspId, version) + .orElseThrow(() -> new CoreException(new OrchestrationTemplateNotFoundErrorBuilder(vspId).build())); + return OrchestrationProcessFactory.getInstance(candidate.getFileSuffix()) + .map(processor -> processor.process(getVspDetails(vspId, version), candidate)).orElse(new OrchestrationTemplateActionResponse()); + } - @Override - public Optional getFilesDataStructure(String vspId, Version version) { - return candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version); - } + @Override + public Optional getFilesDataStructure(String vspId, Version version) { + return candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version); + } - @Override - public ValidationResponse updateFilesDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure) { - ValidationResponse response = new ValidationResponse(); - Optional> validateErrors = - candidateService.validateFileDataStructure(fileDataStructure); - if (validateErrors.isPresent()) { - List errorMessages = validateErrors.get(); - if (CollectionUtils.isNotEmpty(errorMessages)) { - Map> errorsMap = Collections.singletonMap(SdcCommon.UPLOAD_FILE, errorMessages); - response.setUploadDataErrors(errorsMap); + @Override + public ValidationResponse updateFilesDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { + ValidationResponse response = new ValidationResponse(); + Optional> validateErrors = candidateService.validateFileDataStructure(fileDataStructure); + if (validateErrors.isPresent()) { + List errorMessages = validateErrors.get(); + if (CollectionUtils.isNotEmpty(errorMessages)) { + Map> errorsMap = Collections.singletonMap(SdcCommon.UPLOAD_FILE, errorMessages); + response.setUploadDataErrors(errorsMap); + return response; + } + } + candidateService.updateOrchestrationTemplateCandidateFileDataStructure(vspId, version, fileDataStructure); return response; - } } - candidateService - .updateOrchestrationTemplateCandidateFileDataStructure(vspId, version, fileDataStructure); - return response; - } - @Override - - public Optional> get(String vspId, Version version) throws IOException { - VspDetails vspDetails = getVspDetails(vspId, version); - - Optional candidateDataEntity = - candidateService.getOrchestrationTemplateCandidate(vspId, version); - - if (!candidateDataEntity.isPresent()) { - return Optional.empty(); + @Override + public Optional> get(String vspId, Version version) throws IOException { + VspDetails vspDetails = getVspDetails(vspId, version); + Optional candidateDataEntity = candidateService.getOrchestrationTemplateCandidate(vspId, version); + if (!candidateDataEntity.isPresent()) { + return Optional.empty(); + } + if (CommonUtil.isFileOriginFromZip(candidateDataEntity.get().getFileSuffix())) { + FilesDataStructure structure = JsonUtil.json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class); + String manifest = candidateService.createManifest(vspDetails, structure); + OnboardingTypesEnum type = OnboardingTypesEnum.getOnboardingTypesEnum(candidateDataEntity.get().getFileSuffix()); + return Optional.of(new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(), + candidateService.replaceManifestInZip(candidateDataEntity.get().getContentData(), manifest, type))); + } + return Optional.of(new ImmutablePair<>(candidateDataEntity.get().getFileSuffix(), candidateDataEntity.get().getContentData().array())); } - if (CommonUtil.isFileOriginFromZip(candidateDataEntity.get().getFileSuffix())) { - FilesDataStructure structure = JsonUtil - .json2Object(candidateDataEntity.get().getFilesDataStructure(), FilesDataStructure.class); - String manifest = candidateService.createManifest(vspDetails, structure); - OnboardingTypesEnum type = - OnboardingTypesEnum.getOnboardingTypesEnum(candidateDataEntity.get().getFileSuffix()); - return Optional.of( - new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(), candidateService - .replaceManifestInZip(candidateDataEntity.get().getContentData(), - manifest, type))); + @Override + public Optional getInfo(String vspId, Version version) { + return candidateService.getOrchestrationTemplateCandidateInfo(vspId, version); } - return Optional.of( - new ImmutablePair<>(candidateDataEntity.get().getFileSuffix(), candidateDataEntity.get() - .getContentData().array())); - } - - @Override - public Optional getInfo(String vspId, Version version) { - return candidateService.getOrchestrationTemplateCandidateInfo(vspId, version); - } - - @Override - public void abort(String vspId, Version version) { - candidateService.deleteOrchestrationTemplateCandidate(vspId, version); - } + @Override + public void abort(String vspId, Version version) { + candidateService.deleteOrchestrationTemplateCandidate(vspId, version); + } - private VspDetails getVspDetails(String vspId, Version version) { - return vspInfoDao.get(new VspDetails(vspId, version)); - } -} \ No newline at end of file + private VspDetails getVspDetails(String vspId, Version version) { + return vspInfoDao.get(new VspDetails(vspId, version)); + } +} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerFactoryImpl.java index b1b8ff4d42..9f10df65a5 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.core.dao.UniqueValueDaoFactory; @@ -26,12 +25,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.ProcessManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; public class ProcessManagerFactoryImpl extends ProcessManagerFactory { - private static final ProcessManager INSTANCE = - new ProcessManagerImpl(ProcessDaoFactory.getInstance().createInterface(), - UniqueValueDaoFactory.getInstance().createInterface()); - @Override - public ProcessManager createInterface() { - return INSTANCE; - } + private static final ProcessManager INSTANCE = new ProcessManagerImpl(ProcessDaoFactory.getInstance().createInterface(), + UniqueValueDaoFactory.getInstance().createInterface()); + + @Override + public ProcessManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java index 855007dfd9..a5347350b0 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/ProcessManagerImpl.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.Collection; import org.openecomp.core.dao.UniqueValueDao; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.file.FileUtils; @@ -31,191 +36,144 @@ import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.errors.VersioningErrorCodes; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.Collection; - public class ProcessManagerImpl implements ProcessManager { - private static final String PROCESS_ARTIFACT_NOT_EXIST_MSG = - "Process artifact for process with Id %s does not exist for %s with Id %s and version %s"; - private final ProcessDao processDao; - private final UniqueValueUtil uniqueValueUtil; - - public ProcessManagerImpl(ProcessDao processDao, UniqueValueDao uniqueValueDao) { - this.processDao = processDao; - this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); - } - - @Override - public Collection listProcesses(String vspId, Version version, - String componentId) { - return processDao.list(new ProcessEntity(vspId, version, componentId, null)); - } - - @Override - public void deleteProcesses(String vspId, Version version, String componentId) { - ProcessEntity allProcesses = new ProcessEntity(vspId, version, componentId, null); - Collection processes = processDao.list(allProcesses); - - if (!processes.isEmpty()) { - for (ProcessEntity process : processes) { - deleteUniqueValue(process.getVspId(), process.getVersion(), process.getComponentId(), - process.getName()); - } - } - - if (componentId == null) { - processDao.deleteVspAll(vspId,version); - } else { - processDao.deleteAll(allProcesses); - } - } - - @Override - public ProcessEntity createProcess(ProcessEntity process) { - validateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), - process.getName()); - - processDao.create(process); - createUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), - process.getName()); - return process; - } - - @Override - public ProcessEntity getProcess(String vspId, Version version, String componentId, - String processId) { - ProcessEntity retrieved = - processDao.get(new ProcessEntity(vspId, version, componentId, processId)); - validateProcessExistence(vspId, version, componentId, processId, retrieved); - return retrieved; - } - - @Override - public void updateProcess(ProcessEntity process) { - ProcessEntity retrieved = processDao.get(process); - validateProcessExistence(process.getVspId(), process.getVersion(), process.getComponentId(), - process.getId(), retrieved); - - updateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), - retrieved.getName(), process.getName()); - processDao.update(process); - } - - @Override - public void deleteProcess(String vspId, Version version, String componentId, String processId) { - ProcessEntity retrieved = getProcess(vspId, version, componentId, processId); - - processDao.delete(retrieved); - deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), - retrieved.getName()); - } - - - @Override - public File getProcessArtifact(String vspId, Version version, String componentId, - String processId) { - ProcessEntity retrieved = getValidatedProcessArtifact(vspId, version, componentId, processId); - - File file = new File(String.format("%s_%s_%s", vspId, componentId, processId)); - try (FileOutputStream fos = new FileOutputStream(file)) { - fos.write(retrieved.getArtifact().array()); - } catch (IOException exception) { - throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); - } - return file; - } - - @Override - public void deleteProcessArtifact(String vspId, Version version, String componentId, - String processId) { - ProcessEntity retrieved = getValidatedProcessArtifact(vspId, version, componentId, processId); - - processDao.deleteArtifact(retrieved); - } - - @Override - public void uploadProcessArtifact(InputStream artifactFile, String artifactFileName, String vspId, - Version version, String componentId, String processId) { - ProcessEntity process = getProcess(vspId, version, componentId, processId); - process.setArtifactName(artifactFileName); - process.setArtifact(readArtifact(artifactFile)); - processDao.uploadArtifact(process); - } - - private ProcessEntity getValidatedProcessArtifact(String vspId, Version version, - String componentId, String processId) { - ProcessEntity retrieved = - processDao.getArtifact(new ProcessEntity(vspId, version, componentId, processId)); - validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); - return retrieved; - } - - private ByteBuffer readArtifact(InputStream artifactInputStream) { - if (artifactInputStream == null) { - throw new CoreException(new UploadInvalidErrorBuilder().build()); - } - try { - return ByteBuffer.wrap(FileUtils.toByteArray(artifactInputStream)); - } catch (RuntimeException exception) { - throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); - } - } - - - private void validateProcessExistence(String vspId, Version version, String componentId, - String processId, ProcessEntity retrieved) { - VersioningUtil.validateEntityExistence(retrieved, - new ProcessEntity(vspId, version, componentId, processId), - VspDetails.ENTITY_TYPE); - } - - private void validateProcessArtifactExistence(String vspId, Version version, String componentId, - String processId, ProcessEntity retrieved) { - ProcessEntity inputProcess = new ProcessEntity(vspId, version, componentId, processId); - VersioningUtil.validateEntityExistence(retrieved, inputProcess, VspDetails.ENTITY_TYPE); - if (retrieved.getArtifact() == null) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND) - .withMessage(String.format(PROCESS_ARTIFACT_NOT_EXIST_MSG, - processId, VspDetails.ENTITY_TYPE, vspId, version)).build()); - } - } - - - protected void validateUniqueName(String vspId, Version version, String componentId, - String processName) { - uniqueValueUtil.validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, - vspId, version.getId(), componentId, processName); - } - - protected void createUniqueName(String vspId, Version version, String componentId, - String processName) { - uniqueValueUtil - .createUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, - version.getId(), componentId, processName); - } - - protected void updateUniqueName(String vspId, Version version, String componentId, - String oldProcessName, String newProcessName) { - uniqueValueUtil - .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, oldProcessName, - newProcessName, vspId, version.getId(), componentId); - } - - protected void deleteUniqueValue(String vspId, Version version, String componentId, - String processName) { - if (componentId == null) { - uniqueValueUtil - .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, - version.getId(), processName); - } - uniqueValueUtil - .deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, - version.getId(), componentId, processName); - } + private static final String PROCESS_ARTIFACT_NOT_EXIST_MSG = "Process artifact for process with Id %s does not exist for %s with Id %s and version %s"; + private final ProcessDao processDao; + private final UniqueValueUtil uniqueValueUtil; + + public ProcessManagerImpl(ProcessDao processDao, UniqueValueDao uniqueValueDao) { + this.processDao = processDao; + this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); + } + + @Override + public Collection listProcesses(String vspId, Version version, String componentId) { + return processDao.list(new ProcessEntity(vspId, version, componentId, null)); + } + + @Override + public void deleteProcesses(String vspId, Version version, String componentId) { + ProcessEntity allProcesses = new ProcessEntity(vspId, version, componentId, null); + Collection processes = processDao.list(allProcesses); + if (!processes.isEmpty()) { + for (ProcessEntity process : processes) { + deleteUniqueValue(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); + } + } + if (componentId == null) { + processDao.deleteVspAll(vspId, version); + } else { + processDao.deleteAll(allProcesses); + } + } + + @Override + public ProcessEntity createProcess(ProcessEntity process) { + validateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); + processDao.create(process); + createUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), process.getName()); + return process; + } + + @Override + public ProcessEntity getProcess(String vspId, Version version, String componentId, String processId) { + ProcessEntity retrieved = processDao.get(new ProcessEntity(vspId, version, componentId, processId)); + validateProcessExistence(vspId, version, componentId, processId, retrieved); + return retrieved; + } + + @Override + public void updateProcess(ProcessEntity process) { + ProcessEntity retrieved = processDao.get(process); + validateProcessExistence(process.getVspId(), process.getVersion(), process.getComponentId(), process.getId(), retrieved); + updateUniqueName(process.getVspId(), process.getVersion(), process.getComponentId(), retrieved.getName(), process.getName()); + processDao.update(process); + } + + @Override + public void deleteProcess(String vspId, Version version, String componentId, String processId) { + ProcessEntity retrieved = getProcess(vspId, version, componentId, processId); + processDao.delete(retrieved); + deleteUniqueValue(retrieved.getVspId(), retrieved.getVersion(), retrieved.getComponentId(), retrieved.getName()); + } + + @Override + public File getProcessArtifact(String vspId, Version version, String componentId, String processId) { + ProcessEntity retrieved = getValidatedProcessArtifact(vspId, version, componentId, processId); + File file = new File(String.format("%s_%s_%s", vspId, componentId, processId)); + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(retrieved.getArtifact().array()); + } catch (IOException exception) { + throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); + } + return file; + } + + @Override + public void deleteProcessArtifact(String vspId, Version version, String componentId, String processId) { + ProcessEntity retrieved = getValidatedProcessArtifact(vspId, version, componentId, processId); + processDao.deleteArtifact(retrieved); + } + + @Override + public void uploadProcessArtifact(InputStream artifactFile, String artifactFileName, String vspId, Version version, String componentId, + String processId) { + ProcessEntity process = getProcess(vspId, version, componentId, processId); + process.setArtifactName(artifactFileName); + process.setArtifact(readArtifact(artifactFile)); + processDao.uploadArtifact(process); + } + + private ProcessEntity getValidatedProcessArtifact(String vspId, Version version, String componentId, String processId) { + ProcessEntity retrieved = processDao.getArtifact(new ProcessEntity(vspId, version, componentId, processId)); + validateProcessArtifactExistence(vspId, version, componentId, processId, retrieved); + return retrieved; + } + + private ByteBuffer readArtifact(InputStream artifactInputStream) { + if (artifactInputStream == null) { + throw new CoreException(new UploadInvalidErrorBuilder().build()); + } + try { + return ByteBuffer.wrap(FileUtils.toByteArray(artifactInputStream)); + } catch (RuntimeException exception) { + throw new CoreException(new UploadInvalidErrorBuilder().build(), exception); + } + } + + private void validateProcessExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { + VersioningUtil.validateEntityExistence(retrieved, new ProcessEntity(vspId, version, componentId, processId), VspDetails.ENTITY_TYPE); + } + + private void validateProcessArtifactExistence(String vspId, Version version, String componentId, String processId, ProcessEntity retrieved) { + ProcessEntity inputProcess = new ProcessEntity(vspId, version, componentId, processId); + VersioningUtil.validateEntityExistence(retrieved, inputProcess, VspDetails.ENTITY_TYPE); + if (retrieved.getArtifact() == null) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND) + .withMessage(String.format(PROCESS_ARTIFACT_NOT_EXIST_MSG, processId, VspDetails.ENTITY_TYPE, vspId, version)).build()); + } + } + + protected void validateUniqueName(String vspId, Version version, String componentId, String processName) { + uniqueValueUtil + .validateUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, version.getId(), componentId, processName); + } + + protected void createUniqueName(String vspId, Version version, String componentId, String processName) { + uniqueValueUtil.createUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, version.getId(), componentId, processName); + } + + protected void updateUniqueName(String vspId, Version version, String componentId, String oldProcessName, String newProcessName) { + uniqueValueUtil + .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, oldProcessName, newProcessName, vspId, version.getId(), + componentId); + } + + protected void deleteUniqueValue(String vspId, Version version, String componentId, String processName) { + if (componentId == null) { + uniqueValueUtil.deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, version.getId(), processName); + } + uniqueValueUtil.deleteUniqueValue(VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME, vspId, version.getId(), componentId, processName); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java index 3f45885999..82b1d0a64c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VendorSoftwareProductManagerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductInvalidErrorBuilder.candidateDataNotProcessedOrAbortedErrorBuilder; @@ -141,6 +140,7 @@ import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductManager { + private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductManager.class); private VspMergeDao vspMergeDao; private OrchestrationTemplateDao orchestrationTemplateDao; @@ -162,51 +162,42 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private UniqueValueUtil uniqueValueUtil; private CandidateService candidateService; + private static ErrorCode createMissingMandatoryFieldError(String fieldName) { + return new ValidationErrorBuilder("must be supplied", fieldName).build(); + } + @Override public ValidationResponse validate(VspDetails vspDetails) throws IOException { List vspErrors = new ArrayList<>(validateVspFields(vspDetails)); ValidationResponse validationResponse = new ValidationResponse(); - if (Objects.nonNull(vspDetails.getOnboardingMethod()) && OnboardingMethod.Manual.name() - .equals(vspDetails.getOnboardingMethod())) { + if (Objects.nonNull(vspDetails.getOnboardingMethod()) && OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod())) { validateManualOnboardingMethod(vspDetails, validationResponse, vspErrors); } else { - validateOrchestrationTemplateCandidate(validationResponse, vspErrors, vspDetails.getId(), - vspDetails.getVersion()); + validateOrchestrationTemplateCandidate(validationResponse, vspErrors, vspDetails.getId(), vspDetails.getVersion()); if (!validationResponse.isValid()) { return validationResponse; } validateLicense(vspDetails, vspErrors); - OrchestrationTemplateEntity orchestrationTemplate = - orchestrationTemplateDao.get(vspDetails.getId(), vspDetails.getVersion()); - ToscaServiceModel serviceModel = - serviceModelDao.getServiceModel(vspDetails.getId(), vspDetails.getVersion()); + OrchestrationTemplateEntity orchestrationTemplate = orchestrationTemplateDao.get(vspDetails.getId(), vspDetails.getVersion()); + ToscaServiceModel serviceModel = serviceModelDao.getServiceModel(vspDetails.getId(), vspDetails.getVersion()); if (isOrchestrationTemplateMissing(orchestrationTemplate) || isServiceModelMissing(serviceModel)) { vspErrors.add(VendorSoftwareProductInvalidErrorBuilder - .vendorSoftwareProductMissingServiceModelErrorBuilder(vspDetails.getId(), - vspDetails.getVersion())); + .vendorSoftwareProductMissingServiceModelErrorBuilder(vspDetails.getId(), vspDetails.getVersion())); } validationResponse.setUploadDataErrors(validateOrchestrationTemplate(orchestrationTemplate)); } - - QuestionnaireValidationResult questionnaireValidationResult = - validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion(), vspDetails.getOnboardingMethod()); - + QuestionnaireValidationResult questionnaireValidationResult = validateQuestionnaire(vspDetails.getId(), vspDetails.getVersion(), + vspDetails.getOnboardingMethod()); if (Objects.nonNull(questionnaireValidationResult)) { if (validationResponse.getQuestionnaireValidationResult() == null - || validationResponse.getQuestionnaireValidationResult().getValidationData() == null) { + || validationResponse.getQuestionnaireValidationResult().getValidationData() == null) { validationResponse.setQuestionnaireValidationResult(questionnaireValidationResult); } else { - validationResponse.getQuestionnaireValidationResult().getValidationData() - .addAll(questionnaireValidationResult.getValidationData()); + validationResponse.getQuestionnaireValidationResult().getValidationData().addAll(questionnaireValidationResult.getValidationData()); } } - Collection componentDependencies = componentDependencyModelDao - .list(new ComponentDependencyModelEntity( - vspDetails.getId(), - vspDetails.getVersion(), - null)); - + .list(new ComponentDependencyModelEntity(vspDetails.getId(), vspDetails.getVersion(), null)); if (validateComponentDependencies(componentDependencies)) { vspErrors.add(ComponentDependencyModelErrorBuilder.getCyclicDependencyComponentErrorBuilder()); } @@ -216,71 +207,58 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } private void validateLicense(VspDetails vspDetails, List vspErrors) { - if (vspDetails.getVlmVersion() != null || vspDetails.getLicenseAgreement() != null - || vspDetails.getFeatureGroups() != null) { + if (vspDetails.getVlmVersion() != null || vspDetails.getLicenseAgreement() != null || vspDetails.getFeatureGroups() != null) { vspErrors.addAll(validateMandatoryLicenseFields(vspDetails)); } } - private void validateOrchestrationTemplateCandidate(ValidationResponse validationResponse, - List vspErrors, String vspId, Version version) { + private void validateOrchestrationTemplateCandidate(ValidationResponse validationResponse, List vspErrors, String vspId, + Version version) { orchestrationTemplateCandidateManager.getInfo(vspId, version).ifPresent(candidateInfo -> { String fileName = candidateInfo.getFileName(); - vspErrors.add(candidateInfo.getValidationData().isEmpty() ? candidateDataNotProcessedOrAbortedErrorBuilder( - fileName) : invalidProcessedCandidate(fileName)); + vspErrors.add(candidateInfo.getValidationData().isEmpty() ? candidateDataNotProcessedOrAbortedErrorBuilder(fileName) + : invalidProcessedCandidate(fileName)); validationResponse.setVspErrors(vspErrors); }); } - private void validateManualOnboardingMethod(VspDetails vspDetails, ValidationResponse validationResponse, - List vspErrors) { + private void validateManualOnboardingMethod(VspDetails vspDetails, ValidationResponse validationResponse, List vspErrors) { vspErrors.addAll(validateMandatoryLicenseFields(vspDetails)); - - Collection deploymentFlavors = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails.getVersion(), null)); + Collection deploymentFlavors = deploymentFlavorDao + .list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails.getVersion(), null)); if (CollectionUtils.isEmpty(deploymentFlavors)) { vspErrors.add(vspMissingDeploymentFlavorErrorBuilder()); } vspErrors.addAll(validateDeploymentFlavors(deploymentFlavors)); - - Set componentValidationResult = - componentValidation(vspDetails.getId(), vspDetails.getVersion()); + Set componentValidationResult = componentValidation(vspDetails.getId(), vspDetails.getVersion()); if (!CollectionUtils.isEmpty(componentValidationResult)) { if (validationResponse.getQuestionnaireValidationResult() == null - || validationResponse.getQuestionnaireValidationResult().getValidationData() == null) { - validationResponse - .setQuestionnaireValidationResult(new QuestionnaireValidationResult(componentValidationResult)); + || validationResponse.getQuestionnaireValidationResult().getValidationData() == null) { + validationResponse.setQuestionnaireValidationResult(new QuestionnaireValidationResult(componentValidationResult)); } else { - validationResponse.getQuestionnaireValidationResult().getValidationData() - .addAll(componentValidationResult); + validationResponse.getQuestionnaireValidationResult().getValidationData().addAll(componentValidationResult); } } } @Override public Map> compile(String vspId, Version version) { - ToscaServiceModel serviceModel = - OnboardingMethod.Manual.name().equals(getValidatedVsp(vspId, version).getOnboardingMethod()) - //Generate Tosca service model for Manual Onboarding flow - ? manualVspToscaManager - .generateToscaModel(manualVspToscaManager.gatherVspInformation(vspId, version)) - : serviceModelDao.getServiceModel(vspId, version); - + ToscaServiceModel serviceModel = OnboardingMethod.Manual.name().equals(getValidatedVsp(vspId, version).getOnboardingMethod()) + //Generate Tosca service model for Manual Onboarding flow + ? manualVspToscaManager.generateToscaModel(manualVspToscaManager.gatherVspInformation(vspId, version)) + : serviceModelDao.getServiceModel(vspId, version); return compile(vspId, version, serviceModel); } private boolean validateComponentDependencies(Collection componentDependencies) { ComponentDependencyTracker dependencyTracker = new ComponentDependencyTracker(); - for (ComponentDependencyModelEntity componentDependency : componentDependencies) { - dependencyTracker.addDependency(componentDependency.getSourceComponentId(), - componentDependency.getTargetComponentId()); + dependencyTracker.addDependency(componentDependency.getSourceComponentId(), componentDependency.getTargetComponentId()); } return dependencyTracker.isCyclicDependencyPresent(); } private Collection validateDeploymentFlavors(Collection deploymentFlavors) { - Collection errorCodeList = new ArrayList<>(); if (!CollectionUtils.isEmpty(deploymentFlavors)) { deploymentFlavors.forEach(deploymentFlavor -> { @@ -288,32 +266,26 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa DeploymentFlavor deploymentLocalFlavor = deployment.getDeploymentFlavorCompositionData(); if (deploymentLocalFlavor != null) { if (deploymentLocalFlavor.getFeatureGroupId() == null) { - ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder. - getFeatureGroupMandatoryErrorBuilder( - deploymentLocalFlavor - .getModel()); + ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder + .getFeatureGroupMandatoryErrorBuilder(deploymentLocalFlavor.getModel()); errorCodeList.add(deploymentFlavorErrorBuilder); } - validateComponentComputeAssociations(errorCodeList, deploymentFlavor, deployment, - deploymentLocalFlavor); + validateComponentComputeAssociations(errorCodeList, deploymentFlavor, deployment, deploymentLocalFlavor); } }); } return errorCodeList; } - private void validateComponentComputeAssociations(Collection errorCodeList, - DeploymentFlavorEntity deploymentFlavor, DeploymentFlavorEntity deployment, - DeploymentFlavor deploymentlocalFlavor) { - List componentComputeAssociations = - deploymentlocalFlavor.getComponentComputeAssociations(); + private void validateComponentComputeAssociations(Collection errorCodeList, DeploymentFlavorEntity deploymentFlavor, + DeploymentFlavorEntity deployment, DeploymentFlavor deploymentlocalFlavor) { + List componentComputeAssociations = deploymentlocalFlavor.getComponentComputeAssociations(); if (CollectionUtils.isEmpty(componentComputeAssociations)) { validateCompositionEntity(errorCodeList, deploymentFlavor, deployment, deploymentlocalFlavor); } else { componentComputeAssociations.forEach(componentComputeAssociation -> { if (componentComputeAssociation == null || !(componentComputeAssociation.getComponentId() != null - && componentComputeAssociation.getComputeFlavorId() - != null)) { + && componentComputeAssociation.getComputeFlavorId() != null)) { validateCompositionEntity(errorCodeList, deploymentFlavor, deployment, deploymentlocalFlavor); } }); @@ -321,13 +293,12 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } private void validateCompositionEntity(Collection errorCodeList, DeploymentFlavorEntity deploymentFlavor, - DeploymentFlavorEntity deployment, DeploymentFlavor deploymentlocalFlavor) { - CompositionEntityValidationData compositionEntityValidationData = - new CompositionEntityValidationData(CompositionEntityType.deployment, deploymentFlavor.getId()); + DeploymentFlavorEntity deployment, DeploymentFlavor deploymentlocalFlavor) { + CompositionEntityValidationData compositionEntityValidationData = new CompositionEntityValidationData(CompositionEntityType.deployment, + deploymentFlavor.getId()); compositionEntityValidationData.setEntityName(deployment.getDeploymentFlavorCompositionData().getModel()); ErrorCode deploymentFlavorErrorBuilder = DeploymentFlavorErrorBuilder - .getInvalidComponentComputeAssociationErrorBuilder( - deploymentlocalFlavor.getModel()); + .getInvalidComponentComputeAssociationErrorBuilder(deploymentlocalFlavor.getModel()); errorCodeList.add(deploymentFlavorErrorBuilder); } @@ -338,15 +309,12 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa components.forEach(component -> { validateImage(vspId, version, validationData, component); validateNic(vspId, version, validationData, component); - }); } - return validationData; } - private void validateNic(String vspId, Version version, Set validationData, - ComponentEntity component) { + private void validateNic(String vspId, Version version, Set validationData, ComponentEntity component) { Collection nics = nicDao.list(new NicEntity(vspId, version, component.getId(), null)); if (CollectionUtils.isNotEmpty(nics)) { nics.forEach(nicEntity -> { @@ -354,11 +322,10 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa NetworkType networkType = nic.getNicCompositionData().getNetworkType(); String networkId = nic.getNicCompositionData().getNetworkId(); if (networkType.equals(NetworkType.Internal) && networkId == null) { - CompositionEntityValidationData compositionEntityValidationData = - new CompositionEntityValidationData(CompositionEntityType.nic, nic.getId()); + CompositionEntityValidationData compositionEntityValidationData = new CompositionEntityValidationData(CompositionEntityType.nic, + nic.getId()); compositionEntityValidationData.setEntityName(nic.getNicCompositionData().getName()); - ErrorCode nicInternalNetworkErrorBuilder = - NicInternalNetworkErrorBuilder.getNicNullNetworkIdInternalNetworkIdErrorBuilder(); + ErrorCode nicInternalNetworkErrorBuilder = NicInternalNetworkErrorBuilder.getNicNullNetworkIdInternalNetworkIdErrorBuilder(); List errors = new ArrayList<>(); errors.add(nicInternalNetworkErrorBuilder.message()); compositionEntityValidationData.setErrors(errors); @@ -368,12 +335,11 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } } - private void validateImage(String vspId, Version version, Set validationData, - ComponentEntity component) { + private void validateImage(String vspId, Version version, Set validationData, ComponentEntity component) { Collection images = imageDao.list(new ImageEntity(vspId, version, component.getId(), null)); if (CollectionUtils.isEmpty(images)) { - CompositionEntityValidationData compositionEntityValidationData = - new CompositionEntityValidationData(component.getType(), component.getId()); + CompositionEntityValidationData compositionEntityValidationData = new CompositionEntityValidationData(component.getType(), + component.getId()); compositionEntityValidationData.setEntityName(component.getComponentCompositionData().getDisplayName()); ErrorCode vfcMissingImageErrorBuilder = ComponentErrorBuilder.vfcMissingImageErrorBuilder(); List errors = new ArrayList<>(); @@ -385,7 +351,6 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private List validateVspFields(VspDetails vspDetails) { List errors = new ArrayList<>(); - if (vspDetails.getName() == null) { errors.add(createMissingMandatoryFieldError("name")); } @@ -418,52 +383,39 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return errors; } - private static ErrorCode createMissingMandatoryFieldError(String fieldName) { - return new ValidationErrorBuilder("must be supplied", fieldName).build(); - } - - private Map> compile(String vendorSoftwareProductId, Version version, - ToscaServiceModel serviceModel) { + private Map> compile(String vendorSoftwareProductId, Version version, ToscaServiceModel serviceModel) { if (isServiceModelMissing(serviceModel)) { return null; } - enrichedServiceModelDao.deleteAll(vendorSoftwareProductId, version); - - EnrichmentManager enrichmentManager = - EnrichmentManagerFactory.getInstance().createInterface(); + EnrichmentManager enrichmentManager = EnrichmentManagerFactory.getInstance().createInterface(); enrichmentManager.init(vendorSoftwareProductId, version); enrichmentManager.setModel(serviceModel); Map> enrichErrors = enrichmentManager.enrich(); - enrichedServiceModelDao.storeServiceModel(vendorSoftwareProductId, version, enrichmentManager.getModel()); - return enrichErrors; } private Collection validateLicensingData(VspDetails vspDetails) { if (vspDetails.getVendorId() != null) { - Optional errorCode = - vendorLicenseFacade.validateVendorForUsage(vspDetails.getVendorId(), vspDetails.getVlmVersion()); + Optional errorCode = vendorLicenseFacade.validateVendorForUsage(vspDetails.getVendorId(), vspDetails.getVlmVersion()); if (errorCode.isPresent()) { return Collections.singleton(errorCode.get()); } } - - if (vspDetails.getVendorId() == null || vspDetails.getVlmVersion() == null - || vspDetails.getLicenseAgreement() == null || CollectionUtils - .isEmpty(vspDetails.getFeatureGroups())) { + if (vspDetails.getVendorId() == null || vspDetails.getVlmVersion() == null || vspDetails.getLicenseAgreement() == null || CollectionUtils + .isEmpty(vspDetails.getFeatureGroups())) { return Collections.emptyList(); } - return vendorLicenseFacade.validateLicensingData(vspDetails.getVendorId(), vspDetails.getVlmVersion(), - vspDetails.getLicenseAgreement(), vspDetails.getFeatureGroups()); + return vendorLicenseFacade.validateLicensingData(vspDetails.getVendorId(), vspDetails.getVlmVersion(), vspDetails.getLicenseAgreement(), + vspDetails.getFeatureGroups()); } @Override public VspDetails createVsp(VspDetails vspDetails) { vspInfoDao.create(vspDetails); vspInfoDao.updateQuestionnaireData(vspDetails.getId(), vspDetails.getVersion(), - new JsonSchemaDataGenerator(getVspQuestionnaireSchema(null)).generateData()); + new JsonSchemaDataGenerator(getVspQuestionnaireSchema(null)).generateData()); return vspDetails; } @@ -471,16 +423,15 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa public void updateVsp(VspDetails vspDetails) { VspDetails retrieved = vspInfoDao.get(vspDetails); if (retrieved == null) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder().withMessage( - String.format("Vsp with id %s and version %s does not exist.", vspDetails.getId(), - vspDetails.getVersion().getId()))).build()); + throw new CoreException((new ErrorCode.ErrorCodeBuilder() + .withMessage(String.format("Vsp with id %s and version %s does not exist.", vspDetails.getId(), vspDetails.getVersion().getId()))) + .build()); } vspDetails.setOnboardingMethod(retrieved.getOnboardingMethod()); - //If any existing feature group is removed from VSP which is also associated in DF then + //update DF to remove feature group associations. updateDeploymentFlavor(vspDetails); - updateUniqueName(retrieved.getName(), vspDetails.getName()); vspInfoDao.update(vspDetails); } @@ -489,10 +440,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa final List featureGroups = vspDetails.getFeatureGroups(); if (featureGroups != null) { final Collection deploymentFlavorEntities = deploymentFlavorDao - .list(new DeploymentFlavorEntity( - vspDetails.getId(), - vspDetails.getVersion(), - null)); + .list(new DeploymentFlavorEntity(vspDetails.getId(), vspDetails.getVersion(), null)); if (Objects.nonNull(deploymentFlavorEntities)) { for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { updateDeploymentFlavourEntity(featureGroups, deploymentFlavorEntity); @@ -501,19 +449,16 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } } - private void updateDeploymentFlavourEntity(List featureGroups, - DeploymentFlavorEntity deploymentFlavorEntity) { + private void updateDeploymentFlavourEntity(List featureGroups, DeploymentFlavorEntity deploymentFlavorEntity) { final String featureGroupId = deploymentFlavorEntity.getDeploymentFlavorCompositionData().getFeatureGroupId(); if (!featureGroups.contains(featureGroupId)) { - DeploymentFlavor deploymentFlavorCompositionData = - deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); deploymentFlavorCompositionData.setFeatureGroupId(null); deploymentFlavorEntity.setDeploymentFlavorCompositionData(deploymentFlavorCompositionData); deploymentFlavorDao.update(deploymentFlavorEntity); } } - @Override public VspDetails getVsp(String vspId, Version version) { return getValidatedVsp(vspId, version); @@ -543,14 +488,11 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa if (packageInfo == null) { throw new CoreException(new PackageNotFoundErrorBuilder(vspId, version).build()); } - ByteBuffer translatedFileBuffer = packageInfo.getTranslatedFile(); if (translatedFileBuffer == null) { throw new CoreException(new PackageInvalidErrorBuilder(vspId, version).build()); } - File translatedFile = new File(VendorSoftwareProductConstants.VSP_PACKAGE_ZIP); - try (FileOutputStream fos = new FileOutputStream(translatedFile)) { fos.write(translatedFileBuffer.array()); } catch (IOException exception) { @@ -566,11 +508,9 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa if (contentData == null) { return new byte[0]; } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (final ZipOutputStream zos = new ZipOutputStream(baos); - ZipInputStream ignored = new ZipInputStream(new ByteArrayInputStream(contentData.array()))) { + try (final ZipOutputStream zos = new ZipOutputStream(baos); ZipInputStream ignored = new ZipInputStream( + new ByteArrayInputStream(contentData.array()))) { zos.write(contentData.array()); } catch (IOException exception) { throw new CoreException(new FileCreationErrorBuilder(vspId).build(), exception); @@ -585,9 +525,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public Optional getOrchestrationTemplateStructure(String vspId, Version version) { - Optional jsonFileDataStructure = - orchestrationTemplateDao.getOrchestrationTemplateStructure(vspId, version); - + Optional jsonFileDataStructure = orchestrationTemplateDao.getOrchestrationTemplateStructure(vspId, version); if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) { return Optional.of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); } else { @@ -604,10 +542,9 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa populateVersionsForVlm(vspDetails.getVendorId(), vlmVersion); } final PackageInfo packageInfo = createPackageInfo(vspDetails); - final ToscaFileOutputServiceCsarImpl toscaServiceTemplateServiceCsar = new ToscaFileOutputServiceCsarImpl(); - final FileContentHandler licenseArtifacts = licenseArtifactsService.createLicenseArtifacts(vspDetails.getId(), - vspDetails.getVendorId(), vlmVersion, vspDetails.getFeatureGroups()); + final FileContentHandler licenseArtifacts = licenseArtifactsService + .createLicenseArtifacts(vspDetails.getId(), vspDetails.getVendorId(), vlmVersion, vspDetails.getFeatureGroups()); final ETSIService etsiService = new ETSIServiceImpl(); if (etsiService.isSol004WithToscaMetaDirectory(toscaServiceModel.getArtifactFiles())) { final FileContentHandler handler = toscaServiceModel.getArtifactFiles(); @@ -617,20 +554,18 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa packageInfo.setResourceType(etsiService.getResourceType(manifest).name()); packageInfo.setVendorRelease(etsiService.getHighestCompatibleSpecificationVersion(handler).getOriginalValue()); } - packageInfo.setTranslatedFile( - ByteBuffer.wrap(toscaServiceTemplateServiceCsar.createOutputFile(toscaServiceModel, licenseArtifacts))); - + packageInfo.setTranslatedFile(ByteBuffer.wrap(toscaServiceTemplateServiceCsar.createOutputFile(toscaServiceModel, licenseArtifacts))); packageInfoDao.create(packageInfo); return packageInfo; } void populateVersionsForVlm(String vlmId, Version vlmVersion) { VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); - versioningManager.list(vlmId).stream().filter(version -> version.getId().equalsIgnoreCase(vlmVersion.getId())) - .findAny().ifPresent(version -> { - vlmVersion.setMinor(version.getMinor()); - vlmVersion.setMajor(version.getMajor()); - }); + versioningManager.list(vlmId).stream().filter(version -> version.getId().equalsIgnoreCase(vlmVersion.getId())).findAny() + .ifPresent(version -> { + vlmVersion.setMinor(version.getMinor()); + vlmVersion.setMajor(version.getMajor()); + }); } private PackageInfo createPackageInfo(VspDetails vspDetails) { @@ -646,14 +581,10 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } @Override - public QuestionnaireResponse getVspQuestionnaire(String vspId, Version version) { VspQuestionnaireEntity retrieved = vspInfoDao.getQuestionnaire(vspId, version); - VersioningUtil - .validateEntityExistence(retrieved, new VspQuestionnaireEntity(vspId, version), VspDetails.ENTITY_TYPE); - + VersioningUtil.validateEntityExistence(retrieved, new VspQuestionnaireEntity(vspId, version), VspDetails.ENTITY_TYPE); String questionnaireData = retrieved.getQuestionnaireData(); - QuestionnaireResponse questionnaireResponse = new QuestionnaireResponse(); questionnaireResponse.setData(questionnaireData); questionnaireResponse.setSchema(getVspQuestionnaireSchema(null)); @@ -665,45 +596,34 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa vspInfoDao.updateQuestionnaireData(vspId, version, questionnaireData); } - - private Map> validateOrchestrationTemplate( - OrchestrationTemplateEntity orchestrationTemplate) throws IOException { - + private Map> validateOrchestrationTemplate(OrchestrationTemplateEntity orchestrationTemplate) throws IOException { if (isOrchestrationTemplateMissing(orchestrationTemplate)) { return null; } Map> validationErrors = new HashMap<>(); - - FileContentHandler fileContentMap = CommonUtil.validateAndUploadFileContent( - OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix()), + FileContentHandler fileContentMap = CommonUtil + .validateAndUploadFileContent(OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix()), orchestrationTemplate.getContentData().array()); - try (InputStream zipFileManifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { addDummyHeatBase(zipFileManifest, fileContentMap); } catch (Exception e) { LOGGER.error("Invalid package content", e); } - if (CommonUtil.isFileOriginFromZip(orchestrationTemplate.getFileSuffix())) { ValidationManager validationManager = ValidationManagerUtil.initValidationManager(fileContentMap); validationErrors.putAll(validationManager.validate()); } - - return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, validationErrors)) ? null - : validationErrors; + return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, validationErrors)) ? null : validationErrors; } private FileContentHandler addDummyHeatBase(InputStream zipFileManifest, FileContentHandler fileContentMap) { - ManifestContent manifestContent = - JsonUtil.json2Object(zipFileManifest, ManifestContent.class); + ManifestContent manifestContent = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); for (FileData fileData : manifestContent.getData()) { if ((fileData.getFile()).contains("dummy_ignore.yaml")) { String filePath = new File("").getAbsolutePath() + "/resources"; File envFilePath = new File(filePath + "/base_template.env"); File baseFilePath = new File(filePath + "/base_template.yaml"); - try ( - InputStream envStream = new FileInputStream(envFilePath); - InputStream baseStream = new FileInputStream(baseFilePath);) { + try (InputStream envStream = new FileInputStream(envFilePath); InputStream baseStream = new FileInputStream(baseFilePath);) { fileContentMap.addFile("base_template_dummy_ignore.env", envStream); fileContentMap.addFile("base_template_dummy_ignore.yaml", baseStream); } catch (Exception e) { @@ -713,44 +633,34 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } return fileContentMap; } - private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version, - String onboardingMethod) { + + private QuestionnaireValidationResult validateQuestionnaire(String vspId, Version version, String onboardingMethod) { // The apis of CompositionEntityDataManager used here are stateful! + // so, it must be re-created from scratch when it is used! - CompositionEntityDataManager compositionEntityDataManager = - CompositionEntityDataManagerFactory.getInstance().createInterface(); + CompositionEntityDataManager compositionEntityDataManager = CompositionEntityDataManagerFactory.getInstance().createInterface(); compositionEntityDataManager.addEntity(vspInfoDao.getQuestionnaire(vspId, version), null); - Collection nics = nicDao.listByVsp(vspId, version); - Map> nicNamesByComponent = new HashMap<>(); for (NicEntity nicEntity : nics) { compositionEntityDataManager.addEntity(nicEntity, null); - Nic nic = nicEntity.getNicCompositionData(); if (nic != null && nic.getName() != null) { - List nicNames = - nicNamesByComponent.computeIfAbsent(nicEntity.getComponentId(), k -> new ArrayList<>()); + List nicNames = nicNamesByComponent.computeIfAbsent(nicEntity.getComponentId(), k -> new ArrayList<>()); nicNames.add(nic.getName()); } } - Collection components = componentDao.listCompositionAndQuestionnaire(vspId, version); components.forEach(component -> compositionEntityDataManager.addEntity(component, - new ComponentQuestionnaireSchemaInput(nicNamesByComponent.get(component.getId()), - JsonUtil.json2Object(component.getQuestionnaireData(), Map.class), null, - OnboardingMethod.Manual.name().equals(onboardingMethod)))); - + new ComponentQuestionnaireSchemaInput(nicNamesByComponent.get(component.getId()), + JsonUtil.json2Object(component.getQuestionnaireData(), Map.class), null, OnboardingMethod.Manual.name().equals(onboardingMethod)))); Collection computes = computeDao.listByVsp(vspId, version); computes.forEach(compute -> compositionEntityDataManager.addEntity(compute, null)); - if (OnboardingMethod.Manual.name().equals(onboardingMethod)) { Collection images = imageDao.listByVsp(vspId, version); images.forEach(image -> compositionEntityDataManager.addEntity(image, null)); } - - Map> errorsByEntityId = - compositionEntityDataManager.validateEntitiesQuestionnaire(); + Map> errorsByEntityId = compositionEntityDataManager.validateEntitiesQuestionnaire(); if (MapUtils.isNotEmpty(errorsByEntityId)) { compositionEntityDataManager.buildTrees(); compositionEntityDataManager.addErrorsToTrees(errorsByEntityId); @@ -762,24 +672,18 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public File getInformationArtifact(String vspId, Version version) { VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - if (vspDetails == null) { return null; } - String vspName = vspDetails.getName(); ByteBuffer infoArtifactAsByteBuffer; File infoArtifactFile; try { - infoArtifactAsByteBuffer = - ByteBuffer.wrap(informationArtifactGenerator.generate(vspId, version).getBytes()); - - infoArtifactFile = - new File(String.format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName)); + infoArtifactAsByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate(vspId, version).getBytes()); + infoArtifactFile = new File(String.format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName)); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(infoArtifactFile))) { out.write(infoArtifactAsByteBuffer.array()); } - } catch (IOException ex) { throw new CoreException(new InformationArtifactCreationErrorBuilder(vspId).build(), ex); } @@ -792,25 +696,19 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa @Override public Optional> get(String vspId, Version version) throws IOException { - OrchestrationTemplateEntity orchestrationTemplateEntity = orchestrationTemplateDao.get(vspId, version); - if (isOrchestrationTemplateMissing(orchestrationTemplateEntity)) { return Optional.empty(); } - if (CommonUtil.isFileOriginFromZip(orchestrationTemplateEntity.getFileSuffix())) { return Optional.of(new ImmutablePair<>(OnboardingTypesEnum.ZIP.toString(), - candidateService.getZipData(orchestrationTemplateEntity.getContentData()))); + candidateService.getZipData(orchestrationTemplateEntity.getContentData()))); } - return Optional.of(new ImmutablePair<>(orchestrationTemplateEntity.getFileSuffix(), - orchestrationTemplateEntity.getContentData().array())); + return Optional.of(new ImmutablePair<>(orchestrationTemplateEntity.getFileSuffix(), orchestrationTemplateEntity.getContentData().array())); } void updateUniqueName(String oldVspName, String newVspName) { - uniqueValueUtil - .updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, oldVspName, - newVspName); + uniqueValueUtil.updateUniqueValue(VendorSoftwareProductConstants.UniqueValues.VENDOR_SOFTWARE_PRODUCT_NAME, oldVspName, newVspName); } @Override @@ -819,8 +717,8 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa } private boolean isOrchestrationTemplateMissing(OrchestrationTemplateEntity orchestrationTemplate) { - return orchestrationTemplate == null || orchestrationTemplate.getContentData() == null - || orchestrationTemplate.getFileSuffix() == null || orchestrationTemplate.getFileName() == null; + return orchestrationTemplate == null || orchestrationTemplate.getContentData() == null || orchestrationTemplate.getFileSuffix() == null + || orchestrationTemplate.getFileName() == null; } private boolean isServiceModelMissing(ToscaServiceModel serviceModel) { @@ -859,8 +757,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return this; } - public Builder orchestrationTemplateCandidateManager( - OrchestrationTemplateCandidateManager orchestrationTemplateCandidateManager) { + public Builder orchestrationTemplateCandidateManager(OrchestrationTemplateCandidateManager orchestrationTemplateCandidateManager) { this.orchestrationTemplateCandidateManager = orchestrationTemplateCandidateManager; return this; } @@ -880,8 +777,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return this; } - public Builder enrichedServiceModel( - EnrichedServiceModelDao enrichedServiceModelDao) { + public Builder enrichedServiceModel(EnrichedServiceModelDao enrichedServiceModelDao) { this.enrichedServiceModelDao = enrichedServiceModelDao; return this; } @@ -948,12 +844,10 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa private void registerToVersioning() { if (serviceModelDao != null) { - serviceModelDao - .registerVersioning(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); + serviceModelDao.registerVersioning(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); } if (enrichedServiceModelDao != null) { - enrichedServiceModelDao - .registerVersioning(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); + enrichedServiceModelDao.registerVersioning(VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE); } } @@ -961,8 +855,7 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa VendorSoftwareProductManagerImpl vendorSoftwareProductManager = new VendorSoftwareProductManagerImpl(); vendorSoftwareProductManager.vspMergeDao = this.vspMergeDao; vendorSoftwareProductManager.orchestrationTemplateDao = this.orchestrationTemplateDao; - vendorSoftwareProductManager.orchestrationTemplateCandidateManager = - this.orchestrationTemplateCandidateManager; + vendorSoftwareProductManager.orchestrationTemplateCandidateManager = this.orchestrationTemplateCandidateManager; vendorSoftwareProductManager.vspInfoDao = this.vspInfoDao; vendorSoftwareProductManager.vendorLicenseFacade = this.vendorLicenseFacade; vendorSoftwareProductManager.serviceModelDao = this.serviceModelDao; @@ -983,5 +876,4 @@ public class VendorSoftwareProductManagerImpl implements VendorSoftwareProductMa return vendorSoftwareProductManager; } } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VspManagerFactoryImpl.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VspManagerFactoryImpl.java index a504f35026..177bd79b30 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VspManagerFactoryImpl.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/VspManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl; import org.openecomp.core.dao.UniqueValueDaoFactory; @@ -38,30 +37,27 @@ import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.InformationArtifactGeneratorFactory; public class VspManagerFactoryImpl extends VspManagerFactory { - private static final VendorSoftwareProductManager INSTANCE = new VendorSoftwareProductManagerImpl.Builder() - .vspMerge(VspMergeDaoFactory.getInstance().createInterface()) - .orchestrationTemplate(OrchestrationTemplateDaoFactory.getInstance().createInterface()) - .orchestrationTemplateCandidateManager(OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()) - .vspInfo(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()) - .vendorLicenseFacade(VendorLicenseFacadeFactory.getInstance().createInterface()) - .serviceModel(ServiceModelDaoFactory.getInstance().createInterface()) - .enrichedServiceModel(EnrichedServiceModelDaoFactory.getInstance().createInterface()) - .licenseArtifactsService(VendorLicenseArtifactServiceFactory.getInstance().createInterface()) - .informationArtifactGenerator(InformationArtifactGeneratorFactory.getInstance().createInterface()) - .packageInfo(PackageInfoDaoFactory.getInstance().createInterface()) - .deploymentFlavor(DeploymentFlavorDaoFactory.getInstance().createInterface()) - .component(ComponentDaoFactory.getInstance().createInterface()) - .componentDependencyModel(ComponentDependencyModelDaoFactory.getInstance().createInterface()) - .nic(NicDaoFactory.getInstance().createInterface()) - .compute(ComputeDaoFactory.getInstance().createInterface()) - .image(ImageDaoFactory.getInstance().createInterface()) - .manualVspToscaManager(new ManualVspToscaManagerImpl()) - .uniqueValue(UniqueValueDaoFactory.getInstance().createInterface()) - .candidateService(CandidateServiceFactory.getInstance().createInterface()) - .build(); - @Override - public VendorSoftwareProductManager createInterface() { - return INSTANCE; - } + private static final VendorSoftwareProductManager INSTANCE = new VendorSoftwareProductManagerImpl.Builder() + .vspMerge(VspMergeDaoFactory.getInstance().createInterface()) + .orchestrationTemplate(OrchestrationTemplateDaoFactory.getInstance().createInterface()) + .orchestrationTemplateCandidateManager(OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface()) + .vspInfo(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()) + .vendorLicenseFacade(VendorLicenseFacadeFactory.getInstance().createInterface()) + .serviceModel(ServiceModelDaoFactory.getInstance().createInterface()) + .enrichedServiceModel(EnrichedServiceModelDaoFactory.getInstance().createInterface()) + .licenseArtifactsService(VendorLicenseArtifactServiceFactory.getInstance().createInterface()) + .informationArtifactGenerator(InformationArtifactGeneratorFactory.getInstance().createInterface()) + .packageInfo(PackageInfoDaoFactory.getInstance().createInterface()) + .deploymentFlavor(DeploymentFlavorDaoFactory.getInstance().createInterface()).component(ComponentDaoFactory.getInstance().createInterface()) + .componentDependencyModel(ComponentDependencyModelDaoFactory.getInstance().createInterface()) + .nic(NicDaoFactory.getInstance().createInterface()).compute(ComputeDaoFactory.getInstance().createInterface()) + .image(ImageDaoFactory.getInstance().createInterface()).manualVspToscaManager(new ManualVspToscaManagerImpl()) + .uniqueValue(UniqueValueDaoFactory.getInstance().createInterface()).candidateService(CandidateServiceFactory.getInstance().createInterface()) + .build(); + + @Override + public VendorSoftwareProductManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/ManifestAnalyzer.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/ManifestAnalyzer.java index ecb3ac62ed..e3a82e1602 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/ManifestAnalyzer.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/ManifestAnalyzer.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding; import java.util.ArrayList; @@ -29,11 +28,9 @@ import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; public class ManifestAnalyzer { - private final ManifestContent manifest; - private final static Set HEAT_TYPES = Collections.singleton(Type.HEAT); - private final static Set HELM_TYPES = Collections.singleton(Type.HELM); + private final ManifestContent manifest; public ManifestAnalyzer(ManifestContent manifest) { this.manifest = manifest; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageContentHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageContentHandler.java index c519802568..056d4e1a55 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageContentHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageContentHandler.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding; import java.util.HashMap; @@ -37,17 +36,12 @@ public class OnboardingPackageContentHandler extends FileContentHandler { public Map getFileAndSignaturePathMap(final Set signatureExtensionSet) { final Map files = getFiles(); final Map signedFilePairMap = new HashMap<>(); - files.keySet().stream() - .filter(filePath -> !signatureExtensionSet.contains(FilenameUtils.getExtension(filePath))) - .forEach(filePath -> { - final String filePathWithoutExtension = FilenameUtils.removeExtension(filePath); - signatureExtensionSet.stream() - .map(extension -> String.format("%s.%s", filePathWithoutExtension, extension)) - .filter(files::containsKey) - .forEach(file -> signedFilePairMap.put(filePath, file)); - signedFilePairMap.putIfAbsent(filePath, null); - }); + files.keySet().stream().filter(filePath -> !signatureExtensionSet.contains(FilenameUtils.getExtension(filePath))).forEach(filePath -> { + final String filePathWithoutExtension = FilenameUtils.removeExtension(filePath); + signatureExtensionSet.stream().map(extension -> String.format("%s.%s", filePathWithoutExtension, extension)).filter(files::containsKey) + .forEach(file -> signedFilePairMap.put(filePath, file)); + signedFilePairMap.putIfAbsent(filePath, null); + }); return signedFilePairMap; } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageProcessor.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageProcessor.java index e863f34696..640a15735f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageProcessor.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/OnboardingPackageProcessor.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding; import static org.openecomp.sdc.common.errors.Messages.COULD_NOT_READ_MANIFEST_FILE; @@ -69,13 +68,12 @@ public class OnboardingPackageProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingPackageProcessor.class); private static final String CSAR_EXTENSION = "csar"; private static final String ZIP_EXTENSION = "zip"; - private final String packageFileName; private final byte[] packageFileContent; - private FileContentHandler packageContent; private final Set errorMessages = new HashSet<>(); private final OnboardPackageInfo onboardPackageInfo; private final CnfPackageValidator cnfPackageValidator; + private FileContentHandler packageContent; public OnboardingPackageProcessor(final String packageFileName, final byte[] packageFileContent) { this.packageFileName = packageFileName; @@ -106,7 +104,6 @@ public class OnboardingPackageProcessor { if (hasNoErrors()) { final String packageName = FilenameUtils.getBaseName(packageFileName); final String packageExtension = FilenameUtils.getExtension(packageFileName); - if (hasSignedPackageStructure()) { packageInfo = processSignedPackage(packageName, packageExtension); } else { @@ -122,8 +119,7 @@ public class OnboardingPackageProcessor { private void validateFile() { if (!hasValidExtension()) { - String message = PACKAGE_INVALID_EXTENSION - .formatMessage(packageFileName, String.join(", ", CSAR_EXTENSION, ZIP_EXTENSION)); + String message = PACKAGE_INVALID_EXTENSION.formatMessage(packageFileName, String.join(", ", CSAR_EXTENSION, ZIP_EXTENSION)); reportError(ErrorLevel.ERROR, message); } else { try { @@ -141,8 +137,8 @@ public class OnboardingPackageProcessor { } private OnboardPackageInfo processCsarPackage(String packageName, String packageExtension) { - OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, - ByteBuffer.wrap(packageFileContent), new OnboardingPackageContentHandler(packageContent)); + OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), + new OnboardingPackageContentHandler(packageContent)); return new OnboardPackageInfo(onboardPackage, OnboardingTypesEnum.CSAR); } @@ -151,15 +147,14 @@ public class OnboardingPackageProcessor { if (manifest != null) { List errors = validateZipPackage(manifest); if (errors.isEmpty()) { - final OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, - ByteBuffer.wrap(packageFileContent), packageContent); + final OnboardPackage onboardPackage = new OnboardPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), + packageContent); return new OnboardPackageInfo(onboardPackage, OnboardingTypesEnum.ZIP); } else { errors.forEach(message -> reportError(ErrorLevel.ERROR, message)); } } else { - reportError(ErrorLevel.ERROR, - COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName)); + reportError(ErrorLevel.ERROR, COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName)); } return null; } @@ -184,7 +179,6 @@ public class OnboardingPackageProcessor { ManifestContent manifest = null; try (InputStream zipFileManifest = packageContent.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { manifest = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); - } catch (Exception e) { final String message = COULD_NOT_READ_MANIFEST_FILE.formatMessage(SdcCommon.MANIFEST_NAME, packageFileName); LOGGER.error(message, e); @@ -198,8 +192,7 @@ public class OnboardingPackageProcessor { try { boolean heatBase = false; for (FileData fileData : manifestContent.getData()) { - if (Objects.nonNull(fileData.getType()) && - fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { + if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { heatBase = true; fileData.setBase(false); FileData dummyHeat = new FileData(); @@ -217,8 +210,7 @@ public class OnboardingPackageProcessor { String filePath = new File("").getAbsolutePath() + "/resources"; File envFilePath = new File(filePath + "/base_template.env"); File baseFilePath = new File(filePath + "/base_template.yaml"); - try (InputStream envStream = new FileInputStream(envFilePath); - InputStream baseStream = new FileInputStream(baseFilePath)) { + try (InputStream envStream = new FileInputStream(envFilePath); InputStream baseStream = new FileInputStream(baseFilePath)) { packageContent.addFile("base_template_dummy_ignore.env", envStream); packageContent.addFile("base_template_dummy_ignore.yaml", baseStream); } catch (Exception e) { @@ -252,27 +244,23 @@ public class OnboardingPackageProcessor { } final String signatureFilePath = findSignatureFilePath().orElse(null); final String certificateFilePath = findCertificateFilePath().orElse(null); - final OnboardSignedPackage onboardSignedPackage = - new OnboardSignedPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), - packageContent, signatureFilePath, internalPackagePath, certificateFilePath); - + final OnboardSignedPackage onboardSignedPackage = new OnboardSignedPackage(packageName, packageExtension, ByteBuffer.wrap(packageFileContent), + packageContent, signatureFilePath, internalPackagePath, certificateFilePath); final String internalPackageName = FilenameUtils.getName(internalPackagePath); final String internalPackageBaseName = FilenameUtils.getBaseName(internalPackagePath); final String internalPackageExtension = FilenameUtils.getExtension(internalPackagePath); final byte[] internalPackageContent = packageContent.getFileContent(internalPackagePath); final OnboardPackage onboardPackage; try { - final OnboardingPackageContentHandler fileContentHandler = - new OnboardingPackageContentHandler(CommonUtil.getZipContent(internalPackageContent)); - onboardPackage = new OnboardPackage(internalPackageBaseName, internalPackageExtension, - internalPackageContent, fileContentHandler); + final OnboardingPackageContentHandler fileContentHandler = new OnboardingPackageContentHandler( + CommonUtil.getZipContent(internalPackageContent)); + onboardPackage = new OnboardPackage(internalPackageBaseName, internalPackageExtension, internalPackageContent, fileContentHandler); } catch (final ZipException e) { final String message = PACKAGE_PROCESS_INTERNAL_PACKAGE_ERROR.formatMessage(internalPackageName); LOGGER.error(message, e); reportError(ErrorLevel.ERROR, message); return null; } - return new OnboardPackageInfo(onboardSignedPackage, onboardPackage, OnboardingTypesEnum.SIGNED_CSAR); } @@ -281,13 +269,10 @@ public class OnboardingPackageProcessor { } private Optional findInternalPackagePath() { - return packageContent.getFileList().stream() - .filter(filePath -> { - final String extension = FilenameUtils.getExtension(filePath); - return CSAR_EXTENSION.equalsIgnoreCase(extension) || ZIP_EXTENSION.equalsIgnoreCase(extension); - } - ) - .findFirst(); + return packageContent.getFileList().stream().filter(filePath -> { + final String extension = FilenameUtils.getExtension(filePath); + return CSAR_EXTENSION.equalsIgnoreCase(extension) || ZIP_EXTENSION.equalsIgnoreCase(extension); + }).findFirst(); } private boolean isPackageEmpty() { @@ -295,60 +280,43 @@ public class OnboardingPackageProcessor { } private boolean hasSignedPackageStructure() { - if (MapUtils.isEmpty(packageContent.getFiles()) || !CollectionUtils.isEmpty( - packageContent.getFolderList())) { + if (MapUtils.isEmpty(packageContent.getFiles()) || !CollectionUtils.isEmpty(packageContent.getFolderList())) { return false; } final int numberOfFiles = packageContent.getFileList().size(); if (numberOfFiles == 2) { - return hasOneInternalPackageFile(packageContent) && - hasOneSignatureFile(packageContent); + return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent); } - if (numberOfFiles == 3) { - return hasOneInternalPackageFile(packageContent) && - hasOneSignatureFile(packageContent) && - hasOneCertificateFile(packageContent); + return hasOneInternalPackageFile(packageContent) && hasOneSignatureFile(packageContent) && hasOneCertificateFile(packageContent); } - return false; } private boolean hasOneInternalPackageFile(final FileContentHandler fileContentHandler) { - return fileContentHandler.getFileList().parallelStream() - .map(FilenameUtils::getExtension) - .map(String::toLowerCase) + return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(file -> file.endsWith(CSAR_EXTENSION)).count() == 1; } private boolean hasOneSignatureFile(final FileContentHandler fileContentHandler) { - return fileContentHandler.getFileList().parallelStream() - .map(FilenameUtils::getExtension) - .map(String::toLowerCase) + return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_SIGNATURE_EXTENSIONS::contains).count() == 1; } private boolean hasOneCertificateFile(final FileContentHandler fileContentHandler) { - return fileContentHandler.getFileList().parallelStream() - .map(FilenameUtils::getExtension) - .map(String::toLowerCase) + return fileContentHandler.getFileList().parallelStream().map(FilenameUtils::getExtension).map(String::toLowerCase) .filter(ALLOWED_CERTIFICATE_EXTENSIONS::contains).count() == 1; } private Optional findSignatureFilePath() { final Map files = packageContent.getFiles(); - return files.keySet().stream() - .filter( - fileName -> ALLOWED_SIGNATURE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) + return files.keySet().stream().filter(fileName -> ALLOWED_SIGNATURE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } private Optional findCertificateFilePath() { final Map files = packageContent.getFiles(); - return files.keySet().stream() - .filter( - fileName -> ALLOWED_CERTIFICATE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) + return files.keySet().stream().filter(fileName -> ALLOWED_CERTIFICATE_EXTENSIONS.contains(FilenameUtils.getExtension(fileName).toLowerCase())) .findFirst(); } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/validation/CnfPackageValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/validation/CnfPackageValidator.java index 8520672cd3..50f1fd8d06 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/validation/CnfPackageValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/onboarding/validation/CnfPackageValidator.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation; import static org.openecomp.sdc.common.errors.Messages.MANIFEST_VALIDATION_HELM_IS_BASE_MISSING; @@ -32,12 +31,10 @@ public class CnfPackageValidator { public List validateHelmPackage(List modules) { List messages = Collections.emptyList(); - if (modules != null && !modules.isEmpty()) { Stats stats = calculateStats(modules); messages = createErrorMessages(stats); } - return messages; } @@ -55,17 +52,14 @@ public class CnfPackageValidator { private List createErrorMessages(Stats stats) { List messages = new ArrayList<>(); - if (stats.without > 0) { messages.add(MANIFEST_VALIDATION_HELM_IS_BASE_MISSING.formatMessage(stats.without)); } - if (stats.base == 0) { messages.add(MANIFEST_VALIDATION_HELM_IS_BASE_NOT_SET.getErrorMessage()); } else if (stats.base > 1) { messages.add(MANIFEST_VALIDATION_HELM_IS_BASE_NOT_UNIQUE.getErrorMessage()); } - return messages; } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/BaseOrchestrationTemplateHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/BaseOrchestrationTemplateHandler.java index 68309106cd..6e810eefbd 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/BaseOrchestrationTemplateHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/BaseOrchestrationTemplateHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import java.io.ByteArrayInputStream; @@ -35,73 +34,60 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; public abstract class BaseOrchestrationTemplateHandler implements OrchestrationTemplateFileHandler { - protected static final Logger logger = LoggerFactory.getLogger(BaseOrchestrationTemplateHandler.class); - - @Override - public UploadFileResponse upload(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo, - final CandidateService candidateService) { - final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); - final UploadFileResponse uploadFileResponse = new UploadFileResponse(); - uploadFileResponse.setOnboardingType(getHandlerType()); - if (isFileToUploadEmpty(onboardPackage, uploadFileResponse, candidateService)) { - return uploadFileResponse; - } - - final byte[] fileContentByteArray = onboardPackage.getFileContent().array(); - if (isInvalidRawZipData(onboardPackage.getFileExtension(), - uploadFileResponse, fileContentByteArray, candidateService)) { - return uploadFileResponse; - } - - final UploadFileResponse validateResponse = validate(onboardPackageInfo); - if (!MapUtils.isEmpty(validateResponse.getErrors())) { - uploadFileResponse.addStructureErrors(validateResponse.getErrors()); - return uploadFileResponse; - } + protected static final Logger logger = LoggerFactory.getLogger(BaseOrchestrationTemplateHandler.class); - final UploadFileResponse responseFromUpdate = updateCandidateData(vspDetails, onboardPackageInfo, - candidateService); - if (!MapUtils.isEmpty(responseFromUpdate.getErrors())) { - uploadFileResponse.addStructureErrors(responseFromUpdate.getErrors()); + @Override + public UploadFileResponse upload(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo, + final CandidateService candidateService) { + final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); + final UploadFileResponse uploadFileResponse = new UploadFileResponse(); + uploadFileResponse.setOnboardingType(getHandlerType()); + if (isFileToUploadEmpty(onboardPackage, uploadFileResponse, candidateService)) { + return uploadFileResponse; + } + final byte[] fileContentByteArray = onboardPackage.getFileContent().array(); + if (isInvalidRawZipData(onboardPackage.getFileExtension(), uploadFileResponse, fileContentByteArray, candidateService)) { + return uploadFileResponse; + } + final UploadFileResponse validateResponse = validate(onboardPackageInfo); + if (!MapUtils.isEmpty(validateResponse.getErrors())) { + uploadFileResponse.addStructureErrors(validateResponse.getErrors()); + return uploadFileResponse; + } + final UploadFileResponse responseFromUpdate = updateCandidateData(vspDetails, onboardPackageInfo, candidateService); + if (!MapUtils.isEmpty(responseFromUpdate.getErrors())) { + uploadFileResponse.addStructureErrors(responseFromUpdate.getErrors()); + } + return uploadFileResponse; } - return uploadFileResponse; - } - - protected abstract UploadFileResponse updateCandidateData(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo, - final CandidateService candidateService); + protected abstract UploadFileResponse updateCandidateData(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo, + final CandidateService candidateService); - private boolean isFileToUploadEmpty(final OnboardPackage onboardPackage, - final UploadFileResponse uploadFileResponse, - final CandidateService candidateService) { - final ByteArrayInputStream fileToUpload = new ByteArrayInputStream( - onboardPackage.getFileContent().array()); - Optional errorMessage = - candidateService.validateNonEmptyFileToUpload(fileToUpload, onboardPackage.getFileExtension()); - if (errorMessage.isPresent()) { - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); - return true; + private boolean isFileToUploadEmpty(final OnboardPackage onboardPackage, final UploadFileResponse uploadFileResponse, + final CandidateService candidateService) { + final ByteArrayInputStream fileToUpload = new ByteArrayInputStream(onboardPackage.getFileContent().array()); + Optional errorMessage = candidateService.validateNonEmptyFileToUpload(fileToUpload, onboardPackage.getFileExtension()); + if (errorMessage.isPresent()) { + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); + return true; + } + return false; } - return false; - } - protected boolean isInvalidRawZipData(String fileSuffix, - UploadFileResponse uploadFileResponse, - byte[] uploadedFileData, - CandidateService candidateService) { - Optional errorMessage; - errorMessage = candidateService.validateRawZipData(fileSuffix, uploadedFileData); - if (errorMessage.isPresent()) { - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); - return true; + protected boolean isInvalidRawZipData(String fileSuffix, UploadFileResponse uploadFileResponse, byte[] uploadedFileData, + CandidateService candidateService) { + Optional errorMessage; + errorMessage = candidateService.validateRawZipData(fileSuffix, uploadedFileData); + if (errorMessage.isPresent()) { + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage.get()); + return true; + } + return false; } - return false; - } - public abstract UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo); + public abstract UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo); - protected abstract OnboardingTypesEnum getHandlerType(); + protected abstract OnboardingTypesEnum getHandlerType(); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java index 94638a5876..e7367c2a49 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateCSARHandler.java @@ -1,8 +1,8 @@ /* * Copyright (c) 2018 AT&T Intellectual Property. - * Modifications Copyright (c) 2018 Verizon Property. - * Modifications Copyright (c) 2019 Nordix Foundation. + * Modifications Copyright (c) 2018 Verizon Property. + * Modifications Copyright (c) 2019 Nordix Foundation. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; @@ -43,42 +42,35 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardSignedPackage; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; -public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler - implements OrchestrationTemplateFileHandler { +public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateHandler implements OrchestrationTemplateFileHandler { @Override public UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo) { final UploadFileResponse uploadFileResponse = new UploadFileResponse(); if (onboardPackageInfo.getPackageType() == OnboardingTypesEnum.SIGNED_CSAR) { - final OnboardSignedPackage originalOnboardPackage = - (OnboardSignedPackage) onboardPackageInfo.getOriginalOnboardPackage(); + final OnboardSignedPackage originalOnboardPackage = (OnboardSignedPackage) onboardPackageInfo.getOriginalOnboardPackage(); validatePackageSecurity(originalOnboardPackage).ifPresent(packageSignatureResponse -> { if (packageSignatureResponse.hasErrors()) { uploadFileResponse.addStructureErrors(packageSignatureResponse.getErrors()); } }); - if (uploadFileResponse.hasErrors()) { return uploadFileResponse; } } final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); final FileContentHandler fileContentHandler = onboardPackage.getFileContentHandler(); - try { final Validator validator = ValidatorFactory.getValidator(fileContentHandler); uploadFileResponse.addStructureErrors(validator.validateContent(fileContentHandler)); } catch (IOException exception) { logger.error(exception.getMessage(), exception); - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage())); + uploadFileResponse + .addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_CSAR_FILE.getErrorMessage())); } catch (CoreException coreException) { logger.error(coreException.getMessage(), coreException); - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); } - return uploadFileResponse; } @@ -87,8 +79,7 @@ public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateH try { final CsarSecurityValidator csarSecurityValidator = new CsarSecurityValidator(); if (!csarSecurityValidator.verifyPackageSignature(originalOnboardPackage)) { - final ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, - Messages.FAILED_TO_VERIFY_SIGNATURE.getErrorMessage()); + final ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_VERIFY_SIGNATURE.getErrorMessage()); logger.error(errorMessage.getMessage()); uploadFileResponseDto.addStructureError(SdcCommon.UPLOAD_FILE, errorMessage); return Optional.of(uploadFileResponseDto); @@ -103,31 +94,24 @@ public class OrchestrationTemplateCSARHandler extends BaseOrchestrationTemplateH } @Override - protected UploadFileResponse updateCandidateData(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo, + protected UploadFileResponse updateCandidateData(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo, final CandidateService candidateService) { final UploadFileResponse uploadFileResponse = new UploadFileResponse(); final OnboardPackage csarPackage = onboardPackageInfo.getOnboardPackage(); final OnboardPackage originalOnboardPackage = onboardPackageInfo.getOriginalOnboardPackage(); try { candidateService.updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(), - new OrchestrationTemplateCandidateData(csarPackage.getFileContent(), - "", csarPackage.getFileExtension(), - csarPackage.getFilename(), originalOnboardPackage.getFilename(), - originalOnboardPackage.getFileExtension(), - originalOnboardPackage.getFileContent())); + new OrchestrationTemplateCandidateData(csarPackage.getFileContent(), "", csarPackage.getFileExtension(), csarPackage.getFilename(), + originalOnboardPackage.getFilename(), originalOnboardPackage.getFileExtension(), originalOnboardPackage.getFileContent())); } catch (final Exception exception) { - logger.error(getErrorWithParameters(Messages.FILE_LOAD_CONTENT_ERROR.getErrorMessage(), - getHandlerType().toString()), exception); - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); + logger.error(getErrorWithParameters(Messages.FILE_LOAD_CONTENT_ERROR.getErrorMessage(), getHandlerType().toString()), exception); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); } return uploadFileResponse; } - @Override - protected OnboardingTypesEnum getHandlerType() { - return OnboardingTypesEnum.CSAR; - } - + @Override + protected OnboardingTypesEnum getHandlerType() { + return OnboardingTypesEnum.CSAR; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateFileHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateFileHandler.java index 2d2f1ae92b..9bd1b2ea22 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateFileHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateFileHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; @@ -24,7 +23,5 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; @FunctionalInterface public interface OrchestrationTemplateFileHandler { - UploadFileResponse upload(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo, - final CandidateService candidateService); + UploadFileResponse upload(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo, final CandidateService candidateService); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateZipHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateZipHandler.java index 3e54260e8b..65ce2f5397 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateZipHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationTemplateZipHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; @@ -35,44 +34,37 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackage; import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; -public class OrchestrationTemplateZipHandler extends BaseOrchestrationTemplateHandler - implements OrchestrationTemplateFileHandler { +public class OrchestrationTemplateZipHandler extends BaseOrchestrationTemplateHandler implements OrchestrationTemplateFileHandler { @Override public UploadFileResponse validate(final OnboardPackageInfo onboardPackageInfo) { final UploadFileResponse uploadFileResponse = new UploadFileResponse(); final OnboardPackage onboardPackage = onboardPackageInfo.getOnboardPackage(); - OrchestrationUtil - .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, onboardPackage.getFileContent().array()); + OrchestrationUtil.getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, onboardPackage.getFileContent().array()); return uploadFileResponse; } - @Override - protected UploadFileResponse updateCandidateData(final VspDetails vspDetails, - final OnboardPackageInfo onboardPackageInfo, - final CandidateService candidateService) { - final UploadFileResponse uploadFileResponse = new UploadFileResponse(); - try { - final OnboardPackage zipPackage = onboardPackageInfo.getOnboardPackage(); - final OrchestrationTemplateCandidateData candidateData = - new CandidateEntityBuilder(candidateService) - .buildCandidateEntityFromZip(vspDetails, zipPackage.getFileContent().array(), zipPackage.getFileContentHandler(), - uploadFileResponse.getErrors()); - candidateData.setFileName(zipPackage.getFilename()); - candidateData.setFileSuffix(zipPackage.getFileExtension()); - candidateService - .updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(), candidateData); - } catch (final Exception exception) { - logger.error(getErrorWithParameters(Messages.FILE_LOAD_CONTENT_ERROR.getErrorMessage(), - getHandlerType().toString()), exception); - uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); + @Override + protected UploadFileResponse updateCandidateData(final VspDetails vspDetails, final OnboardPackageInfo onboardPackageInfo, + final CandidateService candidateService) { + final UploadFileResponse uploadFileResponse = new UploadFileResponse(); + try { + final OnboardPackage zipPackage = onboardPackageInfo.getOnboardPackage(); + final OrchestrationTemplateCandidateData candidateData = new CandidateEntityBuilder(candidateService) + .buildCandidateEntityFromZip(vspDetails, zipPackage.getFileContent().array(), zipPackage.getFileContentHandler(), + uploadFileResponse.getErrors()); + candidateData.setFileName(zipPackage.getFilename()); + candidateData.setFileSuffix(zipPackage.getFileExtension()); + candidateService.updateCandidateUploadData(vspDetails.getId(), vspDetails.getVersion(), candidateData); + } catch (final Exception exception) { + logger.error(getErrorWithParameters(Messages.FILE_LOAD_CONTENT_ERROR.getErrorMessage(), getHandlerType().toString()), exception); + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())); + } + return uploadFileResponse; } - return uploadFileResponse; - } - @Override - protected OnboardingTypesEnum getHandlerType() { - return OnboardingTypesEnum.ZIP; - } + @Override + protected OnboardingTypesEnum getHandlerType() { + return OnboardingTypesEnum.ZIP; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java index 4b2decd412..9c881be75e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUploadFactory.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_CONFIG_NAMESPACE; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_IMPL_KEY; + +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; @@ -24,35 +29,24 @@ import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.OrchestrationTemplateFileExtensionErrorBuilder; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_CONFIG_NAMESPACE; -import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_IMPL_KEY; - public class OrchestrationUploadFactory { + private static final Map FILE_HANLDERS; - private OrchestrationUploadFactory() { - } static { Configuration config = ConfigurationManager.lookup(); - FILE_HANLDERS = new ConcurrentHashMap<>(config.populateMap(ORCHESTRATION_CONFIG_NAMESPACE, - ORCHESTRATION_IMPL_KEY, ImplementationConfiguration.class)); + FILE_HANLDERS = new ConcurrentHashMap<>( + config.populateMap(ORCHESTRATION_CONFIG_NAMESPACE, ORCHESTRATION_IMPL_KEY, ImplementationConfiguration.class)); + } + private OrchestrationUploadFactory() { } - public static OrchestrationTemplateFileHandler createOrchestrationTemplateFileHandler( - final OnboardingTypesEnum onboardingType) { + public static OrchestrationTemplateFileHandler createOrchestrationTemplateFileHandler(final OnboardingTypesEnum onboardingType) { final ImplementationConfiguration orchestrationTemplateFileHandler = FILE_HANLDERS.get(onboardingType.toString()); - - if(Objects.isNull(orchestrationTemplateFileHandler)){ - throw new CoreException(new OrchestrationTemplateFileExtensionErrorBuilder - ().build()); + if (Objects.isNull(orchestrationTemplateFileHandler)) { + throw new CoreException(new OrchestrationTemplateFileExtensionErrorBuilder().build()); } - - return CommonMethods.newInstance(orchestrationTemplateFileHandler.getImplementationClass(), - OrchestrationTemplateFileHandler.class); + return CommonMethods.newInstance(orchestrationTemplateFileHandler.getImplementationClass(), OrchestrationTemplateFileHandler.class); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUtil.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUtil.java index ef41262621..bc84e89e74 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUtil.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/OrchestrationUtil.java @@ -13,9 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration; +import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.dao.UniqueValueDaoFactory; @@ -41,366 +53,290 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManager; import org.openecomp.sdc.vendorsoftwareproduct.CompositionEntityDataManagerFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.*; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.MonitoringUploadDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants.UniqueValues.PROCESS_NAME; - public class OrchestrationUtil { - private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationUtil.class); - public static final String ORCHESTRATION_CONFIG_NAMESPACE = "orchestration"; - public static final String ORCHESTRATION_IMPL_KEY = "orchestration_impl"; - - private final NicDao nicDao; - private final ComponentArtifactDao componentArtifactDao; - private final ProcessDao processDao; - private final OrchestrationTemplateDao orchestrationTemplateDataDao; - private final ComponentDao componentDao; - private final ServiceModelDao serviceModelDao; - private final ComponentDependencyModelDao componentDependencyModelDao; - private final CompositionEntityDataManager compositionEntityDataManager; - private final CompositionDataExtractor compositionDataExtractor; - - public OrchestrationUtil() { - this(NicDaoFactory.getInstance().createInterface(), - MonitoringUploadDaoFactory.getInstance().createInterface(), - ProcessDaoFactory.getInstance().createInterface(), - OrchestrationTemplateDaoFactory.getInstance().createInterface(), - ComponentDaoFactory.getInstance().createInterface(), - ServiceModelDaoFactory.getInstance().createInterface(), - ComponentDependencyModelDaoFactory.getInstance().createInterface(), - CompositionEntityDataManagerFactory.getInstance().createInterface(), + public static final String ORCHESTRATION_CONFIG_NAMESPACE = "orchestration"; + public static final String ORCHESTRATION_IMPL_KEY = "orchestration_impl"; + private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationUtil.class); + private final NicDao nicDao; + private final ComponentArtifactDao componentArtifactDao; + private final ProcessDao processDao; + private final OrchestrationTemplateDao orchestrationTemplateDataDao; + private final ComponentDao componentDao; + private final ServiceModelDao serviceModelDao; + private final ComponentDependencyModelDao componentDependencyModelDao; + private final CompositionEntityDataManager compositionEntityDataManager; + private final CompositionDataExtractor compositionDataExtractor; + + public OrchestrationUtil() { + this(NicDaoFactory.getInstance().createInterface(), MonitoringUploadDaoFactory.getInstance().createInterface(), + ProcessDaoFactory.getInstance().createInterface(), OrchestrationTemplateDaoFactory.getInstance().createInterface(), + ComponentDaoFactory.getInstance().createInterface(), ServiceModelDaoFactory.getInstance().createInterface(), + ComponentDependencyModelDaoFactory.getInstance().createInterface(), CompositionEntityDataManagerFactory.getInstance().createInterface(), CompositionDataExtractorFactory.getInstance().createInterface()); - } - - private OrchestrationUtil( - NicDao nicDao, - ComponentArtifactDao componentArtifactDao, - ProcessDao processDao, - OrchestrationTemplateDao orchestrationTemplateDataDao, - ComponentDao componentDao, - ServiceModelDao serviceModelDao, - ComponentDependencyModelDao componentDependencyModelDao, - CompositionEntityDataManager compositionEntityDataManager, - CompositionDataExtractor compositionDataExtractor) { - this.nicDao = nicDao; - this.componentArtifactDao = componentArtifactDao; - this.processDao = processDao; - this.orchestrationTemplateDataDao = orchestrationTemplateDataDao; - this.componentDao = componentDao; - this.serviceModelDao = serviceModelDao; - this.componentDependencyModelDao = componentDependencyModelDao; - this.compositionEntityDataManager = compositionEntityDataManager; - this.compositionDataExtractor = compositionDataExtractor; - } - - public static Optional getFileContentMap(OnboardingTypesEnum type, - UploadFileResponse uploadFileResponse, - byte[] uploadedFileData) { - FileContentHandler contentMap = null; - try { - contentMap = CommonUtil.validateAndUploadFileContent(type, uploadedFileData); - } catch (IOException exception) { - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage())); - LOGGER.error("{}\n{}", Messages.INVALID_ZIP_FILE.getErrorMessage(), - exception.getMessage(), exception); - } catch (CoreException coreException) { - uploadFileResponse.addStructureError( - SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); - LOGGER.error(coreException.getMessage(), coreException); } - return Optional.ofNullable(contentMap); - } - - public void backupComponentsQuestionnaireBeforeDelete(String vspId, Version version, - Map componentsQustanniare, - Map> - componentNicsQustanniare, - Map> - componentMibList, - Map> - componentProcesses, - Map processArtifact) { - Collection componentsCompositionAndQuestionnaire = - componentDao.listCompositionAndQuestionnaire(vspId, version); - componentsCompositionAndQuestionnaire.forEach(componentEntity -> { - String componentName = componentEntity.getComponentCompositionData().getName(); - componentsQustanniare.put(componentName, componentEntity.getQuestionnaireData()); - backupMibData(vspId, version, componentEntity, componentName, componentMibList); - backupProcess(vspId, version, componentEntity.getId(), componentName, componentProcesses, - processArtifact); - backupNicsQuestionnaire(vspId, version, componentEntity, componentName, - componentNicsQustanniare); - }); - } - - private void backupMibData(String vspId, Version version, ComponentEntity componentEntity, - String componentName, - Map> componentMibList) { - Collection componentMib = - componentArtifactDao.listArtifacts(new - ComponentMonitoringUploadEntity(vspId, version, componentEntity.getId(), - null)); - if (CollectionUtils.isNotEmpty(componentMib)) { - componentMibList.put(componentName, componentMib); + private OrchestrationUtil(NicDao nicDao, ComponentArtifactDao componentArtifactDao, ProcessDao processDao, + OrchestrationTemplateDao orchestrationTemplateDataDao, ComponentDao componentDao, ServiceModelDao serviceModelDao, + ComponentDependencyModelDao componentDependencyModelDao, CompositionEntityDataManager compositionEntityDataManager, + CompositionDataExtractor compositionDataExtractor) { + this.nicDao = nicDao; + this.componentArtifactDao = componentArtifactDao; + this.processDao = processDao; + this.orchestrationTemplateDataDao = orchestrationTemplateDataDao; + this.componentDao = componentDao; + this.serviceModelDao = serviceModelDao; + this.componentDependencyModelDao = componentDependencyModelDao; + this.compositionEntityDataManager = compositionEntityDataManager; + this.compositionDataExtractor = compositionDataExtractor; } - } - private void backupProcess(String vspId, Version version, String componentId, - String componentName, Map> processes, - Map processArtifact) { - Collection processList = - processDao.list(new ProcessEntity(vspId, version, componentId, null)); - if (!processList.isEmpty()) { - processes.put(componentName, processList); - processList.forEach(process -> { - ProcessEntity artifact = processDao - .getArtifact(new ProcessEntity(vspId, version, componentId, process.getId())); - if (artifact.getArtifact() != null) { - processArtifact.put(process.getId(), artifact); + public static Optional getFileContentMap(OnboardingTypesEnum type, UploadFileResponse uploadFileResponse, + byte[] uploadedFileData) { + FileContentHandler contentMap = null; + try { + contentMap = CommonUtil.validateAndUploadFileContent(type, uploadedFileData); + } catch (IOException exception) { + uploadFileResponse + .addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage())); + LOGGER.error("{}\n{}", Messages.INVALID_ZIP_FILE.getErrorMessage(), exception.getMessage(), exception); + } catch (CoreException coreException) { + uploadFileResponse.addStructureError(SdcCommon.UPLOAD_FILE, new ErrorMessage(ErrorLevel.ERROR, coreException.getMessage())); + LOGGER.error(coreException.getMessage(), coreException); } - }); + return Optional.ofNullable(contentMap); } - } - private void backupNicsQuestionnaire(String vspId, Version version, - ComponentEntity componentEntity, - String componentName, - Map> componentNicsQustanniare) { - Collection - nics = nicDao.list(new NicEntity(vspId, version, componentEntity.getId(), null)); - if (CollectionUtils.isNotEmpty(nics)) { - Map nicsQuestionnaire = new HashMap<>(); - nics.forEach(nicEntity -> { - NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, version, - componentEntity.getId(), nicEntity.getId()); + public static HeatStructureTree createHeatTree(FileContentHandler fileContentMap, Map> validationErrors) { + HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileContentMap); + heatTreeManager.createTree(); + heatTreeManager.addErrors(validationErrors); + return heatTreeManager.getTree(); + } - nicsQuestionnaire.put(nicEntity.getNicCompositionData().getName(), - nicQuestionnaire.getQuestionnaireData()); - }); - componentNicsQustanniare.put(componentName, nicsQuestionnaire); + public void backupComponentsQuestionnaireBeforeDelete(String vspId, Version version, Map componentsQustanniare, + Map> componentNicsQustanniare, + Map> componentMibList, + Map> componentProcesses, + Map processArtifact) { + Collection componentsCompositionAndQuestionnaire = componentDao.listCompositionAndQuestionnaire(vspId, version); + componentsCompositionAndQuestionnaire.forEach(componentEntity -> { + String componentName = componentEntity.getComponentCompositionData().getName(); + componentsQustanniare.put(componentName, componentEntity.getQuestionnaireData()); + backupMibData(vspId, version, componentEntity, componentName, componentMibList); + backupProcess(vspId, version, componentEntity.getId(), componentName, componentProcesses, processArtifact); + backupNicsQuestionnaire(vspId, version, componentEntity, componentName, componentNicsQustanniare); + }); } - } - public void retainComponentQuestionnaireData(String vspId, Version version, - Map componentsQustanniare, - Map> - componentNicsQustanniare, - Map> componentMibList, - Map> processes, - Map processArtifact) { - //VSP processes - restoreProcess(vspId, version, null, null, processes, processArtifact); - Collection components = - componentDao.list(new ComponentEntity(vspId, version, null)); - components.forEach(componentEntity -> { - String componentName = componentEntity.getComponentCompositionData().getName(); - if (componentsQustanniare.containsKey(componentName)) { - componentDao.updateQuestionnaireData(vspId, version, - componentEntity.getId(), - componentsQustanniare.get(componentEntity.getComponentCompositionData() - .getName())); - if (componentNicsQustanniare.containsKey(componentName)) { - restoreComponentNicQuestionnaire(vspId, version, componentName, componentEntity, - componentNicsQustanniare); + private void backupMibData(String vspId, Version version, ComponentEntity componentEntity, String componentName, + Map> componentMibList) { + Collection componentMib = componentArtifactDao + .listArtifacts(new ComponentMonitoringUploadEntity(vspId, version, componentEntity.getId(), null)); + if (CollectionUtils.isNotEmpty(componentMib)) { + componentMibList.put(componentName, componentMib); } - //MIB //todo add for VES_EVENTS - if (componentMibList.containsKey(componentName)) { - restoreComponentMibData(componentName, componentEntity, componentMibList); - } - //VFC processes - restoreProcess(vspId, version, componentEntity.getId(), componentName, processes, - processArtifact); - } - }); - } - - private void restoreComponentNicQuestionnaire(String vspId, Version version, - String componentName, - ComponentEntity componentEntity, - Map> componentNicsQustanniare) { - Map nicsQustanniare = componentNicsQustanniare.get(componentName); - Collection nics = - nicDao.list(new NicEntity(vspId, version, componentEntity.getId(), null)); - nics.forEach(nicEntity -> { - if (nicsQustanniare.containsKey(nicEntity.getNicCompositionData().getName())) { - nicDao.updateQuestionnaireData(vspId, version, - componentEntity.getId(), nicEntity.getId(), - nicsQustanniare.get(nicEntity.getNicCompositionData().getName())); - } - }); - } - - private void restoreComponentMibData(String componentName, ComponentEntity componentEntity, - Map> componentMibList) { - Collection mibList = componentMibList.get(componentName); - mibList.forEach(mib -> { - mib.setComponentId(componentEntity.getId()); - componentArtifactDao.create(mib); - }); - } + } - private void restoreProcess(String vspId, Version version, String componentId, - String componentName, - Map> processes, - Map processArtifact) { - if (processes.containsKey(componentName)) { - Collection processList = processes.get(componentName); - processList.forEach(process -> { - process.setComponentId(componentId); - UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance() - .createInterface()); - uniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, version.getId(), componentId, - process.getName()); - processDao.create(process); - if (processArtifact.containsKey(process.getId())) { - ProcessEntity artifact = processArtifact.get(process.getId()); - processDao.uploadArtifact(artifact); + private void backupProcess(String vspId, Version version, String componentId, String componentName, + Map> processes, Map processArtifact) { + Collection processList = processDao.list(new ProcessEntity(vspId, version, componentId, null)); + if (!processList.isEmpty()) { + processes.put(componentName, processList); + processList.forEach(process -> { + ProcessEntity artifact = processDao.getArtifact(new ProcessEntity(vspId, version, componentId, process.getId())); + if (artifact.getArtifact() != null) { + processArtifact.put(process.getId(), artifact); + } + }); } - }); } - } - public void deleteUploadDataAndContent(String vspId, Version version) { - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface() - .delete(new VspDetails(vspId, version)); - } + private void backupNicsQuestionnaire(String vspId, Version version, ComponentEntity componentEntity, String componentName, + Map> componentNicsQustanniare) { + Collection nics = nicDao.list(new NicEntity(vspId, version, componentEntity.getId(), null)); + if (CollectionUtils.isNotEmpty(nics)) { + Map nicsQuestionnaire = new HashMap<>(); + nics.forEach(nicEntity -> { + NicEntity nicQuestionnaire = nicDao.getQuestionnaireData(vspId, version, componentEntity.getId(), nicEntity.getId()); + nicsQuestionnaire.put(nicEntity.getNicCompositionData().getName(), nicQuestionnaire.getQuestionnaireData()); + }); + componentNicsQustanniare.put(componentName, nicsQuestionnaire); + } + } - public void saveUploadData(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData, - InputStream uploadedFileData, - FileContentHandler fileContentMap, HeatStructureTree tree) { - Map manifestAsMap = - fileContentMap.containsFile(SdcCommon.MANIFEST_NAME) - ? (Map) JsonUtil.json2Object(fileContentMap.getFileContentAsStream( - SdcCommon.MANIFEST_NAME), Map.class) - : new HashMap<>(); + public void retainComponentQuestionnaireData(String vspId, Version version, Map componentsQustanniare, + Map> componentNicsQustanniare, + Map> componentMibList, + Map> processes, Map processArtifact) { + //VSP processes + restoreProcess(vspId, version, null, null, processes, processArtifact); + Collection components = componentDao.list(new ComponentEntity(vspId, version, null)); + components.forEach(componentEntity -> { + String componentName = componentEntity.getComponentCompositionData().getName(); + if (componentsQustanniare.containsKey(componentName)) { + componentDao.updateQuestionnaireData(vspId, version, componentEntity.getId(), + componentsQustanniare.get(componentEntity.getComponentCompositionData().getName())); + if (componentNicsQustanniare.containsKey(componentName)) { + restoreComponentNicQuestionnaire(vspId, version, componentName, componentEntity, componentNicsQustanniare); + } + //MIB //todo add for VES_EVENTS + if (componentMibList.containsKey(componentName)) { + restoreComponentMibData(componentName, componentEntity, componentMibList); + } + //VFC processes + restoreProcess(vspId, version, componentEntity.getId(), componentName, processes, processArtifact); + } + }); + } - OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(); - uploadData.setFileSuffix(candidateData.getFileSuffix()); - uploadData.setFileName(candidateData.getFileName()); - uploadData.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(uploadedFileData))); - uploadData.setValidationDataStructure(new ValidationStructureList(tree)); - uploadData.setPackageName(Objects.isNull(manifestAsMap.get("name")) ? null : - (String) manifestAsMap.get("name")); - uploadData.setPackageVersion(Objects.isNull(manifestAsMap.get("version")) ? null : - (String) manifestAsMap.get("version")); - uploadData.setFilesDataStructure(candidateData.getFilesDataStructure()); - orchestrationTemplateDataDao.update(vspDetails.getId(), vspDetails.getVersion(), uploadData); + private void restoreComponentNicQuestionnaire(String vspId, Version version, String componentName, ComponentEntity componentEntity, + Map> componentNicsQustanniare) { + Map nicsQustanniare = componentNicsQustanniare.get(componentName); + Collection nics = nicDao.list(new NicEntity(vspId, version, componentEntity.getId(), null)); + nics.forEach(nicEntity -> { + if (nicsQustanniare.containsKey(nicEntity.getNicCompositionData().getName())) { + nicDao.updateQuestionnaireData(vspId, version, componentEntity.getId(), nicEntity.getId(), + nicsQustanniare.get(nicEntity.getNicCompositionData().getName())); + } + }); + } - VspMergeDaoFactory.getInstance().createInterface() - .updateHint(vspDetails.getId(), vspDetails.getVersion()); - } + private void restoreComponentMibData(String componentName, ComponentEntity componentEntity, + Map> componentMibList) { + Collection mibList = componentMibList.get(componentName); + mibList.forEach(mib -> { + mib.setComponentId(componentEntity.getId()); + componentArtifactDao.create(mib); + }); + } - public void saveServiceModel(String vspId, Version version, - ToscaServiceModel serviceModelToExtract, - ToscaServiceModel serviceModelToStore) { - if (serviceModelToExtract != null) { - serviceModelDao.storeServiceModel(vspId, version, serviceModelToStore); - //Extracting the compostion data from the output service model of the first phase of - // translation - compositionEntityDataManager.saveCompositionData(vspId, version, - compositionDataExtractor.extractServiceCompositionData(serviceModelToExtract)); + private void restoreProcess(String vspId, Version version, String componentId, String componentName, + Map> processes, Map processArtifact) { + if (processes.containsKey(componentName)) { + Collection processList = processes.get(componentName); + processList.forEach(process -> { + process.setComponentId(componentId); + UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + uniqueValueUtil.createUniqueValue(PROCESS_NAME, vspId, version.getId(), componentId, process.getName()); + processDao.create(process); + if (processArtifact.containsKey(process.getId())) { + ProcessEntity artifact = processArtifact.get(process.getId()); + processDao.uploadArtifact(artifact); + } + }); + } } - } - public static HeatStructureTree createHeatTree(FileContentHandler fileContentMap, - Map> validationErrors) { - HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileContentMap); - heatTreeManager.createTree(); - heatTreeManager.addErrors(validationErrors); - return heatTreeManager.getTree(); - } + public void deleteUploadDataAndContent(String vspId, Version version) { + VendorSoftwareProductInfoDaoFactory.getInstance().createInterface().delete(new VspDetails(vspId, version)); + } - public void updateVspComponentDependencies(String vspId, Version version, - Map - vspComponentIdNameInfoBeforeProcess, - Collection - componentDependenciesBeforeDelete) { - Map updatedVspComponentNameIdInfo = getVspComponentNameIdInfo(vspId, version); - if (MapUtils.isNotEmpty(updatedVspComponentNameIdInfo)) { - Set updatedVspComponentNames = updatedVspComponentNameIdInfo.keySet(); - if (CollectionUtils.isNotEmpty(componentDependenciesBeforeDelete)) { - restoreComponentDependencies(vspId, version, vspComponentIdNameInfoBeforeProcess, - componentDependenciesBeforeDelete, updatedVspComponentNames, - updatedVspComponentNameIdInfo); - } + public void saveUploadData(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData, InputStream uploadedFileData, + FileContentHandler fileContentMap, HeatStructureTree tree) { + Map manifestAsMap = fileContentMap.containsFile(SdcCommon.MANIFEST_NAME) ? (Map) JsonUtil + .json2Object(fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME), Map.class) : new HashMap<>(); + OrchestrationTemplateEntity uploadData = new OrchestrationTemplateEntity(); + uploadData.setFileSuffix(candidateData.getFileSuffix()); + uploadData.setFileName(candidateData.getFileName()); + uploadData.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(uploadedFileData))); + uploadData.setValidationDataStructure(new ValidationStructureList(tree)); + uploadData.setPackageName(Objects.isNull(manifestAsMap.get("name")) ? null : (String) manifestAsMap.get("name")); + uploadData.setPackageVersion(Objects.isNull(manifestAsMap.get("version")) ? null : (String) manifestAsMap.get("version")); + uploadData.setFilesDataStructure(candidateData.getFilesDataStructure()); + orchestrationTemplateDataDao.update(vspDetails.getId(), vspDetails.getVersion(), uploadData); + VspMergeDaoFactory.getInstance().createInterface().updateHint(vspDetails.getId(), vspDetails.getVersion()); } - } - private void restoreComponentDependencies(String vspId, Version version, - Map vspComponentIdNameInfoBeforeProcess, - Collection - componentDependenciesBeforeDelete, - Set updatedVspComponentNames, - Map updatedVspComponentNameIdInfo) { - for (ComponentDependencyModelEntity componentDependency : componentDependenciesBeforeDelete) { - String sourceComponentName = vspComponentIdNameInfoBeforeProcess.get(componentDependency - .getSourceComponentId()); - String targetComponentName = vspComponentIdNameInfoBeforeProcess.get(componentDependency - .getTargetComponentId()); - if (updatedVspComponentNames.contains(sourceComponentName) - && (updatedVspComponentNames.contains(targetComponentName))) { - ComponentDependencyModelEntity restoredDependency = - new ComponentDependencyModelEntity(vspId, version, null); - String newSourceComponentId = updatedVspComponentNameIdInfo.get(sourceComponentName); - restoredDependency.setSourceComponentId(newSourceComponentId); - String newTargetComponentId = updatedVspComponentNameIdInfo.get(targetComponentName); - restoredDependency.setTargetComponentId(newTargetComponentId); - restoredDependency.setRelation(componentDependency.getRelation()); - componentDependencyModelDao.create(restoredDependency); - } + public void saveServiceModel(String vspId, Version version, ToscaServiceModel serviceModelToExtract, ToscaServiceModel serviceModelToStore) { + if (serviceModelToExtract != null) { + serviceModelDao.storeServiceModel(vspId, version, serviceModelToStore); + //Extracting the compostion data from the output service model of the first phase of + + // translation + compositionEntityDataManager + .saveCompositionData(vspId, version, compositionDataExtractor.extractServiceCompositionData(serviceModelToExtract)); + } } - } - public Map getVspComponentIdNameInfo(String vspId, Version version) { - Collection updatedVspComponents = - componentDao.list(new ComponentEntity(vspId, version, null)); - Map vspComponentIdNameMap = new HashMap<>(); - if (CollectionUtils.isNotEmpty(updatedVspComponents)) { - vspComponentIdNameMap = updatedVspComponents.stream() - .filter(componentEntity -> componentEntity.getComponentCompositionData() != null) - .collect(Collectors.toMap(ComponentEntity::getId, - componentEntity -> componentEntity.getComponentCompositionData().getName())); + public void updateVspComponentDependencies(String vspId, Version version, Map vspComponentIdNameInfoBeforeProcess, + Collection componentDependenciesBeforeDelete) { + Map updatedVspComponentNameIdInfo = getVspComponentNameIdInfo(vspId, version); + if (MapUtils.isNotEmpty(updatedVspComponentNameIdInfo)) { + Set updatedVspComponentNames = updatedVspComponentNameIdInfo.keySet(); + if (CollectionUtils.isNotEmpty(componentDependenciesBeforeDelete)) { + restoreComponentDependencies(vspId, version, vspComponentIdNameInfoBeforeProcess, componentDependenciesBeforeDelete, + updatedVspComponentNames, updatedVspComponentNameIdInfo); + } + } + } + private void restoreComponentDependencies(String vspId, Version version, Map vspComponentIdNameInfoBeforeProcess, + Collection componentDependenciesBeforeDelete, + Set updatedVspComponentNames, Map updatedVspComponentNameIdInfo) { + for (ComponentDependencyModelEntity componentDependency : componentDependenciesBeforeDelete) { + String sourceComponentName = vspComponentIdNameInfoBeforeProcess.get(componentDependency.getSourceComponentId()); + String targetComponentName = vspComponentIdNameInfoBeforeProcess.get(componentDependency.getTargetComponentId()); + if (updatedVspComponentNames.contains(sourceComponentName) && (updatedVspComponentNames.contains(targetComponentName))) { + ComponentDependencyModelEntity restoredDependency = new ComponentDependencyModelEntity(vspId, version, null); + String newSourceComponentId = updatedVspComponentNameIdInfo.get(sourceComponentName); + restoredDependency.setSourceComponentId(newSourceComponentId); + String newTargetComponentId = updatedVspComponentNameIdInfo.get(targetComponentName); + restoredDependency.setTargetComponentId(newTargetComponentId); + restoredDependency.setRelation(componentDependency.getRelation()); + componentDependencyModelDao.create(restoredDependency); + } + } } - return vspComponentIdNameMap; - } - public Collection getComponentDependenciesBeforeDelete(String - vspId, Version version) { - return componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, - version, null)); - } + public Map getVspComponentIdNameInfo(String vspId, Version version) { + Collection updatedVspComponents = componentDao.list(new ComponentEntity(vspId, version, null)); + Map vspComponentIdNameMap = new HashMap<>(); + if (CollectionUtils.isNotEmpty(updatedVspComponents)) { + vspComponentIdNameMap = updatedVspComponents.stream().filter(componentEntity -> componentEntity.getComponentCompositionData() != null) + .collect(Collectors.toMap(ComponentEntity::getId, componentEntity -> componentEntity.getComponentCompositionData().getName())); + } + return vspComponentIdNameMap; + } - private Map getVspComponentNameIdInfo(String vspId, - Version version) { - Collection updatedVspComponents = - componentDao.list(new ComponentEntity(vspId, version, null)); - Map vspComponentNameIdMap = new HashMap<>(); - if (CollectionUtils.isNotEmpty(updatedVspComponents)) { - vspComponentNameIdMap = updatedVspComponents.stream() - .filter(componentEntity -> componentEntity.getComponentCompositionData() != null) - .collect(Collectors - .toMap(componentEntity -> componentEntity.getComponentCompositionData().getName(), - ComponentEntity::getId)); + public Collection getComponentDependenciesBeforeDelete(String vspId, Version version) { + return componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null)); } - return vspComponentNameIdMap; - } + private Map getVspComponentNameIdInfo(String vspId, Version version) { + Collection updatedVspComponents = componentDao.list(new ComponentEntity(vspId, version, null)); + Map vspComponentNameIdMap = new HashMap<>(); + if (CollectionUtils.isNotEmpty(updatedVspComponents)) { + vspComponentNameIdMap = updatedVspComponents.stream().filter(componentEntity -> componentEntity.getComponentCompositionData() != null) + .collect(Collectors.toMap(componentEntity -> componentEntity.getComponentCompositionData().getName(), ComponentEntity::getId)); + } + return vspComponentNameIdMap; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/CsarSecurityValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/CsarSecurityValidator.java index 0efe65b3b6..81a17f333b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/CsarSecurityValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/CsarSecurityValidator.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; import java.util.Optional; @@ -55,7 +54,6 @@ public class CsarSecurityValidator { if (certificateFilePath.isPresent()) { certificateBytes = fileContentHandler.getFileContent(certificateFilePath.get()); } - return securityManager.verifySignedData(signatureBytes, certificateBytes, archiveBytes); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ManifestBuilder.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ManifestBuilder.java index eff1fb31cd..ee708b4176 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ManifestBuilder.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ManifestBuilder.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.ALGORITHM; @@ -36,19 +35,18 @@ import java.util.TreeMap; */ public class ManifestBuilder { + private static final String PROPERTY_FORMAT = "%s: %s%n"; + private static final String SECTION_FORMAT = "%s:%n"; private final Map> sourceWithPropertiesMap = new TreeMap<>(); private final Map> nonManoArtifactMap = new TreeMap<>(); private final Map metadataMap = new TreeMap<>(); - private static final String PROPERTY_FORMAT = "%s: %s%n"; - private static final String SECTION_FORMAT = "%s:%n"; /** * Adds a metadata property. * - * @param metadataProperty the property name - * @param value the property value - * @return - * a reference to this object. + * @param metadataProperty the property name + * @param value the property value + * @return a reference to this object. */ public ManifestBuilder withMetaData(final String metadataProperty, final String value) { metadataMap.put(metadataProperty, value); @@ -58,9 +56,8 @@ public class ManifestBuilder { /** * Adds a manifest source path. * - * @param sourcePath The source path - * @return - * a reference to this object. + * @param sourcePath The source path + * @return a reference to this object. */ public ManifestBuilder withSource(final String sourcePath) { sourceWithPropertiesMap.put(sourcePath, null); @@ -71,10 +68,9 @@ public class ManifestBuilder { * Adds a manifest source path with the source sign. * * @param sourcePath The source path - * @param hashAlgorithm The hash algorithm + * @param hashAlgorithm The hash algorithm * @param hash The hash representing the sign - * @return - * a reference to this object. + * @return a reference to this object. */ public ManifestBuilder withSignedSource(final String sourcePath, final String hashAlgorithm, final String hash) { TreeMap sourcePropertiesMap = new TreeMap<>(); @@ -87,10 +83,9 @@ public class ManifestBuilder { /** * Adds a non mano artifact. * - * @param artifactType the artifact type - * @param sourcePath the artifact source path - * @return - * a reference to this object. + * @param artifactType the artifact type + * @param sourcePath the artifact source path + * @return a reference to this object. */ public ManifestBuilder withNonManoArtifact(final String artifactType, final String sourcePath) { nonManoArtifactMap.putIfAbsent(artifactType, new ArrayList<>()); @@ -98,27 +93,22 @@ public class ManifestBuilder { return this; } - /** * Builds the String representing the manifest file. - * @return - * The manifest file as String + * + * @return The manifest file as String */ public String build() { final StringBuilder stringBuilder = new StringBuilder(); - if (!metadataMap.isEmpty()) { stringBuilder.append(buildMetadata()); } - if (!sourceWithPropertiesMap.isEmpty()) { stringBuilder.append(buildSource()); } - if (!nonManoArtifactMap.isEmpty()) { stringBuilder.append(buildNonManoArtifact()); } - return stringBuilder.toString(); } @@ -143,7 +133,6 @@ public class ManifestBuilder { if (algorithm != null) { stringBuilder.append(String.format(PROPERTY_FORMAT, ALGORITHM.getToken(), algorithm)); } - final String hash = propertiesMap.get(HASH.getToken()); if (hash != null) { stringBuilder.append(String.format(PROPERTY_FORMAT, HASH.getToken(), hash)); @@ -167,5 +156,4 @@ public class ManifestBuilder { } return stringBuilder.toString(); } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ONAPCsarValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ONAPCsarValidator.java index 0d5aef58ac..486970451f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ONAPCsarValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ONAPCsarValidator.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; @@ -51,7 +50,6 @@ import org.openecomp.sdc.tosca.csar.ToscaMetadata; class ONAPCsarValidator implements Validator { private static Logger logger = LoggerFactory.getLogger(ONAPCsarValidator.class); - private List uploadFileErrors = new ArrayList<>(); @Override @@ -61,30 +59,26 @@ class ONAPCsarValidator implements Validator { validateMetadata(contentHandler); validateNoExtraFiles(contentHandler); validateFolders(contentHandler.getFolderList()); - - if(uploadFileErrors == null || uploadFileErrors.isEmpty()){ + if (uploadFileErrors == null || uploadFileErrors.isEmpty()) { return errors; } errors.put(SdcCommon.UPLOAD_FILE, uploadFileErrors); return errors; } - private void validateMetadata(FileContentHandler contentMap){ + private void validateMetadata(FileContentHandler contentMap) { if (!validateTOSCAYamlFileInRootExist(contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME)) { try (InputStream metaFileContent = contentMap.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)) { - ToscaMetadata onboardingToscaMetadata = OnboardingToscaMetadata.parseToscaMetadataFile(metaFileContent); String entryDefinitionsPath = onboardingToscaMetadata.getMetaEntries().get(ENTRY_DEFINITIONS.getName()); if (entryDefinitionsPath != null) { validateFileExist(contentMap, entryDefinitionsPath); } else { - uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, - Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage())); + uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage())); } } catch (IOException exception) { logger.error(exception.getMessage(), exception); - uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, - Messages.FAILED_TO_VALIDATE_METADATA.getErrorMessage())); + uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, Messages.FAILED_TO_VALIDATE_METADATA.getErrorMessage())); } } else { validateFileExist(contentMap, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME); @@ -95,40 +89,32 @@ class ONAPCsarValidator implements Validator { if (!validateFileExist(contentMap, MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { return; } - try (final InputStream fileContent = contentMap.getFileContentAsStream(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME)) { final Manifest onboardingManifest = new ONAPManifestOnboarding(); onboardingManifest.parse(fileContent); if (!onboardingManifest.isValid()) { - onboardingManifest.getErrors() - .forEach(error -> uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, error))); + onboardingManifest.getErrors().forEach(error -> uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, error))); } } catch (final IOException ex) { - final String errorMessage = - Messages.MANIFEST_UNEXPECTED_ERROR.formatMessage(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME, ex.getMessage()); + final String errorMessage = Messages.MANIFEST_UNEXPECTED_ERROR.formatMessage(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME, ex.getMessage()); uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, errorMessage)); logger.error(errorMessage, ex); } } private void validateNoExtraFiles(FileContentHandler contentMap) { - List unwantedFiles = contentMap.getFileList().stream() - .filter(this::filterFiles).collect(Collectors.toList()); + List unwantedFiles = contentMap.getFileList().stream().filter(this::filterFiles).collect(Collectors.toList()); if (!unwantedFiles.isEmpty()) { - unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile -> - uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(), unwantedFile)))); + unwantedFiles.stream().filter(this::filterFiles).forEach(unwantedFile -> uploadFileErrors + .add(new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.CSAR_FILES_NOT_ALLOWED.getErrorMessage(), unwantedFile)))); } } private void validateFolders(Set folderList) { - List filterResult = - folderList.stream().filter(this::filterFolders).collect(Collectors.toList()); + List filterResult = folderList.stream().filter(this::filterFolders).collect(Collectors.toList()); if (!filterResult.isEmpty()) { - folderList.stream().filter(this::filterFolders).forEach(unwantedFolder -> - uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(), - unwantedFolder)))); + folderList.stream().filter(this::filterFolders).forEach(unwantedFolder -> uploadFileErrors.add( + new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.CSAR_DIRECTORIES_NOT_ALLOWED.getErrorMessage(), unwantedFolder)))); } } @@ -146,11 +132,10 @@ class ONAPCsarValidator implements Validator { } private boolean validateFileExist(FileContentHandler contentMap, String fileName) { - boolean containsFile = contentMap.containsFile(fileName); if (!containsFile) { - uploadFileErrors.add(new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName))); + uploadFileErrors + .add(new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.CSAR_FILE_NOT_FOUND.getErrorMessage(), fileName))); } return containsFile; } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/PMDictionaryValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/PMDictionaryValidator.java index 90270c2f7e..77c7347e49 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/PMDictionaryValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/PMDictionaryValidator.java @@ -30,19 +30,14 @@ import org.onap.validation.yaml.error.YamlDocumentValidationError; public class PMDictionaryValidator { public void validate(Stream pmDictionaryFiles, Consumer errorReporter) { - pmDictionaryFiles - .map(this::validate) - .flatMap(Collection::stream) - .forEach(errorReporter); + pmDictionaryFiles.map(this::validate).flatMap(Collection::stream).forEach(errorReporter); } private List validate(byte[] fileContent) { List errors = new ArrayList<>(); try { List validationErrors = new YamlContentValidator().validate(fileContent); - validationErrors.stream() - .map(this::formatErrorMessage) - .forEach(errors::add); + validationErrors.stream().map(this::formatErrorMessage).forEach(errors::add); } catch (Exception e) { errors.add(e.getMessage()); } @@ -50,9 +45,6 @@ public class PMDictionaryValidator { } private String formatErrorMessage(YamlDocumentValidationError error) { - return String.format("Document number: %d, Path: %s, Message: %s", - error.getYamlDocumentNumber(), - error.getPath(), - error.getMessage()); + return String.format("Document number: %d, Path: %s, Message: %s", error.getYamlDocumentNumber(), error.getPath(), error.getMessage()); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004MetaDirectoryValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004MetaDirectoryValidator.java index 22ab4f45a6..d99848ddb8 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004MetaDirectoryValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004MetaDirectoryValidator.java @@ -19,10 +19,8 @@ * * Modifications copyright (c) 2020 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; - import static org.openecomp.sdc.be.config.NonManoArtifactType.ONAP_CNF_HELM; import static org.openecomp.sdc.be.config.NonManoArtifactType.ONAP_PM_DICTIONARY; import static org.openecomp.sdc.be.config.NonManoArtifactType.ONAP_SW_INFORMATION; @@ -44,6 +42,7 @@ import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.TOSCA_META_FILE_VERSIO import static org.openecomp.sdc.tosca.csar.ToscaMetadataFileInfo.TOSCA_META_FILE_VERSION_1_0; import static org.openecomp.sdc.tosca.csar.ToscaMetadataFileInfo.TOSCA_META_PATH_FILE_NAME; +import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -57,8 +56,6 @@ import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; import java.util.stream.Stream; - -import com.google.common.collect.ImmutableSet; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.io.FilenameUtils; import org.openecomp.core.impl.ToscaDefinitionImportHandler; @@ -89,22 +86,21 @@ import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException import org.yaml.snakeyaml.Yaml; /** - * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure - * as defined in ETSI GS NFV-SOL 004 v2.6.1. + * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure as defined in ETSI GS NFV-SOL + * 004 v2.6.1. */ class SOL004MetaDirectoryValidator implements Validator { private static final Logger LOGGER = LoggerFactory.getLogger(SOL004MetaDirectoryValidator.class); - private static final String MANIFEST_SOURCE = "Source"; private static final String MANIFEST_NON_MANO_SOURCE = "Non-MANO Source"; + protected final ValidatorUtils validatorUtils = new ValidatorUtils(); private final List errorsByFile = new CopyOnWriteArrayList<>(); private final SecurityManager securityManager; + private final InternalFilesFilter internalFilesFilter = new InternalFilesFilter(); private OnboardingPackageContentHandler contentHandler; private Set folderList; private ToscaMetadata toscaMetadata; - private final InternalFilesFilter internalFilesFilter = new InternalFilesFilter(); - protected final ValidatorUtils validatorUtils = new ValidatorUtils(); public SOL004MetaDirectoryValidator() { securityManager = SecurityManager.getInstance(); @@ -121,7 +117,6 @@ class SOL004MetaDirectoryValidator implements Validator { this.folderList = contentHandler.getFolderList(); parseToscaMetadata(); verifyMetadataFile(); - if (packageHasCertificate()) { verifySignedFiles(); } @@ -143,9 +138,7 @@ class SOL004MetaDirectoryValidator implements Validator { */ private void parseToscaMetadata() { try { - toscaMetadata = - OnboardingToscaMetadata - .parseToscaMetadataFile(contentHandler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); + toscaMetadata = OnboardingToscaMetadata.parseToscaMetadataFile(contentHandler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); } catch (final IOException e) { reportError(ErrorLevel.ERROR, Messages.METADATA_PARSER_INTERNAL.getErrorMessage()); LOGGER.error(Messages.METADATA_PARSER_INTERNAL.getErrorMessage(), e.getMessage(), e); @@ -175,12 +168,11 @@ class SOL004MetaDirectoryValidator implements Validator { final byte[] fileSignatureBytes = contentHandler.getFileContent(fileSignaturePath); try { if (!securityManager.verifySignedData(fileSignatureBytes, packageCert, fileBytes)) { - reportError(ErrorLevel.ERROR, - Messages.ARTIFACT_INVALID_SIGNATURE.formatMessage(fileSignaturePath, filePath)); + reportError(ErrorLevel.ERROR, Messages.ARTIFACT_INVALID_SIGNATURE.formatMessage(fileSignaturePath, filePath)); } } catch (final SecurityManagerException e) { final String errorMessage = Messages.ARTIFACT_SIGNATURE_VALIDATION_ERROR - .formatMessage(fileSignaturePath, filePath, packageCertificatePath, e.getMessage()); + .formatMessage(fileSignaturePath, filePath, packageCertificatePath, e.getMessage()); reportError(ErrorLevel.ERROR, errorMessage); LOGGER.error(errorMessage, e); } @@ -196,8 +188,7 @@ class SOL004MetaDirectoryValidator implements Validator { reportError(ErrorLevel.ERROR, Messages.MANIFEST_INVALID_EXT.getErrorMessage()); } if (!mainDefinitionFileName.equals(manifestFileName)) { - reportError(ErrorLevel.ERROR, String.format(Messages.MANIFEST_INVALID_NAME.getErrorMessage(), - manifestFileName, mainDefinitionFileName)); + reportError(ErrorLevel.ERROR, String.format(Messages.MANIFEST_INVALID_NAME.getErrorMessage(), manifestFileName, mainDefinitionFileName)); } } @@ -211,15 +202,13 @@ class SOL004MetaDirectoryValidator implements Validator { private boolean hasETSIMetadata() { final Map entries = toscaMetadata.getMetaEntries(); - return hasEntry(entries, TOSCA_META_FILE_VERSION_ENTRY.getName()) - && hasEntry(entries, CSAR_VERSION_ENTRY.getName()) - && hasEntry(entries, CREATED_BY_ENTRY.getName()); + return hasEntry(entries, TOSCA_META_FILE_VERSION_ENTRY.getName()) && hasEntry(entries, CSAR_VERSION_ENTRY.getName()) && hasEntry(entries, + CREATED_BY_ENTRY.getName()); } private boolean hasEntry(final Map entries, final String mandatoryEntry) { if (!entries.containsKey(mandatoryEntry)) { - reportError(ErrorLevel.ERROR, - String.format(Messages.METADATA_MISSING_ENTRY.getErrorMessage(), mandatoryEntry)); + reportError(ErrorLevel.ERROR, String.format(Messages.METADATA_MISSING_ENTRY.getErrorMessage(), mandatoryEntry)); return false; } return true; @@ -237,7 +226,6 @@ class SOL004MetaDirectoryValidator implements Validator { return; } final String value = entry.getValue(); - switch (toscaMetaEntry) { case TOSCA_META_FILE_VERSION_ENTRY: case CSAR_VERSION_ENTRY: @@ -277,18 +265,14 @@ class SOL004MetaDirectoryValidator implements Validator { validateOtherEntries(value); } else { final String key = (String) entry.getKey(); - reportError(ErrorLevel.ERROR, - String.format(Messages.MANIFEST_INVALID_PNF_METADATA.getErrorMessage(), key)); + reportError(ErrorLevel.ERROR, String.format(Messages.MANIFEST_INVALID_PNF_METADATA.getErrorMessage(), key)); } - } } private void verifyMetadataEntryVersions(final String key, final String version) { - if (!(isValidTOSCAVersion(key, version) || isValidCSARVersion(key, version) - || CREATED_BY_ENTRY.getName().equals(key))) { - errorsByFile.add(new ErrorMessage(ErrorLevel.ERROR, - String.format(Messages.METADATA_INVALID_VERSION.getErrorMessage(), key, version))); + if (!(isValidTOSCAVersion(key, version) || isValidCSARVersion(key, version) || CREATED_BY_ENTRY.getName().equals(key))) { + errorsByFile.add(new ErrorMessage(ErrorLevel.ERROR, String.format(Messages.METADATA_INVALID_VERSION.getErrorMessage(), key, version))); LOGGER.error("{}: key {} - value {} ", Messages.METADATA_INVALID_VERSION.getErrorMessage(), key, version); } } @@ -298,16 +282,13 @@ class SOL004MetaDirectoryValidator implements Validator { } private boolean isValidCSARVersion(final String value, final String version) { - return CSAR_VERSION_ENTRY.getName().equals(value) && (CSAR_VERSION_1_1.equals(version) - || CSAR_VERSION_1_0.equals(version)); + return CSAR_VERSION_ENTRY.getName().equals(value) && (CSAR_VERSION_1_1.equals(version) || CSAR_VERSION_1_0.equals(version)); } protected void validateDefinitionFile(final String filePath) { final Set existingFiles = contentHandler.getFileList(); - if (verifyFileExists(existingFiles, filePath)) { - final ToscaDefinitionImportHandler toscaDefinitionImportHandler = - new ToscaDefinitionImportHandler(contentHandler.getFiles(), filePath); + final ToscaDefinitionImportHandler toscaDefinitionImportHandler = new ToscaDefinitionImportHandler(contentHandler.getFiles(), filePath); final List validationErrorList = toscaDefinitionImportHandler.getErrors(); if (CollectionUtils.isNotEmpty(validationErrorList)) { errorsByFile.addAll(validationErrorList); @@ -345,31 +326,23 @@ class SOL004MetaDirectoryValidator implements Validator { private void verifyManifestMetadata(final Map metadata) { if (!validMetaLimit(metadata)) { - reportError(ErrorLevel.ERROR, - String.format(Messages.MANIFEST_METADATA_DOES_NOT_MATCH_LIMIT.getErrorMessage(), - MANIFEST_METADATA_LIMIT)); + reportError(ErrorLevel.ERROR, String.format(Messages.MANIFEST_METADATA_DOES_NOT_MATCH_LIMIT.getErrorMessage(), MANIFEST_METADATA_LIMIT)); } handleMetadataEntries(metadata); } protected boolean isPnfMetadata(final Map metadata) { final String firstMetadataDefinition = metadata.keySet().iterator().next(); - final String expectedMetadataType = - firstMetadataDefinition.contains(TOSCA_TYPE_PNF) ? TOSCA_TYPE_PNF : TOSCA_TYPE_VNF; - if (metadata.keySet().stream() - .anyMatch((final String metadataEntry) -> !metadataEntry.contains(expectedMetadataType))) { + final String expectedMetadataType = firstMetadataDefinition.contains(TOSCA_TYPE_PNF) ? TOSCA_TYPE_PNF : TOSCA_TYPE_VNF; + if (metadata.keySet().stream().anyMatch((final String metadataEntry) -> !metadataEntry.contains(expectedMetadataType))) { throw new InvalidManifestMetadataException(Messages.MANIFEST_METADATA_INVALID_ENTRY.getErrorMessage()); } - return TOSCA_TYPE_PNF.equals(expectedMetadataType); } private void handleMetadataEntries(final Map metadata) { - getManifestMetadata(metadata).stream() - .filter(requiredEntry -> !metadata.containsKey(requiredEntry)) - .forEach(requiredEntry -> - reportError(ErrorLevel.ERROR, - String.format(Messages.MANIFEST_METADATA_MISSING_ENTRY.getErrorMessage(), requiredEntry))); + getManifestMetadata(metadata).stream().filter(requiredEntry -> !metadata.containsKey(requiredEntry)).forEach( + requiredEntry -> reportError(ErrorLevel.ERROR, String.format(Messages.MANIFEST_METADATA_MISSING_ENTRY.getErrorMessage(), requiredEntry))); } /** @@ -381,9 +354,7 @@ class SOL004MetaDirectoryValidator implements Validator { final Set packageFiles = contentHandler.getFileList(); final List sources = internalFilesFilter.filter(onboardingManifest.getSources()); verifyFilesExist(packageFiles, sources, MANIFEST_SOURCE); - final Map> nonManoArtifacts = onboardingManifest.getNonManoSources(); - final List nonManoValidFilePaths = new ArrayList<>(); nonManoArtifacts.forEach((nonManoType, files) -> { final List internalNonManoFileList = internalFilesFilter.filter(files); @@ -397,9 +368,7 @@ class SOL004MetaDirectoryValidator implements Validator { validateOnapCnfHelmNonManoEntry(files); } }); - verifyFilesExist(packageFiles, nonManoValidFilePaths, MANIFEST_NON_MANO_SOURCE); - final Set allReferredFiles = new HashSet<>(); allReferredFiles.addAll(sources); allReferredFiles.addAll(nonManoValidFilePaths); @@ -412,32 +381,25 @@ class SOL004MetaDirectoryValidator implements Validator { return; } if (files.size() != 1) { - final String formattedFileList = files.stream() - .map(filePath -> String.format("'%s'", filePath)) - .collect(Collectors.joining(", ")); - reportError(ErrorLevel.ERROR, - Messages.UNIQUE_SW_INFORMATION_NON_MANO_ERROR.formatMessage(formattedFileList)); + final String formattedFileList = files.stream().map(filePath -> String.format("'%s'", filePath)).collect(Collectors.joining(", ")); + reportError(ErrorLevel.ERROR, Messages.UNIQUE_SW_INFORMATION_NON_MANO_ERROR.formatMessage(formattedFileList)); return; } final String swInformationFilePath = files.get(0); final byte[] swInformationYaml = contentHandler.getFileContent(swInformationFilePath); - final Optional parsedYaml = SoftwareInformationArtifactYamlParser - .parse(swInformationYaml); + final Optional parsedYaml = SoftwareInformationArtifactYamlParser.parse(swInformationYaml); if (!parsedYaml.isPresent()) { - reportError(ErrorLevel.ERROR, - Messages.INVALID_SW_INFORMATION_NON_MANO_ERROR.formatMessage(swInformationFilePath)); + reportError(ErrorLevel.ERROR, Messages.INVALID_SW_INFORMATION_NON_MANO_ERROR.formatMessage(swInformationFilePath)); } else { final PnfSoftwareInformation pnfSoftwareInformation = parsedYaml.get(); if (!pnfSoftwareInformation.isValid()) { - reportError(ErrorLevel.ERROR, - Messages.INCORRECT_SW_INFORMATION_NON_MANO_ERROR.formatMessage(swInformationFilePath)); + reportError(ErrorLevel.ERROR, Messages.INCORRECT_SW_INFORMATION_NON_MANO_ERROR.formatMessage(swInformationFilePath)); } } } /** - * Validates if a YAML file has the correct extension, is not empty and the content is a valid YAML. Reports each - * error found. + * Validates if a YAML file has the correct extension, is not empty and the content is a valid YAML. Reports each error found. * * @param filePath the file path inside the package */ @@ -450,7 +412,6 @@ class SOL004MetaDirectoryValidator implements Validator { reportError(ErrorLevel.ERROR, Messages.INVALID_YAML_EXTENSION.formatMessage(filePath)); return; } - try (final InputStream fileContent = contentHandler.getFileContentAsStream(filePath)) { if (fileContent == null) { reportError(ErrorLevel.ERROR, Messages.EMPTY_YAML_FILE_1.formatMessage(filePath)); @@ -477,8 +438,7 @@ class SOL004MetaDirectoryValidator implements Validator { private void verifyFilesBeingReferred(final Set referredFileSet, final Set packageFileSet) { packageFileSet.forEach(filePath -> { if (!isManifestFile(filePath) && !referredFileSet.contains(filePath)) { - reportError(ErrorLevel.ERROR, - String.format(Messages.MISSING_MANIFEST_REFERENCE.getErrorMessage(), filePath)); + reportError(ErrorLevel.ERROR, String.format(Messages.MISSING_MANIFEST_REFERENCE.getErrorMessage(), filePath)); } }); } @@ -489,16 +449,14 @@ class SOL004MetaDirectoryValidator implements Validator { private void validateOtherEntries(final String folderPath) { if (!verifyFoldersExist(folderList, folderPath)) { - reportError(ErrorLevel.ERROR, String.format(Messages.METADATA_MISSING_OPTIONAL_FOLDERS.getErrorMessage(), - folderPath)); + reportError(ErrorLevel.ERROR, String.format(Messages.METADATA_MISSING_OPTIONAL_FOLDERS.getErrorMessage(), folderPath)); } } private void validateCertificate(final String file) { final Set packageFiles = contentHandler.getFileList(); if (!verifyFileExist(packageFiles, file)) { - reportError(ErrorLevel.ERROR, - String.format(Messages.MISSING_METADATA_FILES.getErrorMessage(), file, file)); + reportError(ErrorLevel.ERROR, String.format(Messages.MISSING_METADATA_FILES.getErrorMessage(), file, file)); } } @@ -509,8 +467,7 @@ class SOL004MetaDirectoryValidator implements Validator { private void verifyFilesExist(final Set existingFiles, final List sources, final String type) { sources.forEach(file -> { if (!existingFiles.contains(file)) { - reportError(ErrorLevel.ERROR, - String.format(Messages.MISSING_MANIFEST_SOURCE.getErrorMessage(), type, file)); + reportError(ErrorLevel.ERROR, String.format(Messages.MISSING_MANIFEST_SOURCE.getErrorMessage(), type, file)); } }); } @@ -552,10 +509,8 @@ class SOL004MetaDirectoryValidator implements Validator { } private void validatePmDictionaryContentsAgainstSchema() { - final Stream pmDictionaryFiles = new FileExtractor(getEtsiEntryManifestPath(), contentHandler) - .findFiles(ONAP_PM_DICTIONARY); - new PMDictionaryValidator() - .validate(pmDictionaryFiles, (String message) -> reportError(ErrorLevel.ERROR, message)); + final Stream pmDictionaryFiles = new FileExtractor(getEtsiEntryManifestPath(), contentHandler).findFiles(ONAP_PM_DICTIONARY); + new PMDictionaryValidator().validate(pmDictionaryFiles, (String message) -> reportError(ErrorLevel.ERROR, message)); } private String getEtsiEntryManifestPath() { @@ -564,6 +519,7 @@ class SOL004MetaDirectoryValidator implements Validator { /** * Validates if onap_cnf_helm non_mano type points to a file + * * @param files */ private void validateOnapCnfHelmNonManoEntry(final List files) { @@ -572,11 +528,8 @@ class SOL004MetaDirectoryValidator implements Validator { return; } if (files.size() != 1) { - final String formattedFileList = files.stream() - .map(filePath -> String.format("'%s'", filePath)) - .collect(Collectors.joining(", ")); - reportError(ErrorLevel.ERROR, - Messages.UNIQUE_ONAP_CNF_HELM_NON_MANO_ERROR.formatMessage(formattedFileList)); + final String formattedFileList = files.stream().map(filePath -> String.format("'%s'", filePath)).collect(Collectors.joining(", ")); + reportError(ErrorLevel.ERROR, Messages.UNIQUE_ONAP_CNF_HELM_NON_MANO_ERROR.formatMessage(formattedFileList)); } } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidator.java index 9e380a355c..12d5ecfff9 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version3MetaDirectoryValidator.java @@ -36,8 +36,8 @@ import org.openecomp.sdc.tosca.csar.ToscaMetaEntry; import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager; /** - * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure - * as defined in ETSI GS NFV-SOL 004 v3.3.1. + * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure as defined in ETSI GS NFV-SOL + * 004 v3.3.1. */ class SOL004Version3MetaDirectoryValidator extends SOL004MetaDirectoryValidator { @@ -56,8 +56,9 @@ class SOL004Version3MetaDirectoryValidator extends SOL004MetaDirectoryValidator if (!ToscaMetaEntry.OTHER_DEFINITIONS.getName().equals(entry.getKey())) { reportError(ErrorLevel.ERROR, Messages.METADATA_UNSUPPORTED_ENTRY.formatMessage(entry.getKey())); LOGGER.warn(Messages.METADATA_UNSUPPORTED_ENTRY.getErrorMessage(), entry.getKey()); - } else + } else { validateDefinitionFile(entry.getValue()); + } } @Override diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version4MetaDirectoryValidator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version4MetaDirectoryValidator.java index 701abfc677..31c19d7794 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version4MetaDirectoryValidator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/SOL004Version4MetaDirectoryValidator.java @@ -36,8 +36,8 @@ import org.openecomp.sdc.tosca.csar.ToscaMetaEntry; import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager; /** - * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure - * as defined in ETSI GS NFV-SOL 004 v3.3.1 with CNF Enhancements from ETSI GS NFV-SOL 004 v4.1.1 + * Validates the contents of the package to ensure it complies with the "CSAR with TOSCA-Metadata directory" structure as defined in ETSI GS NFV-SOL + * 004 v3.3.1 with CNF Enhancements from ETSI GS NFV-SOL 004 v4.1.1 */ class SOL004Version4MetaDirectoryValidator extends SOL004MetaDirectoryValidator { @@ -78,5 +78,4 @@ class SOL004Version4MetaDirectoryValidator extends SOL004MetaDirectoryValidator validateDefinitionFile(entry.getValue()); } } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/Validator.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/Validator.java index 34386b6d29..e8f88c7eba 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/Validator.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/Validator.java @@ -17,22 +17,19 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; -import org.openecomp.core.utilities.file.FileContentHandler; -import org.openecomp.sdc.datatypes.error.ErrorMessage; import java.util.List; import java.util.Map; +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.sdc.datatypes.error.ErrorMessage; /** * Validates the contents of the CSAR package uploaded in SDC. */ - public interface Validator { /** - * * @param contentHandler contains file and its data * @return errors Map of errors that occur */ diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ValidatorFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ValidatorFactory.java index 9d218190d8..27a1852644 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ValidatorFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/ValidatorFactory.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation; import static org.openecomp.sdc.tosca.csar.CSARConstants.ETSI_VERSION_2_7_1; @@ -29,8 +28,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi.ETSIServiceImp public class ValidatorFactory { - private ValidatorFactory(){ - + private ValidatorFactory() { } /** @@ -45,7 +43,7 @@ public class ValidatorFactory { if (!etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) { return new ONAPCsarValidator(); } - if (!etsiService.getHighestCompatibleSpecificationVersion(fileContentHandler).isLowerThan(ETSI_VERSION_2_7_1)){ + if (!etsiService.getHighestCompatibleSpecificationVersion(fileContentHandler).isLowerThan(ETSI_VERSION_2_7_1)) { if (etsiService.hasCnfEnhancements(fileContentHandler)) { return new SOL004Version4MetaDirectoryValidator(); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/exception/MissingCertificateException.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/exception/MissingCertificateException.java index 620ff345ad..e3d91e01df 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/exception/MissingCertificateException.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/exception/MissingCertificateException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.exception; public class MissingCertificateException extends RuntimeException { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/FileExtractor.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/FileExtractor.java index c6d7d637fa..bfef0b4471 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/FileExtractor.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/FileExtractor.java @@ -48,8 +48,7 @@ public class FileExtractor { Map> nonManoSources = extractNonManoSources(); List pathsToSources = nonManoSources.getOrDefault(fileType.getType(), new ArrayList<>()); List pathsToLocalFiles = internalFilesFilter.filter(pathsToSources); - return pathsToLocalFiles.stream() - .map(contentHandler::getFileContent); + return pathsToLocalFiles.stream().map(contentHandler::getFileContent); } private Map> extractNonManoSources() { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/InternalFilesFilter.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/InternalFilesFilter.java index 50dcd0ce29..ce119f6a6f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/InternalFilesFilter.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/InternalFilesFilter.java @@ -25,9 +25,7 @@ import java.util.stream.Collectors; public class InternalFilesFilter { public List filter(final List sources) { - return sources.stream() - .filter(this::isInternalFile) - .collect(Collectors.toList()); + return sources.stream().filter(this::isInternalFile).collect(Collectors.toList()); } private boolean isInternalFile(final String filePath) { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/ValidatorUtils.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/ValidatorUtils.java index cfdd53774f..d260b1272b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/ValidatorUtils.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/csar/validation/utils/ValidatorUtils.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.csar.validation.utils; import static org.openecomp.sdc.tosca.csar.CSARConstants.TOSCA_TYPE_PNF; @@ -32,15 +31,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.exceptions.Inv public class ValidatorUtils { public boolean isPnfMetadata(List keys) { - keys = keys.stream().filter(key -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(key)) - .collect(Collectors.toList()); - final String expectedMetadataType = - keys.get(0).contains(TOSCA_TYPE_PNF) ? TOSCA_TYPE_PNF : TOSCA_TYPE_VNF; - if (keys.stream() - .anyMatch(k -> !k.startsWith(expectedMetadataType))) { + keys = keys.stream().filter(key -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(key)).collect(Collectors.toList()); + final String expectedMetadataType = keys.get(0).contains(TOSCA_TYPE_PNF) ? TOSCA_TYPE_PNF : TOSCA_TYPE_VNF; + if (keys.stream().anyMatch(k -> !k.startsWith(expectedMetadataType))) { throw new InvalidManifestMetadataException(Messages.MANIFEST_METADATA_INVALID_ENTRY.getErrorMessage()); } return expectedMetadataType.equals(TOSCA_TYPE_PNF); } - } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/InvalidManifestMetadataException.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/InvalidManifestMetadataException.java index 137891c0c9..1204a73509 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/InvalidManifestMetadataException.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/InvalidManifestMetadataException.java @@ -17,12 +17,11 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.exceptions; -public class InvalidManifestMetadataException extends RuntimeException{ +public class InvalidManifestMetadataException extends RuntimeException { - public InvalidManifestMetadataException(String message){ + public InvalidManifestMetadataException(String message) { super(message); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/OrchestrationTemplateHandlerException.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/OrchestrationTemplateHandlerException.java index a8a9105254..3f47915fdd 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/OrchestrationTemplateHandlerException.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/exceptions/OrchestrationTemplateHandlerException.java @@ -17,12 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.exceptions; -public class OrchestrationTemplateHandlerException extends RuntimeException{ +public class OrchestrationTemplateHandlerException extends RuntimeException { - public OrchestrationTemplateHandlerException(String message, Throwable throwable){ + public OrchestrationTemplateHandlerException(String message, Throwable throwable) { super(message, throwable); } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java index 0ac093240d..0b222fd51d 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationProcessFactory.java @@ -13,9 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; +import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_CONFIG_NAMESPACE; + +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; @@ -23,49 +27,39 @@ import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.vendorsoftwareproduct.types.ConfigConstants; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; - -import static org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil.ORCHESTRATION_CONFIG_NAMESPACE; public class OrchestrationProcessFactory { - private static final Map PROCESS_IMPL_MAP; - private OrchestrationProcessFactory() { - - } - - static { - Configuration config = ConfigurationManager.lookup(); - PROCESS_IMPL_MAP = new ConcurrentHashMap<>(config.populateMap(ORCHESTRATION_CONFIG_NAMESPACE, - ConfigConstants.PROCESS_IMPL_KEY, ImplementationConfiguration.class)); + private static final Map PROCESS_IMPL_MAP; - } - - public static Optional getInstance(String fileSuffix) { - - if (fileSuffix == null) { - return Optional.empty(); + static { + Configuration config = ConfigurationManager.lookup(); + PROCESS_IMPL_MAP = new ConcurrentHashMap<>( + config.populateMap(ORCHESTRATION_CONFIG_NAMESPACE, ConfigConstants.PROCESS_IMPL_KEY, ImplementationConfiguration.class)); } - String updatedFileSuffix = fileSuffix; - updatedFileSuffix = updatedFileSuffix.toLowerCase().trim(); - OnboardingTypesEnum onboardingTypesEnum = OnboardingTypesEnum.getOnboardingTypesEnum(updatedFileSuffix); - if (onboardingTypesEnum == null) { - return Optional.empty(); + + private OrchestrationProcessFactory() { } - try { - return Optional.of(createInstance(PROCESS_IMPL_MAP.get(onboardingTypesEnum.toString()))); - }catch (Exception e){ - return Optional.empty(); + public static Optional getInstance(String fileSuffix) { + if (fileSuffix == null) { + return Optional.empty(); + } + String updatedFileSuffix = fileSuffix; + updatedFileSuffix = updatedFileSuffix.toLowerCase().trim(); + OnboardingTypesEnum onboardingTypesEnum = OnboardingTypesEnum.getOnboardingTypesEnum(updatedFileSuffix); + if (onboardingTypesEnum == null) { + return Optional.empty(); + } + try { + return Optional.of(createInstance(PROCESS_IMPL_MAP.get(onboardingTypesEnum.toString()))); + } catch (Exception e) { + return Optional.empty(); + } } - } - private static OrchestrationTemplateProcessHandler createInstance(ImplementationConfiguration implClass) - throws Exception { - OrchestrationTemplateProcessHandler handler; - handler = - CommonMethods.newInstance(implClass.getImplementationClass(), OrchestrationTemplateProcessHandler.class); - return handler; - } + private static OrchestrationTemplateProcessHandler createInstance(ImplementationConfiguration implClass) throws Exception { + OrchestrationTemplateProcessHandler handler; + handler = CommonMethods.newInstance(implClass.getImplementationClass(), OrchestrationTemplateProcessHandler.class); + return handler; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessCsarHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessCsarHandler.java index 38508c6ec3..8778e0b56b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessCsarHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessCsarHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; import java.io.ByteArrayInputStream; @@ -58,125 +57,107 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; public class OrchestrationTemplateProcessCsarHandler implements OrchestrationTemplateProcessHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class); - private static final String SDC_ONBOARDED_PACKAGE_DIR = "Deployment/" + ArtifactTypeEnum.ETSI_PACKAGE.getType() + "/"; - private static final String EXT_SEPARATOR = "."; - private final CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface(); - private final ToscaTreeManager toscaTreeManager = new ToscaTreeManager(); - - @Override - public OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData) { - - - UploadFileResponse uploadFileResponse = new UploadFileResponse(); - Optional fileContent = OrchestrationUtil - .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse, - candidateData.getContentData().array()); - - OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); - if (fileContent.isPresent()) { - try { - FileContentHandler fileContentHandler = fileContent.get(); - processCsar(vspDetails, fileContentHandler, candidateData, response); - } catch (CoreException e) { - LOGGER.error(e.getMessage(), e); - response.addErrorMessageToMap(e.code().id(), e.code().message(),ErrorLevel.ERROR); - }catch (IOException e){ - LOGGER.error(e.getMessage(), e); - response.addErrorMessageToMap(SdcCommon.PROCESS_FILE, e.getMessage(), ErrorLevel.ERROR); - } - } else { - if (!uploadFileResponse.getErrors().isEmpty()) { - response.addStructureErrors(uploadFileResponse.getErrors()); - } + private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessCsarHandler.class); + private static final String SDC_ONBOARDED_PACKAGE_DIR = "Deployment/" + ArtifactTypeEnum.ETSI_PACKAGE.getType() + "/"; + private static final String EXT_SEPARATOR = "."; + private final CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface(); + private final ToscaTreeManager toscaTreeManager = new ToscaTreeManager(); + + @Override + public OrchestrationTemplateActionResponse process(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData) { + UploadFileResponse uploadFileResponse = new UploadFileResponse(); + Optional fileContent = OrchestrationUtil + .getFileContentMap(OnboardingTypesEnum.CSAR, uploadFileResponse, candidateData.getContentData().array()); + OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); + if (fileContent.isPresent()) { + try { + FileContentHandler fileContentHandler = fileContent.get(); + processCsar(vspDetails, fileContentHandler, candidateData, response); + } catch (CoreException e) { + LOGGER.error(e.getMessage(), e); + response.addErrorMessageToMap(e.code().id(), e.code().message(), ErrorLevel.ERROR); + } catch (IOException e) { + LOGGER.error(e.getMessage(), e); + response.addErrorMessageToMap(SdcCommon.PROCESS_FILE, e.getMessage(), ErrorLevel.ERROR); + } + } else { + if (!uploadFileResponse.getErrors().isEmpty()) { + response.addStructureErrors(uploadFileResponse.getErrors()); + } + } + return response; } - return response; - } - - private void processCsar(VspDetails vspDetails, - FileContentHandler fileContentHandler, - OrchestrationTemplateCandidateData candidateData, - OrchestrationTemplateActionResponse response) throws IOException{ - response.setFileNames(new ArrayList<>(fileContentHandler.getFileList())); - Map> errors = validateCsar(fileContentHandler); - toscaTreeManager.createTree(); - if (!isValid(errors)) { - response.addStructureErrors(errors); - toscaTreeManager.addErrors(errors); - candidateService.updateValidationData(vspDetails.getId(), vspDetails.getVersion(), - new ValidationStructureList(toscaTreeManager.getTree())); - return; + private void processCsar(VspDetails vspDetails, FileContentHandler fileContentHandler, OrchestrationTemplateCandidateData candidateData, + OrchestrationTemplateActionResponse response) throws IOException { + response.setFileNames(new ArrayList<>(fileContentHandler.getFileList())); + Map> errors = validateCsar(fileContentHandler); + toscaTreeManager.createTree(); + if (!isValid(errors)) { + response.addStructureErrors(errors); + toscaTreeManager.addErrors(errors); + candidateService + .updateValidationData(vspDetails.getId(), vspDetails.getVersion(), new ValidationStructureList(toscaTreeManager.getTree())); + return; + } + HeatStructureTree tree = toscaTreeManager.getTree(); + Map componentsQuestionnaire = new HashMap<>(); + Map> componentNicsQuestionnaire = new HashMap<>(); + Map> componentMibList = new HashMap<>(); + Map> processes = new HashMap<>(); + Map processArtifact = new HashMap<>(); + OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); + orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(), vspDetails.getVersion(), componentsQuestionnaire, + componentNicsQuestionnaire, componentMibList, processes, processArtifact); + Optional zipByteArrayInputStream = candidateService + .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null, OnboardingTypesEnum.CSAR, errors); + orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion()); + zipByteArrayInputStream.ifPresent( + byteArrayInputStream -> orchestrationUtil.saveUploadData(vspDetails, candidateData, byteArrayInputStream, fileContentHandler, tree)); + ETSIService etsiService = new ETSIServiceImpl(); + ToscaServiceModel toscaServiceModel; + if (etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) { + if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) { + fileContentHandler + .addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getOriginalFileName() + EXT_SEPARATOR + candidateData.getOriginalFileSuffix(), + candidateData.getOriginalFileContentData().array()); + } else { + fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getFileName() + EXT_SEPARATOR + candidateData.getFileSuffix(), + candidateData.getContentData().array()); + } + final ResourceTypeEnum resourceType = etsiService.getResourceType(fileContentHandler); + toscaServiceModel = instantiateToscaConverterFor(resourceType).convert(fileContentHandler); + } else { + toscaServiceModel = new ToscaConverterImpl().convert(fileContentHandler); + } + orchestrationUtil.saveServiceModel(vspDetails.getId(), vspDetails.getVersion(), toscaServiceModel, toscaServiceModel); + candidateService.deleteOrchestrationTemplateCandidate(vspDetails.getId(), vspDetails.getVersion()); } - HeatStructureTree tree = toscaTreeManager.getTree(); - - Map componentsQuestionnaire = new HashMap<>(); - Map> componentNicsQuestionnaire = new HashMap<>(); - Map> componentMibList = new HashMap<>(); - Map> processes = new HashMap<>(); - Map processArtifact = new HashMap<>(); - OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); - orchestrationUtil.backupComponentsQuestionnaireBeforeDelete(vspDetails.getId(), - vspDetails.getVersion(), componentsQuestionnaire, - componentNicsQuestionnaire, componentMibList, processes, processArtifact); - - Optional zipByteArrayInputStream = candidateService - .fetchZipFileByteArrayInputStream(vspDetails.getId(), candidateData, null, - OnboardingTypesEnum.CSAR, errors); - - orchestrationUtil.deleteUploadDataAndContent(vspDetails.getId(), vspDetails.getVersion()); - zipByteArrayInputStream.ifPresent(byteArrayInputStream -> orchestrationUtil - .saveUploadData(vspDetails, candidateData, byteArrayInputStream, - fileContentHandler, tree)); - - ETSIService etsiService = new ETSIServiceImpl(); - ToscaServiceModel toscaServiceModel; - if (etsiService.isSol004WithToscaMetaDirectory(fileContentHandler)) { - if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) { - fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getOriginalFileName() + - EXT_SEPARATOR + candidateData.getOriginalFileSuffix(), candidateData.getOriginalFileContentData().array()); - } else { - fileContentHandler.addFile(SDC_ONBOARDED_PACKAGE_DIR + candidateData.getFileName() + - EXT_SEPARATOR + candidateData.getFileSuffix(), candidateData.getContentData().array()); - } - final ResourceTypeEnum resourceType = etsiService.getResourceType(fileContentHandler); - toscaServiceModel = instantiateToscaConverterFor(resourceType).convert(fileContentHandler); - } else { - toscaServiceModel = new ToscaConverterImpl().convert(fileContentHandler); + private AbstractToscaSolConverter instantiateToscaConverterFor(ResourceTypeEnum resourceType) { + if (resourceType == ResourceTypeEnum.PNF) { + return new ToscaSolModelDrivenConverterPnf(); + } + // default is VF + return new ToscaSolConverterVnf(); } - orchestrationUtil.saveServiceModel(vspDetails.getId(), - vspDetails.getVersion(), toscaServiceModel, - toscaServiceModel); - candidateService - .deleteOrchestrationTemplateCandidate(vspDetails.getId(), vspDetails.getVersion()); - } - private AbstractToscaSolConverter instantiateToscaConverterFor(ResourceTypeEnum resourceType) { - if (resourceType == ResourceTypeEnum.PNF) { - return new ToscaSolModelDrivenConverterPnf(); + private void addFiles(FileContentHandler fileContentHandler) { + for (Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) { + toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue()); + } } - // default is VF - return new ToscaSolConverterVnf(); - } - private void addFiles(FileContentHandler fileContentHandler) { - for (Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) { - toscaTreeManager.addFile(fileEntry.getKey(), fileEntry.getValue()); + private Map> validateCsar(FileContentHandler fileContentHandler) { + Map> errors = new HashMap<>(); + addFiles(fileContentHandler); + toscaTreeManager.createTree(); + toscaTreeManager.addErrors(errors); + //todo - add tosca validation here to the existing validation framework + return errors; } - } - - private Map> validateCsar(FileContentHandler fileContentHandler) { - Map> errors = new HashMap<>(); - addFiles(fileContentHandler); - toscaTreeManager.createTree(); - toscaTreeManager.addErrors(errors); - //todo - add tosca validation here to the existing validation framework - return errors; - } - private boolean isValid(Map> errors) { - return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors)); - } + private boolean isValid(Map> errors) { + return MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors)); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessHandler.java index c775ac2c84..ae555b78a0 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessHandler.java @@ -13,10 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; - import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; @@ -24,6 +22,5 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateAction @FunctionalInterface public interface OrchestrationTemplateProcessHandler { - OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData); + OrchestrationTemplateActionResponse process(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData); } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessZipHandler.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessZipHandler.java index 2d18a62122..5f18cb2faa 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessZipHandler.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/impl/orchestration/process/OrchestrationTemplateProcessZipHandler.java @@ -14,9 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.process; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.translator.datatypes.TranslatorOutput; @@ -37,7 +46,11 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.validation.util.ValidationManagerUtil; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; import org.openecomp.sdc.vendorsoftwareproduct.impl.orchestration.OrchestrationUtil; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; @@ -47,157 +60,119 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStru import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.*; - public class OrchestrationTemplateProcessZipHandler implements OrchestrationTemplateProcessHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessZipHandler.class); - private final CandidateService candidateService = - CandidateServiceFactory.getInstance().createInterface(); - - @Override - public OrchestrationTemplateActionResponse process(VspDetails vspDetails, - OrchestrationTemplateCandidateData candidateData) { - String vspId = vspDetails.getId(); - Version version = vspDetails.getVersion(); - OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); - UploadFileResponse uploadFileResponse = new UploadFileResponse(); - Optional fileContent = OrchestrationUtil - .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, - candidateData.getContentData().array()); - if (!fileContent.isPresent()) { - response.addStructureErrors(uploadFileResponse.getErrors()); - return response; - } - - Map> uploadErrors = uploadFileResponse.getErrors(); - FileContentHandler fileContentMap = fileContent.get(); - try (InputStream zipFileManifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { - addDummyHeatBase(zipFileManifest ,fileContentMap); - } catch (Exception e) { - LOGGER.error("Invalid package content", e); - } - FilesDataStructure structure = - JsonUtil.json2Object(candidateData.getFilesDataStructure(), FilesDataStructure.class); - - if (CollectionUtils.isNotEmpty(structure.getUnassigned())) { - response.addErrorMessageToMap(SdcCommon.UPLOAD_FILE, - Messages.FOUND_UNASSIGNED_FILES.getErrorMessage(), ErrorLevel.ERROR); - return response; - } - - - ManifestContent zipManifestFile = readManifestFromZip(fileContentMap); - String manifest = null; - if (zipManifestFile == null) { - manifest = candidateService.createManifest(vspDetails, structure); - } else { - manifest = candidateService.createManifestFromExisting(vspDetails, structure, zipManifestFile); + private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateProcessZipHandler.class); + private final CandidateService candidateService = CandidateServiceFactory.getInstance().createInterface(); + + @Override + public OrchestrationTemplateActionResponse process(VspDetails vspDetails, OrchestrationTemplateCandidateData candidateData) { + String vspId = vspDetails.getId(); + Version version = vspDetails.getVersion(); + OrchestrationTemplateActionResponse response = new OrchestrationTemplateActionResponse(); + UploadFileResponse uploadFileResponse = new UploadFileResponse(); + Optional fileContent = OrchestrationUtil + .getFileContentMap(OnboardingTypesEnum.ZIP, uploadFileResponse, candidateData.getContentData().array()); + if (!fileContent.isPresent()) { + response.addStructureErrors(uploadFileResponse.getErrors()); + return response; + } + Map> uploadErrors = uploadFileResponse.getErrors(); + FileContentHandler fileContentMap = fileContent.get(); + try (InputStream zipFileManifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + addDummyHeatBase(zipFileManifest, fileContentMap); + } catch (Exception e) { + LOGGER.error("Invalid package content", e); + } + FilesDataStructure structure = JsonUtil.json2Object(candidateData.getFilesDataStructure(), FilesDataStructure.class); + if (CollectionUtils.isNotEmpty(structure.getUnassigned())) { + response.addErrorMessageToMap(SdcCommon.UPLOAD_FILE, Messages.FOUND_UNASSIGNED_FILES.getErrorMessage(), ErrorLevel.ERROR); + return response; + } + ManifestContent zipManifestFile = readManifestFromZip(fileContentMap); + String manifest = null; + if (zipManifestFile == null) { + manifest = candidateService.createManifest(vspDetails, structure); + } else { + manifest = candidateService.createManifestFromExisting(vspDetails, structure, zipManifestFile); + } + fileContentMap.addFile(SdcCommon.MANIFEST_NAME, manifest.getBytes()); + Optional zipByteArrayInputStream = candidateService + .fetchZipFileByteArrayInputStream(vspId, candidateData, manifest, OnboardingTypesEnum.ZIP, uploadErrors); + if (!zipByteArrayInputStream.isPresent()) { + return response; + } + HeatStructureTree tree = createAndValidateHeatTree(response, fileContentMap); + Map> errors = getErrors(response); + if (MapUtils.isNotEmpty(errors)) { + response.addStructureErrors(errors); + candidateService.updateValidationData(vspId, version, new ValidationStructureList(tree)); + return response; + } + Map componentsQuestionnaire = new HashMap<>(); + Map> componentNicsQuestionnaire = new HashMap<>(); + Map> componentMibList = new HashMap<>(); + Map> processes = new HashMap<>(); + Map processArtifact = new HashMap<>(); + OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); + Map vspComponentIdNameInfoBeforeProcess = orchestrationUtil.getVspComponentIdNameInfo(vspId, version); + Collection componentDependenciesBeforeDelete = orchestrationUtil + .getComponentDependenciesBeforeDelete(vspId, version); + orchestrationUtil + .backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQuestionnaire, componentNicsQuestionnaire, componentMibList, + processes, processArtifact); + orchestrationUtil.deleteUploadDataAndContent(vspId, version); + orchestrationUtil.saveUploadData(vspDetails, candidateData, zipByteArrayInputStream.get(), fileContentMap, tree); + TranslatorOutput translatorOutput = HeatToToscaUtil.loadAndTranslateTemplateData(fileContentMap); + ToscaServiceModel toscaServiceModel = translatorOutput.getToscaServiceModel(); + orchestrationUtil.saveServiceModel(vspId, version, translatorOutput.getNonUnifiedToscaServiceModel(), toscaServiceModel); + orchestrationUtil + .retainComponentQuestionnaireData(vspId, version, componentsQuestionnaire, componentNicsQuestionnaire, componentMibList, processes, + processArtifact); + orchestrationUtil.updateVspComponentDependencies(vspId, version, vspComponentIdNameInfoBeforeProcess, componentDependenciesBeforeDelete); + uploadFileResponse.addStructureErrors(uploadErrors); + candidateService.deleteOrchestrationTemplateCandidate(vspId, version); + return response; } - fileContentMap.addFile(SdcCommon.MANIFEST_NAME, manifest.getBytes()); - Optional zipByteArrayInputStream = candidateService - .fetchZipFileByteArrayInputStream( - vspId, candidateData, manifest, OnboardingTypesEnum.ZIP, uploadErrors); - if (!zipByteArrayInputStream.isPresent()) { - return response; + private ManifestContent readManifestFromZip(FileContentHandler fileContentMap) { + ManifestContent zipManifestFile = null; + try (InputStream zipFileManifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + zipManifestFile = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); + } catch (Exception e) { + LOGGER.error("Invalid package content", e); + } + return zipManifestFile; } - HeatStructureTree tree = createAndValidateHeatTree(response, fileContentMap); - Map> errors = getErrors(response); - if (MapUtils.isNotEmpty(errors)) { - response.addStructureErrors(errors); - candidateService.updateValidationData(vspId, version, new ValidationStructureList(tree)); - return response; + private FileContentHandler addDummyHeatBase(InputStream zipFileManifest, FileContentHandler fileContentMap) { + ManifestContent manifestContent = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); + for (FileData fileData : manifestContent.getData()) { + if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { + String filePath = new File("").getAbsolutePath() + "/resources"; + File envFilePath = new File(filePath + "/base_template.env"); + File baseFilePath = new File(filePath + "/base_template.yaml"); + try (InputStream envStream = new FileInputStream(envFilePath); InputStream baseStream = new FileInputStream(baseFilePath);) { + fileContentMap.addFile("base_template_dummy_ignore.env", envStream); + fileContentMap.addFile("base_template_dummy_ignore.yaml", baseStream); + } catch (Exception e) { + LOGGER.error("File not found error {}", e); + } + } + } + return fileContentMap; } - Map componentsQuestionnaire = new HashMap<>(); - Map> componentNicsQuestionnaire = new HashMap<>(); - Map> componentMibList = new HashMap<>(); - Map> processes = new HashMap<>(); - Map processArtifact = new HashMap<>(); - - OrchestrationUtil orchestrationUtil = new OrchestrationUtil(); - Map vspComponentIdNameInfoBeforeProcess = - orchestrationUtil.getVspComponentIdNameInfo(vspId, version); - Collection componentDependenciesBeforeDelete = - orchestrationUtil.getComponentDependenciesBeforeDelete(vspId, version); - orchestrationUtil - .backupComponentsQuestionnaireBeforeDelete(vspId, version, componentsQuestionnaire, - componentNicsQuestionnaire, componentMibList, processes, processArtifact); - orchestrationUtil.deleteUploadDataAndContent(vspId, version); - orchestrationUtil - .saveUploadData(vspDetails, candidateData, zipByteArrayInputStream.get(), fileContentMap, - tree); - - TranslatorOutput translatorOutput = - HeatToToscaUtil.loadAndTranslateTemplateData(fileContentMap); - - ToscaServiceModel toscaServiceModel = translatorOutput.getToscaServiceModel(); - orchestrationUtil - .saveServiceModel(vspId, version, translatorOutput.getNonUnifiedToscaServiceModel(), - toscaServiceModel); - orchestrationUtil.retainComponentQuestionnaireData(vspId, version, componentsQuestionnaire, - componentNicsQuestionnaire, componentMibList, processes, processArtifact); - orchestrationUtil.updateVspComponentDependencies(vspId, version, - vspComponentIdNameInfoBeforeProcess, componentDependenciesBeforeDelete); - - uploadFileResponse.addStructureErrors(uploadErrors); - candidateService.deleteOrchestrationTemplateCandidate(vspId, version); - return response; - } - - private ManifestContent readManifestFromZip(FileContentHandler fileContentMap) { - ManifestContent zipManifestFile = null; - try (InputStream zipFileManifest = fileContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { - zipManifestFile = JsonUtil.json2Object(zipFileManifest, ManifestContent.class); - } catch (Exception e) { - LOGGER.error("Invalid package content", e); + private Map> getErrors(OrchestrationTemplateActionResponse orchestrationTemplateActionResponse) { + Map> errors = MessageContainerUtil + .getMessageByLevel(ErrorLevel.ERROR, orchestrationTemplateActionResponse.getErrors()); + return MapUtils.isEmpty(errors) ? null : orchestrationTemplateActionResponse.getErrors(); } - return zipManifestFile; - } - private FileContentHandler addDummyHeatBase(InputStream zipFileManifest, FileContentHandler fileContentMap) { - ManifestContent manifestContent = - JsonUtil.json2Object(zipFileManifest, ManifestContent.class); - for (FileData fileData : manifestContent.getData()) { - if (Objects.nonNull(fileData.getType()) && - fileData.getType().equals(FileData.Type.HELM) && fileData.getBase()) { - String filePath = new File("").getAbsolutePath() + "/resources"; - File envFilePath = new File(filePath + "/base_template.env"); - File baseFilePath = new File(filePath + "/base_template.yaml"); - try ( - InputStream envStream = new FileInputStream(envFilePath); - InputStream baseStream = new FileInputStream(baseFilePath);) { - fileContentMap.addFile("base_template_dummy_ignore.env", envStream); - fileContentMap.addFile("base_template_dummy_ignore.yaml", baseStream); - } catch (Exception e) { - LOGGER.error("File not found error {}", e); - } - } + private HeatStructureTree createAndValidateHeatTree(OrchestrationTemplateActionResponse response, FileContentHandler fileContentMap) { + VendorSoftwareProductUtils.addFileNamesToUploadFileResponse(fileContentMap, response); + Map> validationErrors = ValidationManagerUtil.initValidationManager(fileContentMap).validate(); + response.getErrors().putAll(validationErrors); + return OrchestrationUtil.createHeatTree(fileContentMap, validationErrors); } - return fileContentMap; - } - - private Map> getErrors(OrchestrationTemplateActionResponse - orchestrationTemplateActionResponse) { - Map> errors = - MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, - orchestrationTemplateActionResponse.getErrors()); - return MapUtils.isEmpty(errors) ? null : orchestrationTemplateActionResponse.getErrors(); - } - - private HeatStructureTree createAndValidateHeatTree(OrchestrationTemplateActionResponse response, - FileContentHandler fileContentMap) { - VendorSoftwareProductUtils.addFileNamesToUploadFileResponse(fileContentMap, response); - Map> validationErrors = - ValidationManagerUtil.initValidationManager(fileContentMap).validate(); - response.getErrors().putAll(validationErrors); - - return OrchestrationUtil.createHeatTree(fileContentMap, validationErrors); - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/security/SecurityManager.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/security/SecurityManager.java index 006af058bb..d60b54b5e1 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/security/SecurityManager.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/security/SecurityManager.java @@ -20,8 +20,13 @@ package org.openecomp.sdc.vendorsoftwareproduct.security; import com.google.common.collect.ImmutableSet; - -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; @@ -41,12 +46,11 @@ import java.security.cert.X509CertSelector; import java.security.cert.X509Certificate; import java.util.Collection; import java.util.HashSet; -import java.util.function.Predicate; import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.Set; - import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cms.CMSException; @@ -62,16 +66,14 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; /** - * This is temporary solution. When AAF provides functionality for verifying trustedCertificates, this class should be - * reviewed Class is responsible for providing root trustedCertificates from configured location in onboarding - * container. + * This is temporary solution. When AAF provides functionality for verifying trustedCertificates, this class should be reviewed Class is responsible + * for providing root trustedCertificates from configured location in onboarding container. */ public class SecurityManager { private static final String CERTIFICATE_DEFAULT_LOCATION = "cert"; public static final Set ALLOWED_SIGNATURE_EXTENSIONS = ImmutableSet.of("cms"); public static final Set ALLOWED_CERTIFICATE_EXTENSIONS = ImmutableSet.of("cert", "crt"); - private Logger logger = LoggerFactory.getLogger(SecurityManager.class); private Set trustedCertificates = new HashSet<>(); private Set trustedCertificatesFromPackage = new HashSet<>(); @@ -87,7 +89,6 @@ public class SecurityManager { certificateDirectory = this.getcertDirectory(System.getenv("SDC_CERT_DIR")); } - // Package level constructor use in tests to avoid power mock SecurityManager(String sdcCertDir) { certificateDirectory = this.getcertDirectory(sdcCertDir); @@ -123,8 +124,7 @@ public class SecurityManager { processCertificateDir(); } if (!trustedCertificatesFromPackage.isEmpty()) { - return Stream.concat(trustedCertificatesFromPackage.stream(), trustedCertificates.stream()) - .collect(Collectors.toUnmodifiableSet()); + return Stream.concat(trustedCertificatesFromPackage.stream(), trustedCertificates.stream()).collect(Collectors.toUnmodifiableSet()); } return ImmutableSet.copyOf(trustedCertificates); } @@ -145,10 +145,10 @@ public class SecurityManager { * @return true if signature verified * @throws SecurityManagerException */ - public boolean verifySignedData(final byte[] messageSyntaxSignature, final byte[] packageCert, - final byte[] innerPackageFile) throws SecurityManagerException { - try (ByteArrayInputStream signatureStream = new ByteArrayInputStream(messageSyntaxSignature); - final PEMParser pemParser = new PEMParser(new InputStreamReader(signatureStream))) { + public boolean verifySignedData(final byte[] messageSyntaxSignature, final byte[] packageCert, final byte[] innerPackageFile) + throws SecurityManagerException { + try (ByteArrayInputStream signatureStream = new ByteArrayInputStream(messageSyntaxSignature); final PEMParser pemParser = new PEMParser( + new InputStreamReader(signatureStream))) { final Object parsedObject = pemParser.readObject(); if (!(parsedObject instanceof ContentInfo)) { throw new SecurityManagerException("Signature is not recognized"); @@ -156,26 +156,23 @@ public class SecurityManager { final ContentInfo signature = ContentInfo.getInstance(parsedObject); final CMSTypedData signedContent = new CMSProcessableByteArray(innerPackageFile); final CMSSignedData signedData = new CMSSignedData(signedContent, signature); - final Collection signers = signedData.getSignerInfos().getSigners(); final SignerInformation firstSigner = signers.iterator().next(); final X509Certificate cert; Collection certs; if (packageCert == null) { certs = signedData.getCertificates().getMatches(null); - cert = readSignCert(certs, firstSigner).orElseThrow(() -> new SecurityManagerException( - "No certificate found in cms signature that should contain one!")); + cert = readSignCert(certs, firstSigner) + .orElseThrow(() -> new SecurityManagerException("No certificate found in cms signature that should contain one!")); } else { certs = parseCertsFromPem(packageCert); - cert = readSignCert(certs, firstSigner).orElseThrow(() -> new SecurityManagerException( - "No matching certificate found in certificate file that should contain one!")); + cert = readSignCert(certs, firstSigner) + .orElseThrow(() -> new SecurityManagerException("No matching certificate found in certificate file that should contain one!")); } trustedCertificatesFromPackage = readTrustedCerts(certs, firstSigner); - if (verifyCertificate(cert, getTrustedCertificates()) == null) { return false; } - return firstSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert)); } catch (OperatorCreationException | IOException | CMSException e) { logger.error(e.getMessage(), e); @@ -186,18 +183,12 @@ public class SecurityManager { } private Optional readSignCert(final Collection certs, final SignerInformation firstSigner) { - return certs.stream() - .filter(crt -> firstSigner.getSID().match(crt)) - .findAny() - .map(this::loadCertificate); + return certs.stream().filter(crt -> firstSigner.getSID().match(crt)).findAny().map(this::loadCertificate); } private Set readTrustedCerts(final Collection certs, final SignerInformation firstSigner) { - return certs.stream() - .filter(crt -> !firstSigner.getSID().match(crt)) - .map(this::loadCertificate) - .filter(Predicate.not(this::isSelfSigned)) - .collect(Collectors.toSet()); + return certs.stream().filter(crt -> !firstSigner.getSID().match(crt)).map(this::loadCertificate).filter(Predicate.not(this::isSelfSigned)) + .collect(Collectors.toSet()); } private Set parseCertsFromPem(final byte[] packageCert) throws IOException { @@ -219,7 +210,6 @@ public class SecurityManager { logger.error("Issue with certificate directory, check if exists!"); return; } - File[] files = certificateDirectory.listFiles(); if (files == null) { logger.error("Certificate directory is empty!"); @@ -238,10 +228,10 @@ public class SecurityManager { return new File(certDirLocation); } - private X509Certificate loadCertificate(File certFile) throws SecurityManagerException { + private X509Certificate loadCertificate(File certFile) throws SecurityManagerException { try (FileInputStream fi = new FileInputStream(certFile)) { return loadCertificateFactory(fi); - } catch(IOException e) { + } catch (IOException e) { throw new SecurityManagerException("Error during loading Certificate from file!", e); } } @@ -263,21 +253,17 @@ public class SecurityManager { } } - private PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, - Set additionalCerts) - throws GeneralSecurityException, SecurityManagerException { + private PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, Set additionalCerts) + throws GeneralSecurityException, SecurityManagerException { if (null == cert) { throw new SecurityManagerException("The certificate is empty!"); } - if (isExpired(cert)) { throw new SecurityManagerException("The certificate expired on: " + cert.getNotAfter()); } - if (isSelfSigned(cert)) { throw new SecurityManagerException("The certificate is self-signed."); } - Set trustedRootCerts = new HashSet<>(); Set intermediateCerts = new HashSet<>(); for (X509Certificate additionalCert : additionalCerts) { @@ -287,25 +273,19 @@ public class SecurityManager { intermediateCerts.add(additionalCert); } } - return verifyCertificate(cert, trustedRootCerts, intermediateCerts); } - private PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, - Set allTrustedRootCerts, - Set allIntermediateCerts) - throws GeneralSecurityException { - + private PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, Set allTrustedRootCerts, + Set allIntermediateCerts) throws GeneralSecurityException { // Create the selector that specifies the starting certificate X509CertSelector selector = new X509CertSelector(); selector.setCertificate(cert); - // Create the trust anchors (set of root CA certificates) Set trustAnchors = new HashSet<>(); for (X509Certificate trustedRootCert : allTrustedRootCerts) { trustAnchors.add(new TrustAnchor(trustedRootCert, null)); } - // Configure the PKIX certificate builder algorithm parameters PKIXBuilderParameters pkixParams; try { @@ -313,25 +293,20 @@ public class SecurityManager { } catch (InvalidAlgorithmParameterException ex) { throw new InvalidAlgorithmParameterException("No root CA has been found for this certificate", ex); } - // Not supporting CRL checks for now pkixParams.setRevocationEnabled(false); - Set certSet = new HashSet<>(); certSet.add(cert); pkixParams.addCertStore(createCertStore(certSet)); pkixParams.addCertStore(createCertStore(allIntermediateCerts)); pkixParams.addCertStore(createCertStore(allTrustedRootCerts)); - - CertPathBuilder builder = CertPathBuilder - .getInstance(CertPathBuilder.getDefaultType(), BouncyCastleProvider.PROVIDER_NAME); + CertPathBuilder builder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType(), BouncyCastleProvider.PROVIDER_NAME); return (PKIXCertPathBuilderResult) builder.build(pkixParams); } - private CertStore createCertStore(Set certificateSet) throws InvalidAlgorithmParameterException, - NoSuchAlgorithmException, NoSuchProviderException { - return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certificateSet), - BouncyCastleProvider.PROVIDER_NAME); + private CertStore createCertStore(Set certificateSet) + throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { + return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certificateSet), BouncyCastleProvider.PROVIDER_NAME); } private boolean isExpired(X509Certificate cert) { diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ComponentValidationResult.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ComponentValidationResult.java index a8d528c503..ed38b61e81 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ComponentValidationResult.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ComponentValidationResult.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; - import java.util.Set; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; public class ComponentValidationResult { - private boolean valid; - private Set validationData; - public ComponentValidationResult(Set validationData) { - this.validationData = validationData; - valid = validationData == null; - } + private boolean valid; + private Set validationData; + + public ComponentValidationResult(Set validationData) { + this.validationData = validationData; + valid = validationData == null; + } - public boolean isValid() { - return valid; - } + public boolean isValid() { + return valid; + } - public Set getValidationData() { - return validationData; - } + public Set getValidationData() { + return validationData; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CompositionEntityResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CompositionEntityResponse.java index 24d28b198a..90518b93d0 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CompositionEntityResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CompositionEntityResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionDataEntity; public class CompositionEntityResponse { - private String id; - private String schema; - private T data; + private String id; + private String schema; + private T data; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getSchema() { - return schema; - } + public String getSchema() { + return schema; + } - public void setSchema(String schema) { - this.schema = schema; - } + public void setSchema(String schema) { + this.schema = schema; + } - public T getData() { - return data; - } + public T getData() { + return data; + } - public void setData(T data) { - this.data = data; - } + public void setData(T data) { + this.data = data; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ConfigConstants.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ConfigConstants.java index 640d0c9bbc..35b6851a9b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ConfigConstants.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ConfigConstants.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.types; public class ConfigConstants { - public static final String NAMESPACE = "Orchestration"; - public static final String PROCESS_IMPL_KEY = "process_impl"; - private ConfigConstants(){ + public static final String NAMESPACE = "Orchestration"; + public static final String PROCESS_IMPL_KEY = "process_impl"; - } + private ConfigConstants() { + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/DeploymentFlavorValidationResult.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/DeploymentFlavorValidationResult.java index bc24103779..5aca10294e 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/DeploymentFlavorValidationResult.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/DeploymentFlavorValidationResult.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; - import java.util.Set; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; public class DeploymentFlavorValidationResult { - private boolean valid; - private Set validationData; - public DeploymentFlavorValidationResult(Set validationData){ - this.validationData = validationData; - valid = validationData == null; - } + private boolean valid; + private Set validationData; - public boolean isValid() { - return valid; - } + public DeploymentFlavorValidationResult(Set validationData) { + this.validationData = validationData; + valid = validationData == null; + } - public Set getValidationData() { - return validationData; - } + public boolean isValid() { + return valid; + } + public Set getValidationData() { + return validationData; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/LicensingData.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/LicensingData.java index e5b8f7ff66..5911701bea 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/LicensingData.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/LicensingData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.util.List; @@ -27,22 +26,22 @@ import java.util.List; */ public class LicensingData { - private String licenseAgreement; - private List featureGroups; + private String licenseAgreement; + private List featureGroups; - public String getLicenseAgreement() { - return licenseAgreement; - } + public String getLicenseAgreement() { + return licenseAgreement; + } - public void setLicenseAgreement(String licenseAgreement) { - this.licenseAgreement = licenseAgreement; - } + public void setLicenseAgreement(String licenseAgreement) { + this.licenseAgreement = licenseAgreement; + } - public List getFeatureGroups() { - return featureGroups; - } + public List getFeatureGroups() { + return featureGroups; + } - public void setFeatureGroups(List featureGroups) { - this.featureGroups = featureGroups; - } + public void setFeatureGroups(List featureGroups) { + this.featureGroups = featureGroups; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ListComputeResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ListComputeResponse.java index 21e0de7f17..226f0aeede 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ListComputeResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ListComputeResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; public class ListComputeResponse { - private ComputeEntity computeEntity; - private boolean associatedWithDeploymentFlavor; - - public boolean isAssociatedWithDeploymentFlavor() { - return associatedWithDeploymentFlavor; - } - - public void setAssociatedWithDeploymentFlavor(boolean associatedWithDeploymentFlavor) { - this.associatedWithDeploymentFlavor = associatedWithDeploymentFlavor; - } + private ComputeEntity computeEntity; + private boolean associatedWithDeploymentFlavor; - public ComputeEntity getComputeEntity() { - return computeEntity; - } + public boolean isAssociatedWithDeploymentFlavor() { + return associatedWithDeploymentFlavor; + } - public void setComputeEntity( - ComputeEntity computeEntity) { - this.computeEntity = computeEntity; - } + public void setAssociatedWithDeploymentFlavor(boolean associatedWithDeploymentFlavor) { + this.associatedWithDeploymentFlavor = associatedWithDeploymentFlavor; + } + public ComputeEntity getComputeEntity() { + return computeEntity; + } + public void setComputeEntity(ComputeEntity computeEntity) { + this.computeEntity = computeEntity; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackage.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackage.java index 1551cd8a1d..fc5306e892 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackage.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackage.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.nio.ByteBuffer; @@ -43,8 +42,7 @@ public class OnboardPackage { this.fileContentHandler = fileContentHandler; } - public OnboardPackage(final String filename, final String fileExtension, final ByteBuffer fileContent) - throws OnboardPackageException { + public OnboardPackage(final String filename, final String fileExtension, final ByteBuffer fileContent) throws OnboardPackageException { this.filename = filename; this.fileExtension = fileExtension; this.fileContent = fileContent; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackageInfo.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackageInfo.java index 6c35bd67d9..a78185e89f 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackageInfo.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardPackageInfo.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.nio.ByteBuffer; @@ -35,20 +34,17 @@ public class OnboardPackageInfo { this(onboardPackage, onboardPackage, packageType); } - public OnboardPackageInfo(final OnboardPackage originalOnboardPackage, - final OnboardPackage onboardPackage, final OnboardingTypesEnum packageType) { + public OnboardPackageInfo(final OnboardPackage originalOnboardPackage, final OnboardPackage onboardPackage, + final OnboardingTypesEnum packageType) { this.packageType = packageType; this.originalOnboardPackage = originalOnboardPackage; this.onboardPackage = onboardPackage; } - public OnboardPackageInfo(final String filename, - final String fileExtension, - final ByteBuffer fileContent, - final OnboardingTypesEnum packageType) throws OnboardPackageException { + public OnboardPackageInfo(final String filename, final String fileExtension, final ByteBuffer fileContent, final OnboardingTypesEnum packageType) + throws OnboardPackageException { this.packageType = packageType; originalOnboardPackage = new OnboardPackage(filename, fileExtension, fileContent); this.onboardPackage = originalOnboardPackage; } - -} \ No newline at end of file +} diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardSignedPackage.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardSignedPackage.java index a1436fcd2d..e208610337 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardSignedPackage.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OnboardSignedPackage.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.nio.ByteBuffer; @@ -27,13 +26,14 @@ import org.openecomp.core.utilities.file.FileContentHandler; @Getter public class OnboardSignedPackage extends OnboardPackage { + private String signatureFilePath; private String internalPackageFilePath; private String certificateFilePath; public OnboardSignedPackage(final String filename, final String fileExtension, final ByteBuffer fileContent, - final FileContentHandler fileContentHandler, final String signatureFilePath, - final String internalPackageFilePath, final String certificateFilePath) { + final FileContentHandler fileContentHandler, final String signatureFilePath, final String internalPackageFilePath, + final String certificateFilePath) { super(filename, fileExtension, fileContent, fileContentHandler); this.signatureFilePath = signatureFilePath; this.internalPackageFilePath = internalPackageFilePath; diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OrchestrationTemplateActionResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OrchestrationTemplateActionResponse.java index cca20351bd..bdda2a22bd 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OrchestrationTemplateActionResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/OrchestrationTemplateActionResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,102 +17,95 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public class OrchestrationTemplateActionResponse { - private List fileNames; - private Map> errors = new HashMap<>(); - private UploadFileStatus status = UploadFileStatus.Success; - public UploadFileStatus getStatus() { - return status; - } + private List fileNames; + private Map> errors = new HashMap<>(); + private UploadFileStatus status = UploadFileStatus.Success; - public void setStatus(UploadFileStatus status) { - this.status = status; - } - - public List getFileNames() { - return fileNames; - } - - public void setFileNames(List fileNames) { - this.fileNames = fileNames; - } + public UploadFileStatus getStatus() { + return status; + } - public void addNewFileToList(String filename) { - this.fileNames.add(filename); - } + public void setStatus(UploadFileStatus status) { + this.status = status; + } - public void removeFileFromList(String toRemove) { - this.fileNames.remove(toRemove); - } + public List getFileNames() { + return fileNames; + } - /** - * Add structure errors. - * - * @param errorsByFileName the errors by file name - */ - public void addStructureErrors(Map> errorsByFileName) { - if (errorsByFileName == null) { - return; + public void setFileNames(List fileNames) { + this.fileNames = fileNames; } - errors.putAll(errorsByFileName); + public void addNewFileToList(String filename) { + this.fileNames.add(filename); + } - if (status == UploadFileStatus.Failure) { - return; + public void removeFileFromList(String toRemove) { + this.fileNames.remove(toRemove); } - for (Map.Entry> entry : errorsByFileName.entrySet()) { - for (ErrorMessage errorMessage : entry.getValue()) { - if (errorMessage.getLevel() == ErrorLevel.ERROR) { - status = UploadFileStatus.Failure; - return; + + /** + * Add structure errors. + * + * @param errorsByFileName the errors by file name + */ + public void addStructureErrors(Map> errorsByFileName) { + if (errorsByFileName == null) { + return; + } + errors.putAll(errorsByFileName); + if (status == UploadFileStatus.Failure) { + return; + } + for (Map.Entry> entry : errorsByFileName.entrySet()) { + for (ErrorMessage errorMessage : entry.getValue()) { + if (errorMessage.getLevel() == ErrorLevel.ERROR) { + status = UploadFileStatus.Failure; + return; + } + } } - } } - } - /** - * Add error message to map. - * - * @param key the key - * @param error the error - * @param level the level - */ - public void addErrorMessageToMap(String key, String error, ErrorLevel level) { - ErrorMessage errorMessage = new ErrorMessage(level, error); - List errorMessages = getErrorList(key); - - errorMessages.add(errorMessage); - this.errors.put(key, errorMessages); - - if (level.equals(ErrorLevel.ERROR)) { - status = UploadFileStatus.Failure; + /** + * Add error message to map. + * + * @param key the key + * @param error the error + * @param level the level + */ + public void addErrorMessageToMap(String key, String error, ErrorLevel level) { + ErrorMessage errorMessage = new ErrorMessage(level, error); + List errorMessages = getErrorList(key); + errorMessages.add(errorMessage); + this.errors.put(key, errorMessages); + if (level.equals(ErrorLevel.ERROR)) { + status = UploadFileStatus.Failure; + } } - } - private List getErrorList(String key) { - List errorMessages = this.errors.get(key); - if (CollectionUtils.isEmpty(errorMessages)) { - errorMessages = new ArrayList<>(); + private List getErrorList(String key) { + List errorMessages = this.errors.get(key); + if (CollectionUtils.isEmpty(errorMessages)) { + errorMessages = new ArrayList<>(); + } + return errorMessages; } - return errorMessages; - } - - public Map> getErrors() { - return errors; - } + public Map> getErrors() { + return errors; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireResponse.java index 3e7ef9f744..c0447c7cae 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,37 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import org.openecomp.sdc.datatypes.error.ErrorMessage; public class QuestionnaireResponse { - private String schema; - private String data; - private ErrorMessage errorMessage; - public String getSchema() { - return schema; - } + private String schema; + private String data; + private ErrorMessage errorMessage; + + public String getSchema() { + return schema; + } - public void setSchema(String schema) { - this.schema = schema; - } + public void setSchema(String schema) { + this.schema = schema; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ErrorMessage getErrorMessage() { - return errorMessage; - } + public ErrorMessage getErrorMessage() { + return errorMessage; + } - public void setErrorMessage(ErrorMessage errorMessage) { - this.errorMessage = errorMessage; - } + public void setErrorMessage(ErrorMessage errorMessage) { + this.errorMessage = errorMessage; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireValidationResult.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireValidationResult.java index 2599d4723d..9f2e9bd2ec 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireValidationResult.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/QuestionnaireValidationResult.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; - import java.util.Set; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityValidationData; public class QuestionnaireValidationResult { - private boolean valid; - private Set validationData; - public QuestionnaireValidationResult(Set validationData) { - this.validationData = validationData; - valid = validationData == null; - } + private boolean valid; + private Set validationData; + + public QuestionnaireValidationResult(Set validationData) { + this.validationData = validationData; + valid = validationData == null; + } - public boolean isValid() { - return valid; - } + public boolean isValid() { + return valid; + } - public Set getValidationData() { - return validationData; - } + public Set getValidationData() { + return validationData; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileResponse.java index 31bdf21884..0456692b71 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileResponse.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,101 +17,97 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; - -import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; /** * Created by TALIO on 4/27/2016. */ public class UploadFileResponse { - private Map> errors = new HashMap<>(); - private UploadFileStatus status = UploadFileStatus.Success; - private OnboardingTypesEnum onboardingType; - private String networkPackageName; - - public UploadFileStatus getStatus() { - return status; - } - - public void setStatus(UploadFileStatus status) { - this.status = status; - } - public OnboardingTypesEnum getOnboardingType() { - return onboardingType; - } + private Map> errors = new HashMap<>(); + private UploadFileStatus status = UploadFileStatus.Success; + private OnboardingTypesEnum onboardingType; + private String networkPackageName; - public void setOnboardingType(OnboardingTypesEnum onboardingTypesEnum) { - this.onboardingType = onboardingTypesEnum; - } - - public String getNetworkPackageName() { - return networkPackageName; - } + public UploadFileStatus getStatus() { + return status; + } - public void setNetworkPackageName(String networkPackageName) { - this.networkPackageName = networkPackageName; - } + public void setStatus(UploadFileStatus status) { + this.status = status; + } - /** - * Add structure error. - * - * @param fileName the file name - * @param errorMessage the error message - */ - public void addStructureError(String fileName, ErrorMessage errorMessage) { - List errorList = errors.get(fileName); - if (errorList == null) { - errorList = new ArrayList<>(); - errors.put(fileName, errorList); + public OnboardingTypesEnum getOnboardingType() { + return onboardingType; } - errorList.add(errorMessage); - if (ErrorLevel.ERROR.equals(errorMessage.getLevel())) { - status = UploadFileStatus.Failure; + + public void setOnboardingType(OnboardingTypesEnum onboardingTypesEnum) { + this.onboardingType = onboardingTypesEnum; } - } - /** - * Add structure errors. - * - * @param errorsByFileName the errors by file name - */ - public void addStructureErrors(Map> errorsByFileName) { - if (errorsByFileName == null) { - return; + public String getNetworkPackageName() { + return networkPackageName; } - errors.putAll(errorsByFileName); + public void setNetworkPackageName(String networkPackageName) { + this.networkPackageName = networkPackageName; + } - if (status == UploadFileStatus.Failure) { - return; + /** + * Add structure error. + * + * @param fileName the file name + * @param errorMessage the error message + */ + public void addStructureError(String fileName, ErrorMessage errorMessage) { + List errorList = errors.get(fileName); + if (errorList == null) { + errorList = new ArrayList<>(); + errors.put(fileName, errorList); + } + errorList.add(errorMessage); + if (ErrorLevel.ERROR.equals(errorMessage.getLevel())) { + status = UploadFileStatus.Failure; + } } - for (Map.Entry> entry : errorsByFileName.entrySet()) { - for (ErrorMessage errorMessage : entry.getValue()) { - if (errorMessage.getLevel() == ErrorLevel.ERROR) { - status = UploadFileStatus.Failure; - return; + + /** + * Add structure errors. + * + * @param errorsByFileName the errors by file name + */ + public void addStructureErrors(Map> errorsByFileName) { + if (errorsByFileName == null) { + return; + } + errors.putAll(errorsByFileName); + if (status == UploadFileStatus.Failure) { + return; + } + for (Map.Entry> entry : errorsByFileName.entrySet()) { + for (ErrorMessage errorMessage : entry.getValue()) { + if (errorMessage.getLevel() == ErrorLevel.ERROR) { + status = UploadFileStatus.Failure; + return; + } + } } - } } - } - public Map> getErrors() { - return errors; - } + public Map> getErrors() { + return errors; + } - public boolean hasErrors() { - return !MapUtils.isEmpty(errors); - } + public boolean hasErrors() { + return !MapUtils.isEmpty(errors); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStatus.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStatus.java index 2bd8d76a66..231111b0f9 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStatus.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; public enum UploadFileStatus { - Success, - Failure + Success, Failure } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStructure.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStructure.java index 525d627f4f..45a439fa61 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStructure.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/UploadFileStructure.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.util.List; @@ -27,17 +26,17 @@ import java.util.List; */ public class UploadFileStructure { - private List fileNames; + private List fileNames; - public List getFileNames() { - return fileNames; - } + public List getFileNames() { + return fileNames; + } - public void setFileNames(List fileNames) { - this.fileNames = fileNames; - } + public void setFileNames(List fileNames) { + this.fileNames = fileNames; + } - public void addNewFileToList(String filename) { - this.fileNames.add(filename); - } + public void addNewFileToList(String filename) { + this.fileNames.add(filename); + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ValidationResponse.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ValidationResponse.java index cab205c212..4ec6027c26 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ValidationResponse.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/ValidationResponse.java @@ -13,96 +13,92 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.types; +import java.util.Collection; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils; -import java.util.Collection; -import java.util.List; -import java.util.Map; - public class ValidationResponse { - private boolean valid = true; - private Collection vspErrors; - private Collection licensingDataErrors; - private Map> uploadDataErrors; - private QuestionnaireValidationResult questionnaireValidationResult; - public boolean isValid() { - return valid; - } + private boolean valid = true; + private Collection vspErrors; + private Collection licensingDataErrors; + private Map> uploadDataErrors; + private QuestionnaireValidationResult questionnaireValidationResult; - public Collection getVspErrors() { - return vspErrors; - } - - /** - * Sets vsp errors. - * @param vspErrors the vsp errors - */ - public void setVspErrors(Collection vspErrors) { - this.vspErrors = vspErrors; - if (CollectionUtils.isNotEmpty(vspErrors)) { - valid = false; + public boolean isValid() { + return valid; } - VendorSoftwareProductUtils.setErrorsIntoLogger(vspErrors); - } - + public Collection getVspErrors() { + return vspErrors; + } - public Collection getLicensingDataErrors() { - return licensingDataErrors; - } + /** + * Sets vsp errors. + * + * @param vspErrors the vsp errors + */ + public void setVspErrors(Collection vspErrors) { + this.vspErrors = vspErrors; + if (CollectionUtils.isNotEmpty(vspErrors)) { + valid = false; + } + VendorSoftwareProductUtils.setErrorsIntoLogger(vspErrors); + } - /** - * Sets licensing data errors. - * - * @param licensingDataErrors the licensing data errors - */ - public void setLicensingDataErrors(Collection licensingDataErrors) { - this.licensingDataErrors = licensingDataErrors; - if (CollectionUtils.isNotEmpty(licensingDataErrors)) { - valid = false; + public Collection getLicensingDataErrors() { + return licensingDataErrors; } - } - public Map> getUploadDataErrors() { - return uploadDataErrors; - } + /** + * Sets licensing data errors. + * + * @param licensingDataErrors the licensing data errors + */ + public void setLicensingDataErrors(Collection licensingDataErrors) { + this.licensingDataErrors = licensingDataErrors; + if (CollectionUtils.isNotEmpty(licensingDataErrors)) { + valid = false; + } + } - /** - * Sets upload data errors. - * @param uploadDataErrors the upload data errors - */ - public void setUploadDataErrors(Map> uploadDataErrors) { - this.uploadDataErrors = uploadDataErrors; - if (MapUtils.isNotEmpty(uploadDataErrors)) { - valid = false; + public Map> getUploadDataErrors() { + return uploadDataErrors; } - VendorSoftwareProductUtils - .setErrorsIntoLogger(uploadDataErrors); - } + /** + * Sets upload data errors. + * + * @param uploadDataErrors the upload data errors + */ + public void setUploadDataErrors(Map> uploadDataErrors) { + this.uploadDataErrors = uploadDataErrors; + if (MapUtils.isNotEmpty(uploadDataErrors)) { + valid = false; + } + VendorSoftwareProductUtils.setErrorsIntoLogger(uploadDataErrors); + } - public QuestionnaireValidationResult getQuestionnaireValidationResult() { - return questionnaireValidationResult; - } + public QuestionnaireValidationResult getQuestionnaireValidationResult() { + return questionnaireValidationResult; + } - /** - * Sets questionnaire validation result. - * - * @param questionnaireValidationResult the questionnaire validation result - */ - public void setQuestionnaireValidationResult( - QuestionnaireValidationResult questionnaireValidationResult) { - this.questionnaireValidationResult = questionnaireValidationResult; - if (questionnaireValidationResult != null && !questionnaireValidationResult.isValid()) { - valid = false; + /** + * Sets questionnaire validation result. + * + * @param questionnaireValidationResult the questionnaire validation result + */ + public void setQuestionnaireValidationResult(QuestionnaireValidationResult questionnaireValidationResult) { + this.questionnaireValidationResult = questionnaireValidationResult; + if (questionnaireValidationResult != null && !questionnaireValidationResult.isValid()) { + valid = false; + } } - } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/MonitoringUploadStatus.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/MonitoringUploadStatus.java index ad604e822e..ad6e5fb2ec 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/MonitoringUploadStatus.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/MonitoringUploadStatus.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; public class MonitoringUploadStatus { - private String snmpTrap; - private String snmpPoll; - private String vesEvent; - - - //todo 1802 tech debt story : refactor this to be a map of type-filename - - - public MonitoringUploadStatus(String snmpTrap, String snmpPoll) { - this.snmpTrap = snmpTrap; - this.snmpPoll = snmpPoll; - } - public MonitoringUploadStatus() { - } + private String snmpTrap; + private String snmpPoll; + private String vesEvent; - public String getSnmpTrap() { - return snmpTrap; - } + //todo 1802 tech debt story : refactor this to be a map of type-filename + public MonitoringUploadStatus(String snmpTrap, String snmpPoll) { + this.snmpTrap = snmpTrap; + this.snmpPoll = snmpPoll; + } - public void setSnmpTrap(String snmpTrap) { - this.snmpTrap = snmpTrap; - } + public MonitoringUploadStatus() { + } - public String getSnmpPoll() { - return snmpPoll; - } + public String getSnmpTrap() { + return snmpTrap; + } - public String getVesEvent() { - return vesEvent; - } + public void setSnmpTrap(String snmpTrap) { + this.snmpTrap = snmpTrap; + } - public void setVesEvent(String vesEvent) { - this.vesEvent = vesEvent; - } + public String getSnmpPoll() { + return snmpPoll; + } - public void setSnmpPoll(String snmpPoll) { - this.snmpPoll = snmpPoll; + public void setSnmpPoll(String snmpPoll) { + this.snmpPoll = snmpPoll; + } + public String getVesEvent() { + return vesEvent; + } - } + public void setVesEvent(String vesEvent) { + this.vesEvent = vesEvent; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/zusammen/ItemProperties.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/zusammen/ItemProperties.java index 03aad04e15..0bf3037e5b 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/zusammen/ItemProperties.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/zusammen/ItemProperties.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.types.zusammen; /** @@ -21,12 +20,12 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.zusammen; * @since February 16, 2017 */ public class ItemProperties { - public static final String TYPE = "type"; - public static final String CATEGORY = "category"; - public static final String VENDOR_NAME = "vendorName"; - public static final String VSP_ID = "vspId"; - private ItemProperties(){ + public static final String TYPE = "type"; + public static final String CATEGORY = "category"; + public static final String VENDOR_NAME = "vendorName"; + public static final String VSP_ID = "vspId"; - } + private ItemProperties() { + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ComponentDependencyTracker.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ComponentDependencyTracker.java index 39f04d67c6..8d6546f209 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ComponentDependencyTracker.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/ComponentDependencyTracker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.utils; import java.util.HashMap; @@ -22,51 +21,48 @@ import java.util.Map; import java.util.Set; public class ComponentDependencyTracker { - private final Map> store = new HashMap<>(); - /** - * Add dependency. - * - * @param dependent the dependent - * @param dependsOn the depends on - */ - public void addDependency(String dependent, String dependsOn) { - if (dependent != null && dependsOn != null && dependent.trim().length() > 0 && dependsOn.trim() - .length() > 0) { - Set dependsOnList = store - .computeIfAbsent(dependent.toLowerCase(), k -> new HashSet<>()); - dependsOnList.add(dependsOn.toLowerCase()); - } - } + private final Map> store = new HashMap<>(); - /** - * Is cyclic dependency present boolean. - * - * @return the boolean - */ - public boolean isCyclicDependencyPresent() { - Set>> entries = store.entrySet(); - for (Map.Entry> entry : entries) { - for (String dependentOn : entry.getValue()) { - if (!entry.getKey().equals(dependentOn) && isCyclicDependencyPresent(entry.getKey(), - dependentOn)) { - return true; + /** + * Add dependency. + * + * @param dependent the dependent + * @param dependsOn the depends on + */ + public void addDependency(String dependent, String dependsOn) { + if (dependent != null && dependsOn != null && dependent.trim().length() > 0 && dependsOn.trim().length() > 0) { + Set dependsOnList = store.computeIfAbsent(dependent.toLowerCase(), k -> new HashSet<>()); + dependsOnList.add(dependsOn.toLowerCase()); } - } } - return false; - } - private boolean isCyclicDependencyPresent(String root, String dependentOn) { - Set dependentOnList = store.get(dependentOn); - if (dependentOnList != null && dependentOnList.contains(root)) { - return true; - } else if (dependentOnList != null) { - for (String item : dependentOnList) { - return isCyclicDependencyPresent(root, item); - } + /** + * Is cyclic dependency present boolean. + * + * @return the boolean + */ + public boolean isCyclicDependencyPresent() { + Set>> entries = store.entrySet(); + for (Map.Entry> entry : entries) { + for (String dependentOn : entry.getValue()) { + if (!entry.getKey().equals(dependentOn) && isCyclicDependencyPresent(entry.getKey(), dependentOn)) { + return true; + } + } + } + return false; } - return false; - } + private boolean isCyclicDependencyPresent(String root, String dependentOn) { + Set dependentOnList = store.get(dependentOn); + if (dependentOnList != null && dependentOnList.contains(root)) { + return true; + } else if (dependentOnList != null) { + for (String item : dependentOnList) { + return isCyclicDependencyPresent(root, item); + } + } + return false; + } } diff --git a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VendorSoftwareProductUtils.java b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VendorSoftwareProductUtils.java index ded0d3d2df..575c74d93c 100644 --- a/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VendorSoftwareProductUtils.java +++ b/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/utils/VendorSoftwareProductUtils.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.utils; +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.enrichment.types.MonitoringUploadType; @@ -30,96 +35,84 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; -import java.io.File; -import java.util.*; - public class VendorSoftwareProductUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductUtils.class); - - private VendorSoftwareProductUtils(){ - - } + private static final Logger LOGGER = LoggerFactory.getLogger(VendorSoftwareProductUtils.class); - /** - * Add file names to upload file response. - * - * @param fileContentMap the file content map - * @param uploadFileResponse the upload file response - */ - public static void addFileNamesToUploadFileResponse(FileContentHandler fileContentMap, - OrchestrationTemplateActionResponse uploadFileResponse) { - uploadFileResponse.setFileNames(new ArrayList<>()); - for (String filename : fileContentMap.getFileList()) { - if (!new File(filename).isDirectory()) { - uploadFileResponse.addNewFileToList(filename); - } + private VendorSoftwareProductUtils() { } - uploadFileResponse.removeFileFromList(SdcCommon.MANIFEST_NAME); - } - /** - * Validate content zip data. - * - * @param contentMap the content map - * @param errors the errors - */ - public static void validateContentZipData(FileContentHandler contentMap, - Map> errors) { - if (contentMap.getFileList().isEmpty()) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage())); - } - } - - - /** - * Maps all artifacts by type. - * - * @param artifacts the artifacts - * @return the map - */ - public static Map mapArtifactsByType( - Collection artifacts) { - Map artifactTypeToFilename - = new EnumMap<>(MonitoringUploadType.class); - for (ComponentMonitoringUploadEntity entity : artifacts) { - artifactTypeToFilename.put(entity.getType(), entity.getArtifactName()); + /** + * Add file names to upload file response. + * + * @param fileContentMap the file content map + * @param uploadFileResponse the upload file response + */ + public static void addFileNamesToUploadFileResponse(FileContentHandler fileContentMap, OrchestrationTemplateActionResponse uploadFileResponse) { + uploadFileResponse.setFileNames(new ArrayList<>()); + for (String filename : fileContentMap.getFileList()) { + if (!new File(filename).isDirectory()) { + uploadFileResponse.addNewFileToList(filename); + } + } + uploadFileResponse.removeFileFromList(SdcCommon.MANIFEST_NAME); } - return artifactTypeToFilename; - } - - - /** - * Sets errors into logger. - * @param errors the errors - */ - public static void setErrorsIntoLogger(Map> errors) { - if (MapUtils.isEmpty(errors)) { - return; + /** + * Validate content zip data. + * + * @param contentMap the content map + * @param errors the errors + */ + public static void validateContentZipData(FileContentHandler contentMap, Map> errors) { + if (contentMap.getFileList().isEmpty()) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage())); + } } - for (Map.Entry> listEntry : errors.entrySet()) { - List errorList = listEntry.getValue(); - for (ErrorMessage message : errorList) { - LOGGER.error(message.getMessage()); - } + /** + * Maps all artifacts by type. + * + * @param artifacts the artifacts + * @return the map + */ + public static Map mapArtifactsByType(Collection artifacts) { + Map artifactTypeToFilename = new EnumMap<>(MonitoringUploadType.class); + for (ComponentMonitoringUploadEntity entity : artifacts) { + artifactTypeToFilename.put(entity.getType(), entity.getArtifactName()); + } + return artifactTypeToFilename; } - } - - /** - * Sets errors into logger. - * @param errors the errors - */ - public static void setErrorsIntoLogger(Collection errors) { - if (CollectionUtils.isEmpty(errors)) { - return; + /** + * Sets errors into logger. + * + * @param errors the errors + */ + public static void setErrorsIntoLogger(Map> errors) { + if (MapUtils.isEmpty(errors)) { + return; + } + for (Map.Entry> listEntry : errors.entrySet()) { + List errorList = listEntry.getValue(); + for (ErrorMessage message : errorList) { + LOGGER.error(message.getMessage()); + } + } } - for (ErrorCode error : errors) { - LOGGER.error(error.message()); + /** + * Sets errors into logger. + * + * @param errors the errors + */ + public static void setErrorsIntoLogger(Collection errors) { + if (CollectionUtils.isEmpty(errors)) { + return; + } + for (ErrorCode error : errors) { + LOGGER.error(error.message()); + } } - } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/BaseErrorBuilder.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/BaseErrorBuilder.java index 367cbf7df6..8c090d68b8 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/BaseErrorBuilder.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/BaseErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; public abstract class BaseErrorBuilder { - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public ErrorCode build() { - return builder.build(); - } + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public ErrorCode build() { + return builder.build(); + } - protected ErrorCode.ErrorCodeBuilder getErrorCodeBuilder() { - return builder; - } + protected ErrorCode.ErrorCodeBuilder getErrorCodeBuilder() { + return builder; + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/CoreException.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/CoreException.java index b41d6647f5..12e10fdb4e 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/CoreException.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/CoreException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; public class CoreException extends RuntimeException { - private final ErrorCode errorCode; + private final ErrorCode errorCode; - public CoreException(ErrorCode errorCode) { - this(errorCode, null); - } + public CoreException(ErrorCode errorCode) { + this(errorCode, null); + } - public CoreException(ErrorCode errorCode, Throwable cause) { - super(errorCode.toString(), cause); - this.errorCode = errorCode; - } + public CoreException(ErrorCode errorCode, Throwable cause) { + super(errorCode.toString(), cause); + this.errorCode = errorCode; + } - public ErrorCode code() { - return errorCode; - } + public ErrorCode code() { + return errorCode; + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCategory.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCategory.java index 00f8d74fb7..bb8f84711c 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCategory.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCategory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,48 +17,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; public enum ErrorCategory { - /** - * System-level problems caused by external factors, resources shortage and similar. For instance: - *
      - *
    • I/O problems (network connectivity, filesystem access etc)
    • - *
    • Java issues (missing or incompatible class definitions etc)
    • - *
    • Environment problems
    • - *
    - */ - SYSTEM, - - /** - * Application-level issues related to implementation of certain functionality (such as detected - * illegal states of a program or data inconsistency). - */ - APPLICATION, - - /** - * Problems related to violations of different rules set either by product metadata (catalog - * definitions or similar) or other types of constraints. - */ - VALIDATION, - - /** - * Problems caused by attempt of a user to perform certain operations which contradict the system - * rules. Mostly applicable to UI-driven flows in presentation tier. - */ - USER, - - /** - * Improper values set in the system configuration (negative numbers, missing or inconsistent - * definitions, mismatch with valid values list etc). - */ - CONFIGURATION, - - /** - * Security constraint violations (failed login attempts, lack of permissions to perform operation - * and so on). Any problems related to authentication/authorization should use the special - * category for system auditing purposes. - */ - SECURITY + /** + * System-level problems caused by external factors, resources shortage and similar. For instance: + *
      + *
    • I/O problems (network connectivity, filesystem access etc)
    • + *
    • Java issues (missing or incompatible class definitions etc)
    • + *
    • Environment problems
    • + *
    + */ + SYSTEM, + /** + * Application-level issues related to implementation of certain functionality (such as detected illegal states of a program or data + * inconsistency). + */ + APPLICATION, + /** + * Problems related to violations of different rules set either by product metadata (catalog definitions or similar) or other types of + * constraints. + */ + VALIDATION, + /** + * Problems caused by attempt of a user to perform certain operations which contradict the system rules. Mostly applicable to UI-driven flows in + * presentation tier. + */ + USER, + /** + * Improper values set in the system configuration (negative numbers, missing or inconsistent definitions, mismatch with valid values list etc). + */ + CONFIGURATION, + /** + * Security constraint violations (failed login attempts, lack of permissions to perform operation and so on). Any problems related to + * authentication/authorization should use the special category for system auditing purposes. + */ + SECURITY } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCode.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCode.java index 6a9990dcf1..dede69b3d0 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCode.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCode.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,92 +17,89 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; import java.io.Serializable; public class ErrorCode implements Serializable { - private static final long serialVersionUID = 1L; - - private String id; - private String message; - private ErrorCategory category; - - protected ErrorCode() { - } - /* - For backward compatibility only - will be removed soon - */ - - @Override - public String toString() { - return message; - } - - public String id() { - return id; - } - - @Deprecated - protected void id(String id) { - this.id = id; - } - - public String message() { - return message; - } - - @Deprecated - protected void message(String message) { - this.message = message; - } + private static final long serialVersionUID = 1L; + private String id; + private String message; + private ErrorCategory category; - public ErrorCategory category() { - return category; - } + protected ErrorCode() { + } - @Deprecated - protected void category(ErrorCategory category) { - this.category = category; - } + /* + For backward compatibility only - will be removed soon + */ + @Override + public String toString() { + return message; + } - public static class ErrorCodeBuilder { + public String id() { + return id; + } - private String id; - private String message; - private ErrorCategory category = ErrorCategory.APPLICATION; + @Deprecated + protected void id(String id) { + this.id = id; + } - public ErrorCodeBuilder withId(String id) { - this.id = id; - return this; + public String message() { + return message; } - //todo remove later + @Deprecated + protected void message(String message) { + this.message = message; + } - public ErrorCodeBuilder withMessage(String message) { - this.message = message; - return this; + public ErrorCategory category() { + return category; } - //todo remove later - public ErrorCodeBuilder withCategory(ErrorCategory category) { - this.category = category; - return this; + @Deprecated + protected void category(ErrorCategory category) { + this.category = category; } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - ErrorCode inst = new ErrorCode(); - inst.id = id; - inst.message = message; - inst.category = category; - return inst; + public static class ErrorCodeBuilder { + + private String id; + private String message; + private ErrorCategory category = ErrorCategory.APPLICATION; + + public ErrorCodeBuilder withId(String id) { + this.id = id; + return this; + } + + //todo remove later + public ErrorCodeBuilder withMessage(String message) { + this.message = message; + return this; + } + + //todo remove later + public ErrorCodeBuilder withCategory(ErrorCategory category) { + this.category = category; + return this; + } + + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + ErrorCode inst = new ErrorCode(); + inst.id = id; + inst.message = message; + inst.category = category; + return inst; + } } - } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCodeAndMessage.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCodeAndMessage.java index d7c5c63506..d6f5848478 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCodeAndMessage.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ErrorCodeAndMessage.java @@ -17,49 +17,43 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; - +import javax.ws.rs.core.Response; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.ws.rs.core.Response; - /** - * This class represents an error object to be returned in failed REST instead of just returning one - * of HTTP fail statuses. + * This class represents an error object to be returned in failed REST instead of just returning one of HTTP fail statuses. */ @Getter @Setter @NoArgsConstructor public class ErrorCodeAndMessage { - /** - * the HTTP status code. - */ - private Response.Status status; - - /** - * Error code no. if available. - */ - private String errorCode; - - /** - * the error message to be displayed. - */ - private String message; - - /** - * Instantiates a new Error code and message. - * - * @param status the status - * @param errorCode the error code - */ - public ErrorCodeAndMessage(Response.Status status, ErrorCode errorCode) { - this.status = status; - this.message = errorCode.message(); - this.errorCode = errorCode.id(); - } + /** + * the HTTP status code. + */ + private Response.Status status; + /** + * Error code no. if available. + */ + private String errorCode; + /** + * the error message to be displayed. + */ + private String message; + + /** + * Instantiates a new Error code and message. + * + * @param status the status + * @param errorCode the error code + */ + public ErrorCodeAndMessage(Response.Status status, ErrorCode errorCode) { + this.status = status; + this.message = errorCode.message(); + this.errorCode = errorCode.id(); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/GeneralErrorBuilder.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/GeneralErrorBuilder.java index 05eae9d7e5..8096b4d7a5 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/GeneralErrorBuilder.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/GeneralErrorBuilder.java @@ -13,31 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.common.errors; import org.apache.commons.text.RandomStringGenerator; public class GeneralErrorBuilder { - private static final String GENERAL_ERROR_REST_ID = "GENERAL_ERROR_REST_ID"; - private static final String GENERAL_ERROR_REST_MSG = - "An internal error has occurred. Please contact support. Error ID: %s"; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new General error builder. - */ - public GeneralErrorBuilder() { - RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('A', 'Z').build(); - builder.withId(GENERAL_ERROR_REST_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(GENERAL_ERROR_REST_MSG, generator.generate(8))); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String GENERAL_ERROR_REST_ID = "GENERAL_ERROR_REST_ID"; + private static final String GENERAL_ERROR_REST_MSG = "An internal error has occurred. Please contact support. Error ID: %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new General error builder. + */ + public GeneralErrorBuilder() { + RandomStringGenerator generator = new RandomStringGenerator.Builder().withinRange('A', 'Z').build(); + builder.withId(GENERAL_ERROR_REST_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(GENERAL_ERROR_REST_MSG, generator.generate(8))); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/JsonMappingErrorBuilder.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/JsonMappingErrorBuilder.java index 8c5b1cd2ad..f890828014 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/JsonMappingErrorBuilder.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/JsonMappingErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; public class JsonMappingErrorBuilder { - private static final String JSON_MAPPING_ERROR_ERR_ID = "JSON_MAPPING_ERROR_ERR_ID"; - private static final String JSON_MAPPING_ERROR_ERR_ERR_MSG = - "Error occurred while parsing the JSON input/body. Further info can be found in the log"; - - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Json mapping error builder. - */ - public JsonMappingErrorBuilder() { - builder.withId(JSON_MAPPING_ERROR_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(JSON_MAPPING_ERROR_ERR_ERR_MSG)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String JSON_MAPPING_ERROR_ERR_ID = "JSON_MAPPING_ERROR_ERR_ID"; + private static final String JSON_MAPPING_ERROR_ERR_ERR_MSG = "Error occurred while parsing the JSON input/body. Further info can be found in the log"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Json mapping error builder. + */ + public JsonMappingErrorBuilder() { + builder.withId(JSON_MAPPING_ERROR_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(JSON_MAPPING_ERROR_ERR_ERR_MSG)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java index d9186bc3b2..91ed6ae2f8 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.common.errors; import lombok.AllArgsConstructor; @@ -22,11 +21,9 @@ import lombok.Getter; @AllArgsConstructor @Getter public enum Messages { + // @formatter:off CANT_LOAD_HEALING_CLASS("Can't load healing class %s."), - - VERSION_UPGRADE("Item %s is of old version. A check out was made in order to get new " + - "functionalities"), - + VERSION_UPGRADE("Item %s is of old version. A check out was made in order to get new " + "functionalities"), PACKAGE_PROCESS_ERROR("Could not process package '%s'"), PACKAGE_INVALID_EXTENSION("Invalid package '%s' extension. Expecting %s."), PACKAGE_EMPTY_ERROR("The given package is empty '%s'"), @@ -49,8 +46,7 @@ public enum Messages { MANIFEST_METADATA_INVALID_ENTRY("Manifest metadata should only have pnf or vnf entries"), MANIFEST_METADATA_INVALID_ENTRY1("Invalid Manifest metadata entry: '%s'."), MANIFEST_METADATA_DUPLICATED_ENTRY("Duplicated Manifest metadata entry: '%s'."), - MANIFEST_METADATA_UNEXPECTED_ENTRY_TYPE( - "Manifest metadata should have either pnf or vnf entries, not both together"), + MANIFEST_METADATA_UNEXPECTED_ENTRY_TYPE("Manifest metadata should have either pnf or vnf entries, not both together"), MANIFEST_INVALID_PNF_METADATA("%s TOSCA.meta file is applicable for VF only"), MANIFEST_INVALID_NON_MANO_KEY("Invalid non mano key '%s'"), MANIFEST_EMPTY_NON_MANO_KEY("Expecting a 'Source' entry for the non mano key '%s'"), @@ -66,8 +62,7 @@ public enum Messages { MANIFEST_DUPLICATED_CMS_SIGNATURE("Duplicated CMS signature"), MANIFEST_SIGNATURE_DUPLICATED("Duplicated manifest signature"), MANIFEST_SIGNATURE_LAST_ENTRY("The manifest signature must be the last entry of the manifest."), - MANIFEST_METADATA_DOES_NOT_MATCH_LIMIT("Manifest metadata must only have the required number [%s] of " - + "entries"), + MANIFEST_METADATA_DOES_NOT_MATCH_LIMIT("Manifest metadata must only have the required number [%s] of " + "entries"), MANIFEST_EMPTY("The manifest is empty"), MANIFEST_ERROR_WITH_LINE("%s;%nAt line %s: '%s'."), MANIFEST_PARSER_INTERNAL("Invalid manifest file"), @@ -83,48 +78,35 @@ public enum Messages { METADATA_MISSING_ENTRY("TOSCA.meta file in TOSCA-metadata directory missing entry %s"), METADATA_NO_ENTRY_DEFINITIONS("TOSCA.meta must contain Entry Definitions"), METADATA_INVALID_ENTRY_DEFINITIONS("TOSCA.meta must contain key:value entries"), - - EMPTY_SW_INFORMATION_NON_MANO_ERROR( - "Non-mano Software Information artifact was declared in the manifest, but not provided"), - UNIQUE_SW_INFORMATION_NON_MANO_ERROR("Only one software information non-mano artifact is allowed. " - + "Found %s."), + EMPTY_SW_INFORMATION_NON_MANO_ERROR("Non-mano Software Information artifact was declared in the manifest, but not provided"), + UNIQUE_SW_INFORMATION_NON_MANO_ERROR("Only one software information non-mano artifact is allowed. " + "Found %s."), INVALID_SW_INFORMATION_NON_MANO_ERROR("Invalid software information non-mano artifact: '%s'"), - INCORRECT_SW_INFORMATION_NON_MANO_ERROR( - "Incorrect software information non-mano artifact. The software version information is missing " - + "or it has one or more incorrect software version entries: '%s'"), - EMPTY_ONAP_CNF_HELM_NON_MANO_ERROR( - "Non-mano onap_cnf_helm artifact was declared in the manifest, but not provided"), - UNIQUE_ONAP_CNF_HELM_NON_MANO_ERROR("Only one onap_cnf_helm non-mano artifact is allowed. " - + "Found %s."), + INCORRECT_SW_INFORMATION_NON_MANO_ERROR("Incorrect software information non-mano artifact. The software version information is missing or it has " + + "one or more incorrect software version entries: '%s'"), + EMPTY_ONAP_CNF_HELM_NON_MANO_ERROR("Non-mano onap_cnf_helm artifact was declared in the manifest, but not provided"), + UNIQUE_ONAP_CNF_HELM_NON_MANO_ERROR("Only one onap_cnf_helm non-mano artifact is allowed. " + "Found %s."), FAILED_TO_VALIDATE_METADATA("Failed to validate metadata file"), ARTIFACT_INVALID_SIGNATURE("Invalid signature '%s' provided for artifact '%s'"), - ARTIFACT_SIGNATURE_VALIDATION_ERROR( - "Could not validate signature '%s' provided for artifact '%s' with certificate '%s': %s"), + ARTIFACT_SIGNATURE_VALIDATION_ERROR("Could not validate signature '%s' provided for artifact '%s' with certificate '%s': %s"), FAILED_TO_TRANSLATE_ZIP_FILE("Failed to translate zip file"), ZIP_NOT_EXIST("Zip file doesn't exist"), - PERMISSIONS_ERROR("Permissions Error. The user does not have permission to perform this action."), PERMISSIONS_OWNER_ERROR("Permissions Error. Only one owner is allowed."), - ENTITY_NOT_FOUND("Incorrect item/version details provided."), SUB_ENTITY_NOT_FOUND("Incorrect sub entity details provided."), FAILED_TO_SYNC("Non existing version cannot be synced."), FAILED_TO_PUBLISH_OUT_OF_SYNC("Publish is not allowed since the version status is Out of sync"), - DELETE_VSP_ERROR("VSP has been certified and cannot be deleted."), DELETE_VLM_ERROR("VLM has been certified and cannot be deleted."), - ZIP_SHOULD_NOT_CONTAIN_FOLDERS("Zip file should not contain folders"), - VES_ZIP_SHOULD_CONTAIN_YML_ONLY( - "Wrong VES EVENT Artifact was uploaded - all files contained in Artifact must be YAML files" + - " (using .yaml/.yml extensions)"), + VES_ZIP_SHOULD_CONTAIN_YML_ONLY("Wrong VES EVENT Artifact was uploaded - all files contained in Artifact must be YAML files" + + " (using .yaml/.yml extensions)"), MANIFEST_NOT_EXIST("Manifest doesn't exist"), MANIFEST_NOT_FOUND("Manifest file %s referenced in TOSCA.meta does not exist"), FILE_TYPE_NOT_LEGAL("File type not legal as data for other file"), MODULE_IN_MANIFEST_NO_YAML("Module '%s', has no yaml file reference"), NO_MODULES_IN_MANIFEST("At least one Base/Module must be defined \n"), - MODULE_IN_MANIFEST_VOL_ENV_NO_VOL("Module '%s', has volume Env. reference with no Volume " + - "reference"), + MODULE_IN_MANIFEST_VOL_ENV_NO_VOL("Module '%s', has volume Env. reference with no Volume " + "reference"), ILLEGAL_MANIFEST("Illegal Manifest"), NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST("no %s file was uploaded or file doesn't exist"), MAPPING_OBJECTS_FAILURE("Failed to map object %s to %s. Exception message: %s"), @@ -133,12 +115,9 @@ public enum Messages { CREATE_MANIFEST_FROM_ZIP("cannot create manifest from the attached zip file"), CANDIDATE_PROCESS_FAILED("Candidate zip file process failed"), FOUND_UNASSIGNED_FILES("cannot process zip since it has unassigned files"), - GENERATED_ARTIFACT_IN_USE("Artifact with file name %s is generated by SDC. " - + "Please remove this artifact from manifest and zip files"), - + GENERATED_ARTIFACT_IN_USE("Artifact with file name %s is generated by SDC. " + "Please remove this artifact from manifest and zip files"), /* Monitor uploads related errors*/ - ILLEGAL_MONITORING_ARTIFACT_TYPE("Illegal monitoring artifact type for component id %s, vsp id " + - "%s"), + ILLEGAL_MONITORING_ARTIFACT_TYPE("Illegal monitoring artifact type for component id %s, vsp id %s"), /* manifest errors*/ MISSING_FILE_IN_ZIP("Missing file in zip"), MISSING_FILE_IN_MANIFEST("Missing file in manifest"), @@ -156,14 +135,12 @@ public enum Messages { CSAR_MANIFEST_FILE_NOT_EXIST("CSAR manifest file does not exist"), CSAR_FAILED_TO_READ("CSAR file is not readable"), TOSCA_PARSING_FAILURE("Invalid tosca file. Error code : %s, Error message : %s/"), - /*definition errors*/ MISSING_DEFINITION_FILE("Definition file %s referenced in TOSCA.meta does not exist"), MISSING_IMPORT_FILE("Package must contain the referenced import file '%s'"), MISSING_MAIN_DEFINITION_FILE("Package must contain the given main definition file '%s'"), INVALID_IMPORT_STATEMENT("Definition file '%s' contains an invalid import statement: '%s'"), INVALID_YAML_EXTENSION("Expecting yaml or yml extension for file: %s"), - /* content errors*/ INVALID_YAML_FORMAT("Invalid YAML format: %s"), INVALID_YAML_FORMAT_1("Invalid YAML format in file '%s'. Format error:%n%s"), @@ -176,8 +153,7 @@ public enum Messages { MISSING_RESOURCE_IN_DEPENDS_ON("a Missing resource in depend On, Missing Resource ID [%s]"), REFERENCED_PARAMETER_NOT_FOUND("Referenced parameter - %s - not found, used in resource [%s]"), GET_ATTR_NOT_FOUND("get_attr attribute not found, Attribute name [%s], Resource ID [%s]"), - MISSING_PARAMETER_IN_NESTED( - "Referenced parameter not found in nested file - %s, parameter name [%s], Resource ID [%s]"), + MISSING_PARAMETER_IN_NESTED("Referenced parameter not found in nested file - %s, parameter name [%s], Resource ID [%s]"), NESTED_LOOP("Nested files loop - %s"), MORE_THAN_ONE_BIND_FROM_NOVA_TO_PORT("Resource Port %s exceed allowed relations from NovaServer"), SERVER_NOT_DEFINED_FROM_NOVA("Missing server group definition - %s, %s"), @@ -185,64 +161,48 @@ public enum Messages { MISSING_IMAGE_AND_FLAVOR("Missing both Image and Flavor in NOVA Server, Resource ID [%s]"), ENV_INCLUDES_PARAMETER_NOT_IN_HEAT("Env file %s includes a parameter not in HEAT - %s"), PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE("Parameter env value %s not align with type"), - PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE( - "Parameter - %s default value not align with type %s"), + PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE("Parameter - %s default value not align with type %s"), INVALID_RESOURCE_TYPE("A resource has an invalid or unsupported type - %s, Resource ID [%s]"), ARTIFACT_FILE_NOT_REFERENCED("Artifact file is not referenced."), RESOURCE_NOT_IN_USE("%s not in use, Resource Id [%s]"), PORT_NO_BIND_TO_ANY_NOVA_SERVER("Port not bind to any NOVA Server, Resource Id [%s]"), - INVALID_GET_RESOURCE_SYNTAX( - "invalid get_resource syntax is in use - %s , get_resource" - + " function should get the resource id of the referenced resource"), - INVALID_RESOURCE_GROUP_TYPE( - "OS::Heat::ResourceGroup resource with resource_def which is not pointing to " - + "nested heat file is not supported, Resource ID [%s], resource_def type [%s]"), - WRONG_VALUE_TYPE_ASSIGNED_NESTED_INPUT( - "Wrong value type assigned to a nested input parameter, nested resource [%s]," - + " property name [%s], nested file [%s]"), - NOVA_NAME_IMAGE_FLAVOR_NOT_CONSISTENT( - "Nova Server naming convention in image, flavor and name properties is not " - + "consistent, Resource ID [%s]"), - RESOURCE_GROUP_INVALID_INDEX_VAR( - "Wrong value assigned to a ResourceGroup index_var property (functions are not allowed" - + " but only strings), Resource ID [%s]"), + INVALID_GET_RESOURCE_SYNTAX("invalid get_resource syntax is in use - %s , get_resource function should get the resource id of the " + + "referenced resource"), + INVALID_RESOURCE_GROUP_TYPE("OS::Heat::ResourceGroup resource with resource_def which is not pointing to nested heat file is not supported, " + + "Resource ID [%s], resource_def type [%s]"), + WRONG_VALUE_TYPE_ASSIGNED_NESTED_INPUT("Wrong value type assigned to a nested input parameter, nested resource [%s], property name [%s], " + + "nested file [%s]"), + NOVA_NAME_IMAGE_FLAVOR_NOT_CONSISTENT("Nova Server naming convention in image, flavor and name properties is not consistent, Resource ID [%s]"), + RESOURCE_GROUP_INVALID_INDEX_VAR("Wrong value assigned to a ResourceGroup index_var property (functions are not allowed but only strings)," + + " Resource ID [%s]"), CONTRAIL_2_IN_USE("Contrail 2.x deprecated resource is in use, Resource ID [%s]"), - /* warnings */ REFERENCED_RESOURCE_NOT_FOUND("Referenced resource - %s not found"), MISSING_GET_PARAM("Missing get_param in %s, Resource Id [%s]"), - /*OPENECOMP Guide lines*/ MISSING_NOVA_SERVER_METADATA("Missing Nova Server Metadata property, Resource ID [%s]"), MISSING_NOVA_SERVER_VNF_ID("Missing VNF_ID in Metadata property, Resource ID [%s]"), MISSING_NOVA_SERVER_VF_MODULE_ID("Missing VF_MODULE_ID in Metadata property, Resource id [%s]"), - NETWORK_PARAM_NOT_ALIGNED_WITH_GUIDE_LINE( - "Network Parameter Name not aligned with Guidelines, Parameter Name [%s] Resource ID [%s]"), - MISSIN_BASE_HEAT_FILE( - "Missing Base HEAT. Pay attention that without Base HEAT, there will be no shared resources"), + NETWORK_PARAM_NOT_ALIGNED_WITH_GUIDE_LINE("Network Parameter Name not aligned with Guidelines, Parameter Name [%s] Resource ID [%s]"), + MISSIN_BASE_HEAT_FILE("Missing Base HEAT. Pay attention that without Base HEAT, there will be no shared resources"), MULTI_BASE_HEAT_FILE("Multi Base HEAT. Expected only one. Files %s."), - RESOURCE_NOT_DEFINED_IN_OUTPUT( - "Resource is not defined as output and thus cannot be Shared, Resource ID [%s]"), - RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE( - "A resource is connected twice to the same network role, Network Role [%s]," - + " Resource ID [%s]"), + RESOURCE_NOT_DEFINED_IN_OUTPUT("Resource is not defined as output and thus cannot be Shared, Resource ID [%s]"), + RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE("A resource is connected twice to the same network role, Network Role [%s], " + + "Resource ID [%s]"), VOLUME_HEAT_NOT_EXPOSED("Volume is not defined as output and thus cannot be attached %s"), FORBIDDEN_RESOURCE_IN_USE("%s is in use, Resource ID [%s]"), - PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES( - "%s '%s' Parameter Name not aligned with Guidelines, Parameter Name [%s], Resource ID [%s]." - + " As a result, VF/VFC Profile may miss this information"), + PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES("%s '%s' Parameter Name not aligned with Guidelines, Parameter Name [%s], Resource ID [%s]." + + " As a result, VF/VFC Profile may miss this information"), /* Contrail validator messages*/ - MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES( - "HEAT Package includes both Contrail 2 and Contrail 3 resources. " - + "Contrail 2 resources can be found in %s. Contrail 3 resources can be found in %s"), - CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION( - "Service Template naming convention in Image and Flavor " - + "properties is not consistent in Resource, Resource ID %s"), - + MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES("HEAT Package includes both Contrail 2 and Contrail 3 resources. " + + "Contrail 2 resources can be found in %s. Contrail 3 resources can be found in %s"), + CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION("Service Template naming convention in Image and Flavor " + + "properties is not consistent in Resource, Resource ID %s"), /* Notifications */ FAILED_TO_MARK_NOTIFICATION_AS_READ("Failed to mark notifications as read"), FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION("Failed to update last seen notification for user %s"), FAILED_TO_VERIFY_SIGNATURE("Could not verify signature of signed package."); + // @formatter:on private String errorMessage; @@ -255,5 +215,4 @@ public enum Messages { public String formatMessage(final Object... params) { return String.format(errorMessage, params); } - } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcConfigurationException.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcConfigurationException.java index 4fb8cadedc..fca6038e49 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcConfigurationException.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcConfigurationException.java @@ -17,15 +17,15 @@ package org.openecomp.sdc.common.errors; public class SdcConfigurationException extends RuntimeException { - public SdcConfigurationException(String message) { - super(message); - } + public SdcConfigurationException(String message) { + super(message); + } - public SdcConfigurationException(String message, Throwable cause) { - super(message, cause); - } + public SdcConfigurationException(String message, Throwable cause) { + super(message, cause); + } - public SdcConfigurationException(Throwable cause) { - super(cause); - } + public SdcConfigurationException(Throwable cause) { + super(cause); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java index f71dd454a3..63383c4df3 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.common.errors; public class SdcRuntimeException extends RuntimeException { - public SdcRuntimeException(String message) { - super(message); - } + public SdcRuntimeException(String message) { + super(message); + } - public SdcRuntimeException(String message, Throwable cause) { - super(message, cause); - } + public SdcRuntimeException(String message, Throwable cause) { + super(message, cause); + } - public SdcRuntimeException(Throwable cause) { - super(cause); - } + public SdcRuntimeException(Throwable cause) { + super(cause); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ValidationErrorBuilder.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ValidationErrorBuilder.java index 129abf3ab7..2f9a0464fc 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ValidationErrorBuilder.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/ValidationErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.errors; public class ValidationErrorBuilder { - public static final String FIELD_VALIDATION_ERROR_ERR_ID = "FIELD_VALIDATION_ERROR_ERR_ID"; - private static final String FIELD_VALIDATION_ERROR_ERR_MSG = - "Field does not conform to predefined criteria : %s : %s"; - private static final String FIELD_VALIDATION_ERROR_ERR_MSG_USE_PREDEFINED_FOR_FIELD = "%s"; - private static final String FIELD_WITH_PREDEFINED_MESSAGE = "arg\\d"; - - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Validation error builder. - * - * @param detailedMessage the detailed message - * @param fieldName the field name - */ - public ValidationErrorBuilder(String detailedMessage, String fieldName) { - builder.withId(FIELD_VALIDATION_ERROR_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - - if (fieldName.matches(FIELD_WITH_PREDEFINED_MESSAGE)) { - builder.withMessage( - String.format(FIELD_VALIDATION_ERROR_ERR_MSG_USE_PREDEFINED_FOR_FIELD, detailedMessage)); - } else { - builder - .withMessage(String.format(FIELD_VALIDATION_ERROR_ERR_MSG, fieldName, detailedMessage)); + public static final String FIELD_VALIDATION_ERROR_ERR_ID = "FIELD_VALIDATION_ERROR_ERR_ID"; + private static final String FIELD_VALIDATION_ERROR_ERR_MSG = "Field does not conform to predefined criteria : %s : %s"; + private static final String FIELD_VALIDATION_ERROR_ERR_MSG_USE_PREDEFINED_FOR_FIELD = "%s"; + private static final String FIELD_WITH_PREDEFINED_MESSAGE = "arg\\d"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Validation error builder. + * + * @param detailedMessage the detailed message + * @param fieldName the field name + */ + public ValidationErrorBuilder(String detailedMessage, String fieldName) { + builder.withId(FIELD_VALIDATION_ERROR_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + if (fieldName.matches(FIELD_WITH_PREDEFINED_MESSAGE)) { + builder.withMessage(String.format(FIELD_VALIDATION_ERROR_ERR_MSG_USE_PREDEFINED_FOR_FIELD, detailedMessage)); + } else { + builder.withMessage(String.format(FIELD_VALIDATION_ERROR_ERR_MSG, fieldName, detailedMessage)); + } } - } - - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/exception/ZipException.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/exception/ZipException.java index d26fae62e4..490fef8442 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/exception/ZipException.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/exception/ZipException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.exception; import java.io.IOException; diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java index a564928820..66a295eba3 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/CommonUtil.java @@ -16,7 +16,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.common.utils; import com.google.common.collect.Multimap; @@ -44,118 +43,105 @@ import org.openecomp.sdc.common.zip.exception.ZipException; public class CommonUtil { - private CommonUtil() { - // prevent instantiation - } - - /** - * Reads the files from the zip AND validates zip is flat (no folders). - * - * @param type the onboarding type - * @param uploadedFileData zip file bytes - * @return FileContentHandler if input is valid and has no folders - * @throws IOException when the zip could not be read - */ - public static FileContentHandler validateAndUploadFileContent(final OnboardingTypesEnum type, - final byte[] uploadedFileData) throws IOException { - final Pair> pair; - try { - pair = getFileContentMapFromOrchestrationCandidateZip(uploadedFileData); - } catch (final ZipException e) { - throw new IOException(e); + private CommonUtil() { + // prevent instantiation } - if (isFileOriginFromZip(type.toString())) { - validateNoFolders(pair.getRight()); - } - - return pair.getLeft(); - } - - /** - * Extracts the zip in memory and build a pair of {@link FileContentHandler} and the zip folder list. The {@link - * FileContentHandler} will only contain the files, not the folders. - * - * @param uploadFileData the zip file to extract - * @return a pair of {@link FileContentHandler} only with the zip files and a list of the zip folders. - * @throws ZipException when there was a problem during the zip reading - */ - public static Pair> getFileContentMapFromOrchestrationCandidateZip( - byte[] uploadFileData) throws ZipException { - final Map zipFileMap = ZipUtils.readZip(uploadFileData, true); - final List folderList = new ArrayList<>(); - final FileContentHandler mapFileContent = new FileContentHandler(); - - zipFileMap.forEach((key, value) -> { - if (value == null) { - folderList.add(key); - } else { - mapFileContent.addFile(key, value); - } - }); - - return new ImmutablePair<>(mapFileContent, folderList); - } - /** - * Extracts the zip in memory and build the {@link FileContentHandler}. - * - * @param zipFile the zip file to extract - * @return The {@link FileContentHandler} based on the zip content - * @throws ZipException when there was a problem during the zip reading - */ - public static FileContentHandler getZipContent(final byte[] zipFile) throws ZipException { - final Map zipFileMap = ZipUtils.readZip(zipFile, true); - final FileContentHandler fileContentHandler = new FileContentHandler(); - zipFileMap.forEach((key, value) -> { - if (value == null) { - fileContentHandler.addFolder(key); - } else { - fileContentHandler.addFile(key, value); - } - }); - return fileContentHandler; - } + /** + * Reads the files from the zip AND validates zip is flat (no folders). + * + * @param type the onboarding type + * @param uploadedFileData zip file bytes + * @return FileContentHandler if input is valid and has no folders + * @throws IOException when the zip could not be read + */ + public static FileContentHandler validateAndUploadFileContent(final OnboardingTypesEnum type, final byte[] uploadedFileData) throws IOException { + final Pair> pair; + try { + pair = getFileContentMapFromOrchestrationCandidateZip(uploadedFileData); + } catch (final ZipException e) { + throw new IOException(e); + } + if (isFileOriginFromZip(type.toString())) { + validateNoFolders(pair.getRight()); + } + return pair.getLeft(); + } - private static void validateNoFolders(List folderList) { - if (CollectionUtils.isNotEmpty(folderList)) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) - .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + /** + * Extracts the zip in memory and build a pair of {@link FileContentHandler} and the zip folder list. The {@link FileContentHandler} will only + * contain the files, not the folders. + * + * @param uploadFileData the zip file to extract + * @return a pair of {@link FileContentHandler} only with the zip files and a list of the zip folders. + * @throws ZipException when there was a problem during the zip reading + */ + public static Pair> getFileContentMapFromOrchestrationCandidateZip(byte[] uploadFileData) throws ZipException { + final Map zipFileMap = ZipUtils.readZip(uploadFileData, true); + final List folderList = new ArrayList<>(); + final FileContentHandler mapFileContent = new FileContentHandler(); + zipFileMap.forEach((key, value) -> { + if (value == null) { + folderList.add(key); + } else { + mapFileContent.addFile(key, value); + } + }); + return new ImmutablePair<>(mapFileContent, folderList); } - } - private static boolean validateFilesExtensions(Set allowedExtensions, FileContentHandler - files) { - for (String fileName : files.getFileList()) { - if (!allowedExtensions.contains(FilenameUtils.getExtension(fileName))) { - return false; - } + /** + * Extracts the zip in memory and build the {@link FileContentHandler}. + * + * @param zipFile the zip file to extract + * @return The {@link FileContentHandler} based on the zip content + * @throws ZipException when there was a problem during the zip reading + */ + public static FileContentHandler getZipContent(final byte[] zipFile) throws ZipException { + final Map zipFileMap = ZipUtils.readZip(zipFile, true); + final FileContentHandler fileContentHandler = new FileContentHandler(); + zipFileMap.forEach((key, value) -> { + if (value == null) { + fileContentHandler.addFolder(key); + } else { + fileContentHandler.addFile(key, value); + } + }); + return fileContentHandler; } - return true; - } - public static boolean validateAllFilesYml(FileContentHandler files) { - Set allowedExtensions = new HashSet<>(Arrays.asList("yml", "yaml")); - return validateFilesExtensions(allowedExtensions, files); - } + private static void validateNoFolders(List folderList) { + if (CollectionUtils.isNotEmpty(folderList)) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()) + .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage()).withCategory(ErrorCategory.APPLICATION).build()); + } + } - public static boolean isFileOriginFromZip(String fileOrigin) { - return Objects.nonNull(fileOrigin) - && fileOrigin.equalsIgnoreCase(OnboardingTypesEnum.ZIP.toString()); - } + private static boolean validateFilesExtensions(Set allowedExtensions, FileContentHandler files) { + for (String fileName : files.getFileList()) { + if (!allowedExtensions.contains(FilenameUtils.getExtension(fileName))) { + return false; + } + } + return true; + } + public static boolean validateAllFilesYml(FileContentHandler files) { + Set allowedExtensions = new HashSet<>(Arrays.asList("yml", "yaml")); + return validateFilesExtensions(allowedExtensions, files); + } - public static Optional createObjectUsingSetters(Object objectCandidate, - Class classToCreate) - throws Exception { - return org.onap.sdc.tosca.services.CommonUtil.createObjectUsingSetters(objectCandidate, classToCreate); - } + public static boolean isFileOriginFromZip(String fileOrigin) { + return Objects.nonNull(fileOrigin) && fileOrigin.equalsIgnoreCase(OnboardingTypesEnum.ZIP.toString()); + } + public static Optional createObjectUsingSetters(Object objectCandidate, Class classToCreate) throws Exception { + return org.onap.sdc.tosca.services.CommonUtil.createObjectUsingSetters(objectCandidate, classToCreate); + } - public static Map getObjectAsMap(Object obj) { - return org.onap.sdc.tosca.services.CommonUtil.getObjectAsMap(obj); - } + public static Map getObjectAsMap(Object obj) { + return org.onap.sdc.tosca.services.CommonUtil.getObjectAsMap(obj); + } public static boolean isMultimapEmpty(Multimap obj) { return Objects.isNull(obj) || obj.isEmpty(); diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java index 9de0e7b0e1..4c1424287f 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.common.utils; public class SdcCommon { - public static final String MANIFEST_NAME = "MANIFEST.json"; - public static final String CSAR_MANIFEST_NAME = "MainServiceTemplate.mf"; - public static final String UPLOAD_FILE = "uploadFile"; - public static final String PROCESS_FILE = "Process File"; - public static final String ILLEGAL_MANIFEST = "Illegal manifest"; - - public static final String HEAT_TO_TOSCA_MAPPING_CONF = "heatToToscaMapping.json"; - public static final String HEAT_META = "HEAT.meta"; - public static final String PARENT = "parent"; - - public static final String VSP_ID = "vspId"; - public static final String VLM_ID = "vlmId"; - public static final String VERSION = "version"; - public static final String USER = "user"; + public static final String MANIFEST_NAME = "MANIFEST.json"; + public static final String CSAR_MANIFEST_NAME = "MainServiceTemplate.mf"; + public static final String UPLOAD_FILE = "uploadFile"; + public static final String PROCESS_FILE = "Process File"; + public static final String ILLEGAL_MANIFEST = "Illegal manifest"; + public static final String HEAT_TO_TOSCA_MAPPING_CONF = "heatToToscaMapping.json"; + public static final String HEAT_META = "HEAT.meta"; + public static final String PARENT = "parent"; + public static final String VSP_ID = "vspId"; + public static final String VLM_ID = "vlmId"; + public static final String VERSION = "version"; + public static final String USER = "user"; } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java index c0947d0b69..16ad7b274a 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts; +import java.util.Optional; import org.openecomp.conflicts.types.Conflict; import org.openecomp.conflicts.types.ConflictResolution; import org.openecomp.conflicts.types.ItemVersionConflict; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Optional; - public interface ItemMergeHandler { - boolean isConflicted(String itemId, Version version); + boolean isConflicted(String itemId, Version version); - void finalizeMerge(String itemId, Version version); + void finalizeMerge(String itemId, Version version); - void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts); + void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts); - Optional getConflict(String itemId, Version version, String conflictId); + Optional getConflict(String itemId, Version version, String conflictId); - void postGetConflict(String itemId, Version version, Conflict conflict); + void postGetConflict(String itemId, Version version, Conflict conflict); - void preResolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution); + void preResolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution); - boolean resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution); + boolean resolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution); } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java index d309e6f8fa..209ce16e44 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts; +import java.util.Optional; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -import java.util.Optional; - -public abstract class ItemMergeHandlerFactory - extends AbstractComponentFactory { +public abstract class ItemMergeHandlerFactory extends AbstractComponentFactory { - public static ItemMergeHandlerFactory getInstance() { - return AbstractFactory.getInstance(ItemMergeHandlerFactory.class); - } + public static ItemMergeHandlerFactory getInstance() { + return AbstractFactory.getInstance(ItemMergeHandlerFactory.class); + } - public abstract Optional createInterface(String itemId); + public abstract Optional createInterface(String itemId); } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java index 20865efc08..a3264e100f 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.dao; import org.openecomp.conflicts.types.Conflict; @@ -27,12 +26,11 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ConflictsDao { - boolean isConflicted(String itemId, Version version); + boolean isConflicted(String itemId, Version version); - ItemVersionConflict getConflict(String itemId, Version version); + ItemVersionConflict getConflict(String itemId, Version version); - Conflict getConflict(String itemId, Version version, String conflictId); + Conflict getConflict(String itemId, Version version, String conflictId); - void resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution conflictResolution); + void resolveConflict(String itemId, Version version, String conflictId, ConflictResolution conflictResolution); } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java index e4c88d6279..3c4525e1aa 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class ConflictsDaoFactory - extends AbstractComponentFactory { +public abstract class ConflictsDaoFactory extends AbstractComponentFactory { - public static ConflictsDaoFactory getInstance() { - return AbstractFactory.getInstance(ConflictsDaoFactory.class); - } + public static ConflictsDaoFactory getInstance() { + return AbstractFactory.getInstance(ConflictsDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java index 80186f876b..33b2026628 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.types; import com.google.common.annotations.VisibleForTesting; import org.openecomp.sdc.datatypes.model.ElementType; public class Conflict extends ConflictInfo { - private T yours; - private T theirs; - - @VisibleForTesting - Conflict() {} - public Conflict(String id, ElementType type, String name) { - super(id, type, name); - } + private T yours; + private T theirs; - public T getYours() { - return yours; - } + @VisibleForTesting + Conflict() { + } - public void setYours(T yours) { - this.yours = yours; - } + public Conflict(String id, ElementType type, String name) { + super(id, type, name); + } - public T getTheirs() { - return theirs; - } + public T getYours() { + return yours; + } - public void setTheirs(T theirs) { - this.theirs = theirs; - } + public void setYours(T yours) { + this.yours = yours; + } + public T getTheirs() { + return theirs; + } + public void setTheirs(T theirs) { + this.theirs = theirs; + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java index af4111c1dd..b56b576eb7 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,48 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.types; import com.google.common.annotations.VisibleForTesting; import org.openecomp.sdc.datatypes.model.ElementType; public class ConflictInfo { - private String id; - private ElementType type; - private String name; - @VisibleForTesting - ConflictInfo() { - } + private String id; + private ElementType type; + private String name; + + @VisibleForTesting + ConflictInfo() { + } - public ConflictInfo(String id, ElementType type, String name) { - this.id = id; - this.type = type; - this.name = name; - } + public ConflictInfo(String id, ElementType type, String name) { + this.id = id; + this.type = type; + this.name = name; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public ElementType getType() { - return type; - } + public ElementType getType() { + return type; + } - public void setType(ElementType type) { - this.type = type; - } + public void setType(ElementType type) { + this.type = type; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java index 04a790ca91..05387c6baf 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.types; import java.util.Map; public class ConflictResolution { - private Resolution resolution; - // sits in lower level... - private Map otherResolution; - public ConflictResolution() { - } + private Resolution resolution; + // sits in lower level... + private Map otherResolution; + + public ConflictResolution() { + } - public ConflictResolution(Resolution resolution) { - this.resolution = resolution; - } + public ConflictResolution(Resolution resolution) { + this.resolution = resolution; + } - public Resolution getResolution() { - return resolution; - } + public Resolution getResolution() { + return resolution; + } - public void setResolution(Resolution resolution) { - this.resolution = resolution; - } + public void setResolution(Resolution resolution) { + this.resolution = resolution; + } - public Map getOtherResolution() { - return otherResolution; - } + public Map getOtherResolution() { + return otherResolution; + } - public void setOtherResolution(Map otherResolution) { - this.otherResolution = otherResolution; - } + public void setOtherResolution(Map otherResolution) { + this.otherResolution = otherResolution; + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java index 4ae2b2c086..4bd3eabc7e 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,35 +17,34 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.types; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.util.ArrayList; import java.util.Collection; +import org.openecomp.sdc.versioning.dao.types.Version; public class ItemVersionConflict { - private Conflict versionConflict; - private Collection elementConflicts = new ArrayList<>(); - public Conflict getVersionConflict() { - return versionConflict; - } + private Conflict versionConflict; + private Collection elementConflicts = new ArrayList<>(); + + public Conflict getVersionConflict() { + return versionConflict; + } - public void setVersionConflict(Conflict versionConflict) { - this.versionConflict = versionConflict; - } + public void setVersionConflict(Conflict versionConflict) { + this.versionConflict = versionConflict; + } - public Collection getElementConflicts() { - return elementConflicts; - } + public Collection getElementConflicts() { + return elementConflicts; + } - public void setElementConflicts(Collection elementConflicts) { - this.elementConflicts = elementConflicts; - } + public void setElementConflicts(Collection elementConflicts) { + this.elementConflicts = elementConflicts; + } - public void addElementConflictInfo(ConflictInfo conflictInfo) { - elementConflicts.add(conflictInfo); - } + public void addElementConflictInfo(ConflictInfo conflictInfo) { + elementConflicts.add(conflictInfo); + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java index 5f7db39486..2f03dbe9d8 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.types; public enum Resolution { - THEIRS,YOURS,OTHER + THEIRS, YOURS, OTHER } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java index 3c879dee17..bff46a81fa 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.conflicts; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import org.openecomp.conflicts.dao.ConflictsDaoFactory; import org.openecomp.conflicts.impl.VspMergeHandler; import org.openecomp.sdc.common.errors.CoreException; @@ -25,32 +27,27 @@ import org.openecomp.sdc.versioning.AsdcItemManagerFactory; import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder; import org.openecomp.sdc.versioning.types.Item; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - public class ItemMergeHandlerFactoryImpl extends ItemMergeHandlerFactory { - // TODO: 11/1/2017 read this map from configuration, move Vsp merge handler to vsp lib, rearrange lib deps - private static final Map MERGE_HANDLER_BY_ITEM_TYPE = - new HashMap<>(); - static { - MERGE_HANDLER_BY_ITEM_TYPE.put(ItemType.vsp, - new VspMergeHandler(ConflictsDaoFactory.getInstance().createInterface(), - VspMergeDaoFactory.getInstance().createInterface())); - } + // TODO: 11/1/2017 read this map from configuration, move Vsp merge handler to vsp lib, rearrange lib deps + private static final Map MERGE_HANDLER_BY_ITEM_TYPE = new HashMap<>(); - @Override - public Optional createInterface(String itemId) { - Item item = AsdcItemManagerFactory.getInstance().createInterface().get(itemId); - if (item == null) { - throw new CoreException(new EntityNotExistErrorBuilder("", itemId).build()); + static { + MERGE_HANDLER_BY_ITEM_TYPE.put(ItemType.vsp, + new VspMergeHandler(ConflictsDaoFactory.getInstance().createInterface(), VspMergeDaoFactory.getInstance().createInterface())); } - return Optional.ofNullable(MERGE_HANDLER_BY_ITEM_TYPE.get(ItemType.valueOf(item.getType()))); - } - @Override - public ItemMergeHandler createInterface() { - return null; // call the one with the item id arg - } + @Override + public Optional createInterface(String itemId) { + Item item = AsdcItemManagerFactory.getInstance().createInterface().get(itemId); + if (item == null) { + throw new CoreException(new EntityNotExistErrorBuilder("", itemId).build()); + } + return Optional.ofNullable(MERGE_HANDLER_BY_ITEM_TYPE.get(ItemType.valueOf(item.getType()))); + } + + @Override + public ItemMergeHandler createInterface() { + return null; // call the one with the item id arg + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java index 1ae13b8c48..61a1e18c45 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.dao.impl.zusammen; - import org.openecomp.conflicts.dao.ConflictsDao; import org.openecomp.conflicts.dao.ConflictsDaoFactory; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -28,11 +26,11 @@ import org.openecomp.core.zusammen.api.ZusammenUtil; public class ConflictsDaoFactoryImpl extends ConflictsDaoFactory { - private static final ConflictsDao INSTANCE = new - ConflictsDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface(), ZusammenUtil::createSessionContext); + private static final ConflictsDao INSTANCE = new ConflictsDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface(), + ZusammenUtil::createSessionContext); - @Override - public ConflictsDao createInterface() { - return INSTANCE; - } + @Override + public ConflictsDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java index ecc0a3c7ab..047d5c2743 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; @@ -37,145 +38,149 @@ import org.openecomp.conflicts.types.ItemVersionConflict; import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.*; -import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.*; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToEntitlementPoolConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToFeatureGroupConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseAgreementConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseKeyGroupConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLimitConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToVLMGeneralConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentDependencyModelConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToCompositionEntityConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComputeConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToImageConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToMonitoringUploadMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNetworkConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToOrchestrationTemplateCandidateMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToServiceModelMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPGeneralConvertor; import org.openecomp.sdc.versioning.dao.types.Version; -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; - public class ConflictsDaoImpl implements ConflictsDao { - private final ZusammenAdaptor zusammenAdaptor; - private final Supplier sessionContextProvider; - - public ConflictsDaoImpl(ZusammenAdaptor zusammenAdaptor, Supplier sessionContextProvider) { - this.zusammenAdaptor = zusammenAdaptor; - this.sessionContextProvider = sessionContextProvider; - } - - @Override - public boolean isConflicted(String itemId, Version version) { - com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict itemVersionConflict = - zusammenAdaptor - .getVersionConflict(sessionContextProvider.get(), new Id(itemId), new Id(version.getId())); - return !(itemVersionConflict == null - || (itemVersionConflict.getVersionDataConflict() == null - && itemVersionConflict.getElementConflictInfos().isEmpty())); - } - - @Override - public ItemVersionConflict getConflict(String itemId, Version version) { - return new ItemVersionConflictConvertorFromZusammen().convert(itemId, version, - zusammenAdaptor - .getVersionConflict(sessionContextProvider.get(), new Id(itemId), new Id(version.getId()))); - } - - @Override - public Conflict getConflict(String itemId, Version version, String conflictId) { - return zusammenAdaptor.getElementConflict(sessionContextProvider.get(), - new ElementContext(new Id(itemId), new Id(version.getId())), new Id(conflictId)) - .map(elementConflict -> convertElementConflict(conflictId, elementConflict)) - .orElse(null); - } - - @Override - public void resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution conflictResolution) { - SessionContext context = sessionContextProvider.get(); - ElementContext elementContext = new ElementContext(new Id(itemId), new Id(version.getId())); - - // TODO: 7/31/2017 when 'OTHER' resolution will be supported - populate zusammen element with it - zusammenAdaptor.resolveElementConflict(context, elementContext, - buildElement(new Id(conflictId), null), - Resolution.valueOf(conflictResolution.getResolution().name())); - } - - private Conflict convertElementConflict(String conflictId, ElementConflict elementConflict) { - Element element = elementConflict.getLocalElement() == null - ? elementConflict.getRemoteElement() - : elementConflict.getLocalElement(); - ElementType elementType = ElementConvertor.getElementType(element); - - Conflict conflict = - new Conflict(conflictId, elementType, ElementConvertor.getElementName(element)); - ElementConvertor convertor = getConvertor(elementType); - if (elementConflict.getLocalElement() != null) { - conflict.setYours(convertor.convert(elementConflict.getLocalElement())); - } - if (elementConflict.getRemoteElement() != null) { - conflict.setTheirs(convertor.convert(elementConflict.getRemoteElement())); - } - return conflict; - } - - private ElementConvertor getConvertor(ElementType type) { - switch (type) { - case VendorSoftwareProduct: - return new ElementToVSPGeneralConvertor(); - case Process: - return new ElementToProcessConvertor(); - case Nic: - return new ElementToNicConvertor(); - case Network: - return new ElementToNetworkConvertor(); - case SNMP_POLL: - case SNMP_TRAP: - case VES_EVENTS: - return new ElementToMonitoringUploadMapConvertor(); - case Image: - return new ElementToImageConvertor(); - case Compute: - return new ElementToComputeConvertor(); - case Component: - return new ElementToComponentConvertor(); - case ComponentDependencies: - return new ElementToComponentDependencyModelConvertor(); - case VendorLicenseModel: - return new ElementToVLMGeneralConvertor(); - case LicenseAgreement: - return new ElementToLicenseAgreementConvertor(); - case FeatureGroup: - return new ElementToFeatureGroupConvertor(); - case LicenseKeyGroup: - return new ElementToLicenseKeyGroupConvertor(); - case EntitlementPool: - return new ElementToEntitlementPoolConvertor(); - case Limit: - return new ElementToLimitConvertor(); - case OrchestrationTemplateCandidate: - return new ElementToOrchestrationTemplateCandidateMapConvertor(); - case ServiceModel: - return new ElementToServiceModelMapConvertor(); - case VSPQuestionnaire: - case ImageQuestionnaire: - case ComponentQuestionnaire: - case ComputeQuestionnaire: - case NicQuestionnaire: - return new ElementToCompositionEntityConvertor(); - default: - return new EchoConvertor(); - } - } - public static class EchoConvertor extends ElementConvertor { + private final ZusammenAdaptor zusammenAdaptor; + private final Supplier sessionContextProvider; + + public ConflictsDaoImpl(ZusammenAdaptor zusammenAdaptor, Supplier sessionContextProvider) { + this.zusammenAdaptor = zusammenAdaptor; + this.sessionContextProvider = sessionContextProvider; + } @Override - public Object convert(Element element) { - return element; + public boolean isConflicted(String itemId, Version version) { + com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict itemVersionConflict = zusammenAdaptor + .getVersionConflict(sessionContextProvider.get(), new Id(itemId), new Id(version.getId())); + return !(itemVersionConflict == null || (itemVersionConflict.getVersionDataConflict() == null && itemVersionConflict.getElementConflictInfos() + .isEmpty())); } @Override - public Object convert(Item item) { - return item; + public ItemVersionConflict getConflict(String itemId, Version version) { + return new ItemVersionConflictConvertorFromZusammen() + .convert(itemId, version, zusammenAdaptor.getVersionConflict(sessionContextProvider.get(), new Id(itemId), new Id(version.getId()))); } @Override - public Object convert(ElementInfo elementInfo) { - return elementInfo; + public Conflict getConflict(String itemId, Version version, String conflictId) { + return zusammenAdaptor + .getElementConflict(sessionContextProvider.get(), new ElementContext(new Id(itemId), new Id(version.getId())), new Id(conflictId)) + .map(elementConflict -> convertElementConflict(conflictId, elementConflict)).orElse(null); } @Override - public Object convert(ItemVersion itemVersion) { - return null; + public void resolveConflict(String itemId, Version version, String conflictId, ConflictResolution conflictResolution) { + SessionContext context = sessionContextProvider.get(); + ElementContext elementContext = new ElementContext(new Id(itemId), new Id(version.getId())); + // TODO: 7/31/2017 when 'OTHER' resolution will be supported - populate zusammen element with it + zusammenAdaptor.resolveElementConflict(context, elementContext, buildElement(new Id(conflictId), null), + Resolution.valueOf(conflictResolution.getResolution().name())); + } + + private Conflict convertElementConflict(String conflictId, ElementConflict elementConflict) { + Element element = elementConflict.getLocalElement() == null ? elementConflict.getRemoteElement() : elementConflict.getLocalElement(); + ElementType elementType = ElementConvertor.getElementType(element); + Conflict conflict = new Conflict(conflictId, elementType, ElementConvertor.getElementName(element)); + ElementConvertor convertor = getConvertor(elementType); + if (elementConflict.getLocalElement() != null) { + conflict.setYours(convertor.convert(elementConflict.getLocalElement())); + } + if (elementConflict.getRemoteElement() != null) { + conflict.setTheirs(convertor.convert(elementConflict.getRemoteElement())); + } + return conflict; + } + + private ElementConvertor getConvertor(ElementType type) { + switch (type) { + case VendorSoftwareProduct: + return new ElementToVSPGeneralConvertor(); + case Process: + return new ElementToProcessConvertor(); + case Nic: + return new ElementToNicConvertor(); + case Network: + return new ElementToNetworkConvertor(); + case SNMP_POLL: + case SNMP_TRAP: + case VES_EVENTS: + return new ElementToMonitoringUploadMapConvertor(); + case Image: + return new ElementToImageConvertor(); + case Compute: + return new ElementToComputeConvertor(); + case Component: + return new ElementToComponentConvertor(); + case ComponentDependencies: + return new ElementToComponentDependencyModelConvertor(); + case VendorLicenseModel: + return new ElementToVLMGeneralConvertor(); + case LicenseAgreement: + return new ElementToLicenseAgreementConvertor(); + case FeatureGroup: + return new ElementToFeatureGroupConvertor(); + case LicenseKeyGroup: + return new ElementToLicenseKeyGroupConvertor(); + case EntitlementPool: + return new ElementToEntitlementPoolConvertor(); + case Limit: + return new ElementToLimitConvertor(); + case OrchestrationTemplateCandidate: + return new ElementToOrchestrationTemplateCandidateMapConvertor(); + case ServiceModel: + return new ElementToServiceModelMapConvertor(); + case VSPQuestionnaire: + case ImageQuestionnaire: + case ComponentQuestionnaire: + case ComputeQuestionnaire: + case NicQuestionnaire: + return new ElementToCompositionEntityConvertor(); + default: + return new EchoConvertor(); + } + } + + public static class EchoConvertor extends ElementConvertor { + + @Override + public Object convert(Element element) { + return element; + } + + @Override + public Object convert(Item item) { + return item; + } + + @Override + public Object convert(ElementInfo elementInfo) { + return elementInfo; + } + + @Override + public Object convert(ItemVersion itemVersion) { + return null; + } } - } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java index 67827bc041..9c5238c44e 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.dao.impl.zusammen; - import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflictInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; @@ -28,6 +26,7 @@ import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; +import java.util.stream.Collectors; import org.openecomp.conflicts.types.Conflict; import org.openecomp.conflicts.types.ConflictInfo; import org.openecomp.sdc.datatypes.model.ElementType; @@ -35,59 +34,40 @@ import org.openecomp.sdc.versioning.dao.impl.zusammen.convertor.ItemVersionToVer import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.util.stream.Collectors; - public class ItemVersionConflictConvertorFromZusammen { - public org.openecomp.conflicts.types.ItemVersionConflict convert(String itemId, Version version, - ItemVersionConflict source) { - org.openecomp.conflicts.types.ItemVersionConflict target = - new org.openecomp.conflicts.types.ItemVersionConflict(); - - target.setVersionConflict( - convertVersionDataConflict(itemId, version, source.getVersionDataConflict())); - target.setElementConflicts(source.getElementConflictInfos().stream() - .map(this::convertElementConflictInfo) - .collect(Collectors.toList())); - return target; - } - - - private Conflict convertVersionDataConflict(String itemId, Version version, - ItemVersionDataConflict versionDataConflict) { - if (versionDataConflict == null) { - return null; + public org.openecomp.conflicts.types.ItemVersionConflict convert(String itemId, Version version, ItemVersionConflict source) { + org.openecomp.conflicts.types.ItemVersionConflict target = new org.openecomp.conflicts.types.ItemVersionConflict(); + target.setVersionConflict(convertVersionDataConflict(itemId, version, source.getVersionDataConflict())); + target.setElementConflicts(source.getElementConflictInfos().stream().map(this::convertElementConflictInfo).collect(Collectors.toList())); + return target; } - Conflict conflict = - new Conflict<>(version.getId(), ElementType.itemVersion, null); - - ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); - conflict.setYours(convertor.convert( - getItemVersion(version.getId(), versionDataConflict.getLocalData()))); - conflict.setTheirs(convertor.convert( - getItemVersion(version.getId(), versionDataConflict.getRemoteData()))); - return conflict; - } - - private ItemVersion getItemVersion(String versionId, ItemVersionData versionData) { - if (versionData == null) { - return null; + private Conflict convertVersionDataConflict(String itemId, Version version, ItemVersionDataConflict versionDataConflict) { + if (versionDataConflict == null) { + return null; + } + Conflict conflict = new Conflict<>(version.getId(), ElementType.itemVersion, null); + ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); + conflict.setYours(convertor.convert(getItemVersion(version.getId(), versionDataConflict.getLocalData()))); + conflict.setTheirs(convertor.convert(getItemVersion(version.getId(), versionDataConflict.getRemoteData()))); + return conflict; } - ItemVersion itemVersion = new ItemVersion(); - itemVersion.setId(new Id(versionId)); - itemVersion.setData(versionData); - return itemVersion; - } - private ConflictInfo convertElementConflictInfo(ElementConflictInfo elementConflictInfo) { - ElementInfo elementInfo = elementConflictInfo.getLocalElementInfo() == null - ? elementConflictInfo.getRemoteElementInfo() - : elementConflictInfo.getLocalElementInfo(); + private ItemVersion getItemVersion(String versionId, ItemVersionData versionData) { + if (versionData == null) { + return null; + } + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(new Id(versionId)); + itemVersion.setData(versionData); + return itemVersion; + } - return new ConflictInfo(elementInfo.getId().getValue(), - ElementType - .valueOf(elementInfo.getInfo().getProperty(ElementPropertyName.elementType.name())), - elementInfo.getInfo().getName()); - } + private ConflictInfo convertElementConflictInfo(ElementConflictInfo elementConflictInfo) { + ElementInfo elementInfo = elementConflictInfo.getLocalElementInfo() == null ? elementConflictInfo.getRemoteElementInfo() + : elementConflictInfo.getLocalElementInfo(); + return new ConflictInfo(elementInfo.getId().getValue(), + ElementType.valueOf(elementInfo.getInfo().getProperty(ElementPropertyName.elementType.name())), elementInfo.getInfo().getName()); + } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java index 17b3043472..f3ea1eec87 100644 --- a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.conflicts.impl; +import static org.openecomp.sdc.datatypes.model.ElementType.NetworkPackage; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplate; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateCandidate; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateCandidateContent; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateValidationData; +import static org.openecomp.sdc.datatypes.model.ElementType.VspModel; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.openecomp.conflicts.ItemMergeHandler; import org.openecomp.conflicts.dao.ConflictsDao; -import org.openecomp.conflicts.types.*; +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictInfo; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.conflicts.types.Resolution; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -30,179 +51,138 @@ import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; +public class VspMergeHandler implements ItemMergeHandler { -import static org.openecomp.sdc.datatypes.model.ElementType.*; + private static final String VSP_MODEL_CONFLICT_ID = "vspModelConflictId"; + private static final String ELEMENT_CONFLICT_NOT_EXIST_ERR_ID = "ELEMENT_CONFLICT_NOT_EXIST"; + private static final String ELEMENT_CONFLICT_NOT_EXISTS_MSG = "Item Id %s, version Id %s, element conflict with Id %s does not exists."; + private static final Set FILTERED_OUT_TYPES = Stream.of(OrchestrationTemplateCandidateContent, OrchestrationTemplateValidationData) + .collect(Collectors.toSet()); + private static final Map> ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES = new EnumMap<>(ElementType.class); -public class VspMergeHandler implements ItemMergeHandler { + static { + ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplateCandidate, Collections.singleton(OrchestrationTemplateCandidateContent)); + ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplate, Collections.singleton(OrchestrationTemplateValidationData)); + } + + private ConflictsDao conflictsDao; + private VspMergeDao vspMergeDao; - private static final String VSP_MODEL_CONFLICT_ID = "vspModelConflictId"; - private static final String ELEMENT_CONFLICT_NOT_EXIST_ERR_ID = "ELEMENT_CONFLICT_NOT_EXIST"; - private static final String ELEMENT_CONFLICT_NOT_EXISTS_MSG = - "Item Id %s, version Id %s, element conflict with Id %s does not exists."; - private static final Set FILTERED_OUT_TYPES = Stream - .of(OrchestrationTemplateCandidateContent, OrchestrationTemplateValidationData) - .collect(Collectors.toSet()); - private static final Map> ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES = - new EnumMap<>(ElementType.class); - - static { - ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplateCandidate, - Collections.singleton(OrchestrationTemplateCandidateContent)); - ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplate, - Collections.singleton(OrchestrationTemplateValidationData)); - } - - private ConflictsDao conflictsDao; - private VspMergeDao vspMergeDao; - - public VspMergeHandler(ConflictsDao conflictsDao, VspMergeDao vspMergeDao) { - this.conflictsDao = conflictsDao; - this.vspMergeDao = vspMergeDao; - } - - @Override - public boolean isConflicted(String itemId, Version version) { - return vspMergeDao.isConflicted(itemId, version); - } - - @Override - public void finalizeMerge(String itemId, Version version) { - if (!conflictsDao.isConflicted(itemId, version)) { - vspMergeDao.applyConflictResolution(itemId, version); + public VspMergeHandler(ConflictsDao conflictsDao, VspMergeDao vspMergeDao) { + this.conflictsDao = conflictsDao; + this.vspMergeDao = vspMergeDao; } - } - - @Override - public void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts) { - List elementConflicts = new ArrayList<>(); - - boolean vspModelConflicted = false; - for (ConflictInfo elementConflict : conflicts.getElementConflicts()) { - if (elementConflict.getType() == VspModel) { - elementConflicts.add( - new ConflictInfo(elementConflict.getId(), NetworkPackage, NetworkPackage.name())); - vspModelConflicted = true; - continue; - } - if (!FILTERED_OUT_TYPES.contains(elementConflict.getType())) { - elementConflicts.add(elementConflict); - } + + @Override + public boolean isConflicted(String itemId, Version version) { + return vspMergeDao.isConflicted(itemId, version); + } + + @Override + public void finalizeMerge(String itemId, Version version) { + if (!conflictsDao.isConflicted(itemId, version)) { + vspMergeDao.applyConflictResolution(itemId, version); + } } - if (!vspModelConflicted && vspMergeDao.isConflicted(itemId, version)) { - elementConflicts - .add(new ConflictInfo(VSP_MODEL_CONFLICT_ID, NetworkPackage, NetworkPackage.name())); + @Override + public void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts) { + List elementConflicts = new ArrayList<>(); + boolean vspModelConflicted = false; + for (ConflictInfo elementConflict : conflicts.getElementConflicts()) { + if (elementConflict.getType() == VspModel) { + elementConflicts.add(new ConflictInfo(elementConflict.getId(), NetworkPackage, NetworkPackage.name())); + vspModelConflicted = true; + continue; + } + if (!FILTERED_OUT_TYPES.contains(elementConflict.getType())) { + elementConflicts.add(elementConflict); + } + } + if (!vspModelConflicted && vspMergeDao.isConflicted(itemId, version)) { + elementConflicts.add(new ConflictInfo(VSP_MODEL_CONFLICT_ID, NetworkPackage, NetworkPackage.name())); + } + conflicts.setElementConflicts(elementConflicts); } - conflicts.setElementConflicts(elementConflicts); - } - - @Override - public Optional getConflict(String itemId, Version version, String conflictId) { - return VSP_MODEL_CONFLICT_ID.equals(conflictId) - ? Optional.of(buildVspModelConflict(conflictId)) - : Optional.empty(); - } - - @Override - public void postGetConflict(String itemId, Version version, Conflict conflict) { - if (conflict.getType() == VspModel) { - Conflict vspModelConflict = buildVspModelConflict(null); - conflict.setType(vspModelConflict.getType()); - conflict.setName(vspModelConflict.getName()); - conflict.setYours(vspModelConflict.getYours()); - conflict.setTheirs(vspModelConflict.getTheirs()); + @Override + public Optional getConflict(String itemId, Version version, String conflictId) { + return VSP_MODEL_CONFLICT_ID.equals(conflictId) ? Optional.of(buildVspModelConflict(conflictId)) : Optional.empty(); } - } - @Override - public void preResolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution) { - if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { - return; + @Override + public void postGetConflict(String itemId, Version version, Conflict conflict) { + if (conflict.getType() == VspModel) { + Conflict vspModelConflict = buildVspModelConflict(null); + conflict.setType(vspModelConflict.getType()); + conflict.setName(vspModelConflict.getName()); + conflict.setYours(vspModelConflict.getYours()); + conflict.setTheirs(vspModelConflict.getTheirs()); + } } - resolveDependantConflicts(itemId, version, conflictId, resolution); - } - - @Override - public boolean resolveConflict(String itemId, Version version, String conflictId, - ConflictResolution resolution) { - if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { - vspMergeDao.updateConflictResolution(itemId, version, - com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); - return true; + + @Override + public void preResolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution) { + if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { + return; + } + resolveDependantConflicts(itemId, version, conflictId, resolution); } - Conflict conflict = conflictsDao.getConflict(itemId, version, conflictId); - if (conflict == null) { - throw getConflictNotExistException(itemId, version, conflictId); + + @Override + public boolean resolveConflict(String itemId, Version version, String conflictId, ConflictResolution resolution) { + if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { + vspMergeDao + .updateConflictResolution(itemId, version, com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); + return true; + } + Conflict conflict = conflictsDao.getConflict(itemId, version, conflictId); + if (conflict == null) { + throw getConflictNotExistException(itemId, version, conflictId); + } + if (conflict.getType() == VspModel) { + vspMergeDao + .updateConflictResolution(itemId, version, com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); + conflictsDao.resolveConflict(itemId, version, conflictId, + new ConflictResolution(conflict.getTheirs() == null ? Resolution.YOURS : Resolution.THEIRS)); + return true; + } + return false; } - if (conflict.getType() == VspModel) { - vspMergeDao.updateConflictResolution(itemId, version, - com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); - conflictsDao.resolveConflict(itemId, version, conflictId, new ConflictResolution( - conflict.getTheirs() == null ? Resolution.YOURS : Resolution.THEIRS)); - return true; + private void resolveDependantConflicts(String itemId, Version version, String conflictId, ConflictResolution resolution) { + ItemVersionConflict conflicts = conflictsDao.getConflict(itemId, version); + Set conflictDependantTypes = ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.get(findConflictById(conflicts, conflictId).getType()); + if (conflictDependantTypes == null) { + return; + } + findConflictsByTypes(conflicts, conflictDependantTypes) + .forEach(dependantConflict -> conflictsDao.resolveConflict(itemId, version, dependantConflict.getId(), resolution)); } - return false; - } - private void resolveDependantConflicts(String itemId, Version version, String conflictId, - ConflictResolution resolution) { - ItemVersionConflict conflicts = conflictsDao.getConflict(itemId, version); + private ConflictInfo findConflictById(ItemVersionConflict versionConflicts, String conflictId) { + return versionConflicts.getElementConflicts().stream().filter(elementConflict -> conflictId.equals(elementConflict.getId())).findFirst() + .orElseThrow(() -> new IllegalStateException(String.format("Conflict Id %s does not exist on conflicts list", conflictId))); + } - Set conflictDependantTypes = - ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES - .get(findConflictById(conflicts, conflictId).getType()); + private Collection findConflictsByTypes(ItemVersionConflict versionConflicts, Set elementTypes) { + return versionConflicts.getElementConflicts().stream().filter(elementConflict -> elementTypes.contains(elementConflict.getType())) + .collect(Collectors.toList()); + } - if (conflictDependantTypes == null) { - return; + private Conflict buildVspModelConflict(String conflictId) { + Conflict conflict = new Conflict(conflictId, NetworkPackage, NetworkPackage.name()); + Map yours = new HashMap<>(); + yours.put("File", "Local (Me)"); + conflict.setYours(yours); + Map theirs = new HashMap<>(); + theirs.put("File", "Last Committed"); + conflict.setTheirs(theirs); + return conflict; } - findConflictsByTypes(conflicts, conflictDependantTypes) - .forEach(dependantConflict -> - conflictsDao.resolveConflict(itemId, version, dependantConflict.getId(), resolution)); - } - - private ConflictInfo findConflictById(ItemVersionConflict versionConflicts, - String conflictId) { - return versionConflicts.getElementConflicts().stream() - .filter(elementConflict -> conflictId.equals(elementConflict.getId())) - .findFirst() - .orElseThrow(() -> new IllegalStateException( - String.format("Conflict Id %s does not exist on conflicts list", conflictId))); - } - - private Collection findConflictsByTypes(ItemVersionConflict versionConflicts, - Set elementTypes) { - return versionConflicts.getElementConflicts().stream() - .filter(elementConflict -> elementTypes.contains(elementConflict.getType())) - .collect(Collectors.toList()); - } - - private Conflict buildVspModelConflict(String conflictId) { - Conflict conflict = new Conflict(conflictId, NetworkPackage, NetworkPackage.name()); - - Map yours = new HashMap<>(); - yours.put("File", "Local (Me)"); - conflict.setYours(yours); - - Map theirs = new HashMap<>(); - theirs.put("File", "Last Committed"); - conflict.setTheirs(theirs); - return conflict; - } - - private CoreException getConflictNotExistException(String itemId, Version version, - String conflictId) { - return new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId(ELEMENT_CONFLICT_NOT_EXIST_ERR_ID) - .withMessage( - String.format(ELEMENT_CONFLICT_NOT_EXISTS_MSG, itemId, version.getId(), conflictId)) - .build()); - } + private CoreException getConflictNotExistException(String itemId, Version version, String conflictId) { + return new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(ELEMENT_CONFLICT_NOT_EXIST_ERR_ID) + .withMessage(String.format(ELEMENT_CONFLICT_NOT_EXISTS_MSG, itemId, version.getId(), conflictId)).build()); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java index 1d5fd16ee1..c1839373fd 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig; +import java.util.Collection; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; -import java.util.Collection; - - public interface ApplicationConfig { - ConfigurationData getConfigurationData(String namespace, String key); + ConfigurationData getConfigurationData(String namespace, String key); - void insertValue(String namespace, String key, String value); + void insertValue(String namespace, String key, String value); - Collection getListOfConfigurationByNamespace(String namespace); + Collection getListOfConfigurationByNamespace(String namespace); } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java index c751b98c7e..8865273fef 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/ApplicationConfigFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; - public abstract class ApplicationConfigFactory extends AbstractComponentFactory { - public static ApplicationConfigFactory getInstance() { - return AbstractFactory.getInstance(ApplicationConfigFactory.class); - } + public static ApplicationConfigFactory getInstance() { + return AbstractFactory.getInstance(ApplicationConfigFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java index a4c582744a..028cff9de4 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; - public interface ApplicationConfigDao extends BaseDao { - long getValueTimestamp(String namespace, String key); + long getValueTimestamp(String namespace, String key); - ConfigurationData getConfigurationData(String namespace, String key); + ConfigurationData getConfigurationData(String namespace, String key); } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java index f60e4a9010..0f03972fd5 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/ApplicationConfigDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class ApplicationConfigDaoFactory - extends AbstractComponentFactory { +public abstract class ApplicationConfigDaoFactory extends AbstractComponentFactory { - public static ApplicationConfigDaoFactory getInstance() { - return AbstractFactory.getInstance(ApplicationConfigDaoFactory.class); - } + public static ApplicationConfigDaoFactory getInstance() { + return AbstractFactory.getInstance(ApplicationConfigDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java index b7cd576557..926266bd0a 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoCassandraImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.dao.impl; import com.datastax.driver.core.ResultSet; @@ -26,6 +25,8 @@ import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.Collection; +import java.util.Objects; import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; @@ -33,85 +34,72 @@ import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; -import java.util.Collection; -import java.util.Objects; +public class ApplicationConfigDaoCassandraImpl extends CassandraBaseDao implements ApplicationConfigDao { + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper mapper = noSqlDb.getMappingManager().mapper(ApplicationConfigEntity.class); + private static final ApplicationConfigAccessor accessor = noSqlDb.getMappingManager().createAccessor(ApplicationConfigAccessor.class); -public class ApplicationConfigDaoCassandraImpl extends CassandraBaseDao - implements - ApplicationConfigDao { - - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(ApplicationConfigEntity.class); - private static final ApplicationConfigAccessor accessor = - noSqlDb.getMappingManager().createAccessor(ApplicationConfigAccessor.class); - - @Override - protected Mapper getMapper() { - return mapper; - } - - @Override - protected Object[] getKeys(ApplicationConfigEntity entity) { - return new Object[]{entity.getNamespace(), entity.getKey(), entity.getValue()}; - } - - @Override - public void create(ApplicationConfigEntity entity) { - accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); - } - - @Override - public void update(ApplicationConfigEntity entity) { - accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); - } - - @Override - public ApplicationConfigEntity get(ApplicationConfigEntity entity) { - return accessor.get(entity.getNamespace(), entity.getKey()); - } - - @Override - public Collection list(ApplicationConfigEntity entity) { - return accessor.list(entity.getNamespace()).all(); - } - - @Override - public long getValueTimestamp(String namespace, String key) { - ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); - - return resultSet.one().getLong("writetime(value)"); - } - - @Override - public ConfigurationData getConfigurationData(String namespace, String key) { - //String value = accessor.getValue(namespace, key).one().getString("value"); - ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); - Row one = resultSet.one(); - - if (Objects.nonNull(one)) { - return new ConfigurationData(one.getString("value"), one.getLong("writetime(value)")); + @Override + protected Mapper getMapper() { + return mapper; } - return null; - } + @Override + protected Object[] getKeys(ApplicationConfigEntity entity) { + return new Object[]{entity.getNamespace(), entity.getKey(), entity.getValue()}; + } + @Override + public void create(ApplicationConfigEntity entity) { + accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); + } - @Accessor - interface ApplicationConfigAccessor { + @Override + public void update(ApplicationConfigEntity entity) { + accessor.updateApplicationConfigData(entity.getNamespace(), entity.getKey(), entity.getValue()); + } - @Query("select namespace, key, value from application_config where namespace=?") - Result list(String namespace); + @Override + public ApplicationConfigEntity get(ApplicationConfigEntity entity) { + return accessor.get(entity.getNamespace(), entity.getKey()); + } - @Query("insert into application_config (namespace, key, value) values (?,?,?)") - ResultSet updateApplicationConfigData(String namespace, String key, String value); + @Override + public Collection list(ApplicationConfigEntity entity) { + return accessor.list(entity.getNamespace()).all(); + } + + @Override + public long getValueTimestamp(String namespace, String key) { + ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); + return resultSet.one().getLong("writetime(value)"); + } + + @Override + public ConfigurationData getConfigurationData(String namespace, String key) { + //String value = accessor.getValue(namespace, key).one().getString("value"); + ResultSet resultSet = accessor.getValueAndTimestampOfConfigurationValue(namespace, key); + Row one = resultSet.one(); + if (Objects.nonNull(one)) { + return new ConfigurationData(one.getString("value"), one.getLong("writetime(value)")); + } + return null; + } + + @Accessor + interface ApplicationConfigAccessor { - @Query("select namespace, key, value from application_config where namespace=? and key=?") - ApplicationConfigEntity get(String namespace, String key); + @Query("select namespace, key, value from application_config where namespace=?") + Result list(String namespace); - @Query("select value, writetime(value) from application_config where namespace=? and key=?") - ResultSet getValueAndTimestampOfConfigurationValue(String namespace, String key); + @Query("insert into application_config (namespace, key, value) values (?,?,?)") + ResultSet updateApplicationConfigData(String namespace, String key, String value); - } + @Query("select namespace, key, value from application_config where namespace=? and key=?") + ApplicationConfigEntity get(String namespace, String key); + + @Query("select value, writetime(value) from application_config where namespace=? and key=?") + ResultSet getValueAndTimestampOfConfigurationValue(String namespace, String key); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java index 23dde63e18..28bee62f93 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/impl/ApplicationConfigDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.dao.impl; import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; - public class ApplicationConfigDaoFactoryImpl extends ApplicationConfigDaoFactory { - private static final ApplicationConfigDao INSTANCE = new ApplicationConfigDaoCassandraImpl(); - @Override - public ApplicationConfigDao createInterface() { - return INSTANCE; - } + private static final ApplicationConfigDao INSTANCE = new ApplicationConfigDaoCassandraImpl(); + + @Override + public ApplicationConfigDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java index 64d7f1a31a..1a8ac63966 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/dao/type/ApplicationConfigEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.dao.type; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; @@ -36,9 +34,9 @@ import lombok.Setter; @Table(keyspace = "dox", name = "application_config") public class ApplicationConfigEntity { - @PartitionKey - private String namespace; - @ClusteringColumn - private String key; - private String value; + @PartitionKey + private String namespace; + @ClusteringColumn + private String key; + private String value; } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java index eebd3320f0..100bf38483 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.impl; import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; - public class ApplicationConfigFactoryImpl extends ApplicationConfigFactory { - private static final ApplicationConfig INSTANCE = new ApplicationConfigImpl(); + private static final ApplicationConfig INSTANCE = new ApplicationConfigImpl(); - @Override - public ApplicationConfig createInterface() { - return INSTANCE; - } + @Override + public ApplicationConfig createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java index 16cd1bce17..42ea334d9c 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/impl/ApplicationConfigImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.impl; +import java.util.Collection; +import java.util.Objects; import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; @@ -29,43 +30,31 @@ import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import java.util.Collection; -import java.util.Objects; - public class ApplicationConfigImpl implements ApplicationConfig { - private static final ApplicationConfigDao applicationConfigDao = - ApplicationConfigDaoFactory.getInstance().createInterface(); - private static final String CONFIGURATION_SEARCH_ERROR = "CONFIGURATION_NOT_FOUND"; - private static final String CONFIGURATION_SEARCH_ERROR_MSG = - "Configuration for namespace %s and key %s was not found"; - - @Override - public ConfigurationData getConfigurationData(String namespace, String key) { - ConfigurationData configurationData = applicationConfigDao.getConfigurationData(namespace, key); - - if (Objects.isNull(configurationData)) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId(CONFIGURATION_SEARCH_ERROR) - .withMessage(String.format(CONFIGURATION_SEARCH_ERROR_MSG, namespace, key)) - .build()); + private static final ApplicationConfigDao applicationConfigDao = ApplicationConfigDaoFactory.getInstance().createInterface(); + private static final String CONFIGURATION_SEARCH_ERROR = "CONFIGURATION_NOT_FOUND"; + private static final String CONFIGURATION_SEARCH_ERROR_MSG = "Configuration for namespace %s and key %s was not found"; + + @Override + public ConfigurationData getConfigurationData(String namespace, String key) { + ConfigurationData configurationData = applicationConfigDao.getConfigurationData(namespace, key); + if (Objects.isNull(configurationData)) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(CONFIGURATION_SEARCH_ERROR) + .withMessage(String.format(CONFIGURATION_SEARCH_ERROR_MSG, namespace, key)).build()); + } + return configurationData; } - return configurationData; - } - - @Override - public void insertValue(String namespace, String key, String value) { - ApplicationConfigEntity applicationConfigEntity = - new ApplicationConfigEntity(namespace, key, value); - applicationConfigDao.create(applicationConfigEntity); - } + @Override + public void insertValue(String namespace, String key, String value) { + ApplicationConfigEntity applicationConfigEntity = new ApplicationConfigEntity(namespace, key, value); + applicationConfigDao.create(applicationConfigEntity); + } - @Override - public Collection getListOfConfigurationByNamespace(String namespace) { - ApplicationConfigEntity applicationConfigEntity = - new ApplicationConfigEntity(namespace, null, null); - return applicationConfigDao.list(applicationConfigEntity); - } + @Override + public Collection getListOfConfigurationByNamespace(String namespace) { + ApplicationConfigEntity applicationConfigEntity = new ApplicationConfigEntity(namespace, null, null); + return applicationConfigDao.list(applicationConfigEntity); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java index 6149fc6ce4..7663e42bb8 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/main/java/org/openecomp/core/utilities/applicationconfig/type/ConfigurationData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.applicationconfig.type; import lombok.AllArgsConstructor; @@ -29,6 +28,6 @@ import lombok.Setter; @AllArgsConstructor public class ConfigurationData { - private String value; - private long timeStamp; + private String value; + private long timeStamp; } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java index 12956417dd..87da8fc6e4 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/api/AbstractFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,20 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.factory.api; import org.openecomp.core.factory.impl.AbstractFactoryBase; /** - * This class provides generic implementation of an abstract factory. Components exposed as Java - * interfaces should have their own concrete factories derived from the given class. This assures - * code alignment and consistency across all Service Management components. - * The class actually - * uses singleton pattern to instantiate and reuse just one instance of a factory. Therefore, each - * factory implementation has to be thread-safe. - * In a general case, the hierarchy of - * factory objects for an Java interface IUknown may look as follows: + * This class provides generic implementation of an abstract factory. Components exposed as Java interfaces should have their own concrete factories + * derived from the given class. This assures code alignment and consistency across all Service Management components. The class actually uses + * singleton pattern to instantiate and reuse just one instance of a factory. Therefore, each factory implementation has to be thread-safe. In + * a general case, the hierarchy of factory objects for an Java interface IUknown may look as follows: *
      *                     AbstractFactory<IUnknown>
      *                                ^
    @@ -42,12 +37,10 @@ import org.openecomp.core.factory.impl.AbstractFactoryBase;
      *                      |                   |
      *             BaselineFactoryImpl   CustomFactoryImpl
      * 
    - * Where the classes responsibility is:
    • Abstract factory - common logic to retrieve the - * implementation class name from a central repository.
    • Concrete factory - abstract class - * that only exposes to application layer the type specific API such as:
      • public static - * ConcreteFactory getInstance()
    • Baseline factory - out of the box - * implementation of concrete factory (that can be replaced by a custom one depending on customer - * needs) which actually implements method:
      • public IUnknown createInterface()
      • + * Where the classes responsibility is:
        • Abstract factory - common logic to retrieve the implementation class name from a central + * repository.
        • Concrete factory - abstract class that only exposes to application layer the type specific API such as:
          • public + * static ConcreteFactory getInstance()
        • Baseline factory - out of the box implementation of concrete factory (that can be replaced + * by a custom one depending on customer needs) which actually implements method:
          • public IUnknown createInterface()
          • *
        The normal concrete factory class may look like: *
          * public abstract class ConcreteFactory extends AbstractFactory<IUnknown> {
        @@ -64,18 +57,15 @@ import org.openecomp.core.factory.impl.AbstractFactoryBase;
          */
         public abstract class AbstractFactory extends AbstractFactoryBase {
         
        -
        -  /**
        -   * Returns the interface implementor instance.
        -   * Note: It's up to the concrete factory to decide on the actual
        -   * implementation of the returned interface. Therefore, the call can get the
        -   * same instance per each call in case of singleton implementation or new
        -   * instance otherwise. However, the API consumer may not assume anything
        -   * regarding the underlying logic and has always go through the factory to
        -   * obtain the reference.
        -   *
        -   * @return Implementor of the exposed Java interface.
        -   */
        -  public abstract I createInterface();
        -
        +    /**
        +     * Returns the interface implementor instance.
        +     * Note: It's up to the concrete factory to decide on the actual
        +     * implementation of the returned interface. Therefore, the call can get the same instance per each call in case of singleton implementation or
        +     * new instance otherwise. However, the API consumer may not assume anything regarding the underlying logic and has always go through the factory
        +     * to obtain the reference.
        +     *
        +     * @return Implementor of the exposed Java interface.
        +     */
        +    public abstract I createInterface();
         } // End of class
        +
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java
        index 3a117ef063..41bfeab826 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java
        @@ -13,30 +13,30 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.factory.impl;
         
         public abstract class AbstractFactoryBase {
         
        -  /**
        -   * Instantiates the configured implementation of an abstract factory.
        -   *
        -   * @param          Type specific abstract factory for concrete Java interface
        -   * @param factoryType Java class of type specific abstract factory
        -   * @return Instance of implementation class
        -   */
        -  public static  F getInstance(Class factoryType) {
        -      return FactoryManager.getInstance().getFactoryInstance(factoryType);
        -  }
        +    /**
        +     * Instantiates the configured implementation of an abstract factory.
        +     *
        +     * @param          Type specific abstract factory for concrete Java interface
        +     * @param factoryType Java class of type specific abstract factory
        +     * @return Instance of implementation class
        +     */
        +    public static  F getInstance(Class factoryType) {
        +        return FactoryManager.getInstance().getFactoryInstance(factoryType);
        +    }
        +
        +    protected void init() {
        +        // allows custom initialization
         
        -  protected void init() {
        -    // allows custom initialization
        -    // noop by default
        -  }
        +        // noop by default
        +    }
         
        -  protected void stop() {
        -    // allows custom shutdown
        -    // noop by default
        -  }
        +    protected void stop() {
        +        // allows custom shutdown
         
        +        // noop by default
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/FactoryManager.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/FactoryManager.java
        index ec2d93f35b..26816aaafe 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/FactoryManager.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/FactoryManager.java
        @@ -16,7 +16,6 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.factory.impl;
         
         import com.amdocs.zusammen.utils.facade.impl.FactoryConfig;
        @@ -33,9 +32,8 @@ public class FactoryManager {
             private static final FactoryManager instance = new FactoryManager();
             private static final String ERROR_CODE_E0001 = "E0001";
             /**
        -     * Temporary registry of default implementations. The map keeps class names rather then class
        -     * types to allow unloading of those classes from memory by garbage collector if factory is not
        -     * actually used.
        +     * Temporary registry of default implementations. The map keeps class names rather then class types to allow unloading of those classes from
        +     * memory by garbage collector if factory is not actually used.
              */
             private final Map factoryRegistry = new ConcurrentHashMap<>();
             /**
        @@ -43,7 +41,6 @@ public class FactoryManager {
              */
             private final Map factoryInstanceMap = new ConcurrentHashMap<>();
         
        -
             private FactoryManager() {
                 initializeFactoryRegistry();
             }
        @@ -54,17 +51,13 @@ public class FactoryManager {
         
             private void initializeFactoryRegistry() {
                 final Map factoryMap = FactoryConfig.getFactoriesMap();
        -
                 for (final Map.Entry entry : factoryMap.entrySet()) {
                     final String abstractClassName = entry.getKey();
                     final String concreteTypeName = entry.getValue();
        -
                     if (StringUtils.isEmpty(concreteTypeName)) {
                         throw new CoreException(
        -                    new ErrorCode.ErrorCodeBuilder().withId("E0003")
        -                        .withMessage("Missing configuration value:" + concreteTypeName + ".")
        +                    new ErrorCode.ErrorCodeBuilder().withId("E0003").withMessage("Missing configuration value:" + concreteTypeName + ".")
                                 .withCategory(ErrorCategory.SYSTEM).build());
        -
                     }
                     registerFactory(abstractClassName, concreteTypeName);
                 }
        @@ -80,32 +73,26 @@ public class FactoryManager {
             @SuppressWarnings("unchecked")
             public  F getFactoryInstance(Class factoryType) {
                 if (factoryType == null) {
        -            throw new CoreException(
        -                new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001)
        -                    .withMessage("Mandatory input factory type.").withCategory(ErrorCategory.SYSTEM)
        -                    .build());
        -
        +            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001).withMessage("Mandatory input factory type.")
        +                .withCategory(ErrorCategory.SYSTEM).build());
                 }
                 final String factoryTypeName = factoryType.getName();
                 // Check if the factory is already cached
                 if (factoryInstanceMap.get(factoryTypeName) == null) {
                     //if not, create a new one and cache it
        +
                     // Get the implementation class name
                     final String implName = factoryRegistry.get(factoryTypeName);
        -
                     if (StringUtils.isEmpty(implName)) {
                         throw new CoreException(
        -                    new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001)
        -                        .withMessage("Mandatory input factory implementation.")
        +                    new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001).withMessage("Mandatory input factory implementation.")
                                 .withCategory(ErrorCategory.SYSTEM).build());
                     }
        -
                     F factory = CommonMethods.newInstance(implName, factoryType);
                     factory.init();
                     // Cache the instantiated singleton
                     factoryInstanceMap.putIfAbsent(factoryTypeName, factory);
                 }
        -
                 return (F) factoryInstanceMap.get(factoryTypeName);
             }
         
        @@ -115,6 +102,7 @@ public class FactoryManager {
         
             /**
              * Unregister factory and removes the cached instance if any.
        +     *
              * @param factoryName the factory name to unregister
              */
             public void unregisterFactory(final String factoryName) {
        @@ -134,10 +122,9 @@ public class FactoryManager {
             public  void removeFactoryInstance(Class factory) {
                 if (factory == null) {
                     throw new CoreException(
        -                new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001).withMessage("Mandatory input factory.")
        -                    .withCategory(ErrorCategory.SYSTEM).build());
        +                new ErrorCode.ErrorCodeBuilder().withId(ERROR_CODE_E0001).withMessage("Mandatory input factory.").withCategory(ErrorCategory.SYSTEM)
        +                    .build());
                 }
        -
                 factoryInstanceMap.remove(factory.getName());
             }
         
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java
        index f4e1a85fee..a98ba44cf9 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/AbstractContextFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,11 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.factory;
         
         import org.openecomp.core.factory.impl.AbstractFactoryBase;
         
         public abstract class AbstractContextFactory extends AbstractFactoryBase {
        -  public abstract I createInterface(C contextType);
        +
        +    public abstract I createInterface(C contextType);
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java
        index 31df923bdd..cfe50f1619 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoriesConfigImpl.java
        @@ -13,45 +13,41 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.factory;
         
        -
        -import org.openecomp.core.factory.api.FactoriesConfiguration;
        -import org.openecomp.core.utilities.file.FileUtils;
        -import org.openecomp.core.utilities.json.JsonUtil;
        -import org.openecomp.sdc.common.errors.SdcConfigurationException;
        -
         import java.io.IOException;
         import java.io.InputStream;
         import java.net.URL;
         import java.util.HashMap;
         import java.util.List;
         import java.util.Map;
        +import org.openecomp.core.factory.api.FactoriesConfiguration;
        +import org.openecomp.core.utilities.file.FileUtils;
        +import org.openecomp.core.utilities.json.JsonUtil;
        +import org.openecomp.sdc.common.errors.SdcConfigurationException;
         
         public final class FactoriesConfigImpl implements FactoriesConfiguration {
         
        -  private final Map factoryConfigurationMap = new HashMap();
        +    private final Map factoryConfigurationMap = new HashMap();
         
        -  public FactoriesConfigImpl() {
        -    init();
        -  }
        +    public FactoriesConfigImpl() {
        +        init();
        +    }
         
        -  @SuppressWarnings("unchecked")
        -  @Override
        -  public Map getFactoriesMap() {
        -    return factoryConfigurationMap;
        -  }
        +    @SuppressWarnings("unchecked")
        +    @Override
        +    public Map getFactoriesMap() {
        +        return factoryConfigurationMap;
        +    }
         
        -  private void init() {
        -    final List factoryConfigUrlList = FileUtils.getAllLocations("factoryConfiguration.json");
        -    for (final URL factoryConfigUrl : factoryConfigUrlList) {
        -      try (InputStream stream = factoryConfigUrl.openStream()) {
        -        factoryConfigurationMap.putAll(JsonUtil.json2Object(stream, Map.class));
        -      } catch (final IOException e) {
        -        throw new SdcConfigurationException("Failed to initialize Factory from '" + factoryConfigUrl.getPath() +"'", e);
        -      }
        +    private void init() {
        +        final List factoryConfigUrlList = FileUtils.getAllLocations("factoryConfiguration.json");
        +        for (final URL factoryConfigUrl : factoryConfigUrlList) {
        +            try (InputStream stream = factoryConfigUrl.openStream()) {
        +                factoryConfigurationMap.putAll(JsonUtil.json2Object(stream, Map.class));
        +            } catch (final IOException e) {
        +                throw new SdcConfigurationException("Failed to initialize Factory from '" + factoryConfigUrl.getPath() + "'", e);
        +            }
        +        }
             }
        -  }
         }
        -
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java
        index 7dbf921ebf..0c118fc2c9 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/FactoryConfig.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.factory;
         
         import java.util.Map;
        @@ -26,14 +25,13 @@ import org.openecomp.core.utilities.CommonMethods;
         
         public final class FactoryConfig {
         
        -  private static final FactoriesConfiguration INSTANCE = CommonMethods.newInstance(
        -      "org.openecomp.core.factory.FactoriesConfigImpl", FactoriesConfiguration.class);
        -
        -  private FactoryConfig() {
        +    private static final FactoriesConfiguration INSTANCE = CommonMethods
        +        .newInstance("org.openecomp.core.factory.FactoriesConfigImpl", FactoriesConfiguration.class);
         
        -  }
        +    private FactoryConfig() {
        +    }
         
        -  public static Map getFactoriesMap() {
        -    return INSTANCE.getFactoriesMap();
        -  }
        +    public static Map getFactoriesMap() {
        +        return INSTANCE.getFactoriesMap();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java
        index 3de0d88f43..0a091c1864 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/AbstractComponentFactory.java
        @@ -4,17 +4,17 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.factory.api;
         
         public abstract class AbstractComponentFactory extends AbstractFactory {
        +
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java
        index 8086181204..b1da7950ce 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-core/src/main/java/org/openecomp/core/factory/api/FactoriesConfiguration.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,13 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.factory.api;
         
         import java.util.Map;
         
        -
         public interface FactoriesConfiguration {
         
        -  Map getFactoriesMap();
        +    Map getFactoriesMap();
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java
        index fa23b51742..e46cade267 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/BaseDao.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao;
         
         import java.util.Collection;
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java
        index 36dfefa840..02db64ec66 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDao.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao;
         
         import org.openecomp.core.dao.types.UniqueValueEntity;
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java
        index 022ad8e09d..c653c8dc4f 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/UniqueValueDaoFactory.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java
        index 24038b9b0c..d107c9f388 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/dao/types/UniqueValueEntity.java
        @@ -17,12 +17,10 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao.types;
         
         import com.datastax.driver.mapping.annotations.PartitionKey;
         import com.datastax.driver.mapping.annotations.Table;
        -
         import lombok.AllArgsConstructor;
         import lombok.Getter;
         import lombok.NoArgsConstructor;
        @@ -37,7 +35,6 @@ public class UniqueValueEntity {
         
             @PartitionKey
             private String type;
        -
             @PartitionKey(value = 1)
             private String value;
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java
        index ff4661c44d..844ce88265 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/api/NoSqlDb.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.nosqldb.api;
         
         import com.datastax.driver.core.ResultSet;
        @@ -26,7 +25,6 @@ import com.datastax.driver.mapping.MappingManager;
         public interface NoSqlDb {
         
             //TODO: remove cassandra types from here!! (like done in SDC...).
        -
             void insert(String tableName, String[] colNames, Object[] values);
         
             ResultSet execute(String statement);
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java
        index 31b6f6a505..e86b64e1aa 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/nosqldb/factory/NoSqlDbFactory.java
        @@ -17,18 +17,15 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.nosqldb.factory;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         
        -
         public abstract class NoSqlDbFactory extends AbstractComponentFactory {
         
             public static NoSqlDbFactory getInstance() {
        -
                 return AbstractFactory.getInstance(NoSqlDbFactory.class);
             }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java
        index aded1fa99f..a70bc47864 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java
        @@ -13,11 +13,9 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.util;
         
         import java.util.Optional;
        -
         import org.apache.commons.lang3.ArrayUtils;
         import org.openecomp.core.dao.UniqueValueDao;
         import org.openecomp.core.dao.types.UniqueValueEntity;
        @@ -31,13 +29,24 @@ public class UniqueValueUtil {
             private static final String UNIQUE_VALUE_VIOLATION = "UNIQUE_VALUE_VIOLATION";
             private static final String UNIQUE_VALUE_VIOLATION_MSG = "%s with the value '%s' already exists.";
             private static final char FORMATTED_UNIQUE_VALUE_SEPARATOR = '_';
        -
             private final UniqueValueDao uniqueValueDao;
         
             public UniqueValueUtil(UniqueValueDao uniqueValueDao) {
                 this.uniqueValueDao = uniqueValueDao;
             }
         
        +    private static Optional formatValue(String[] uniqueCombination) {
        +        if (uniqueCombination == null || uniqueCombination.length == 0 || getValueWithoutContext(uniqueCombination) == null) {
        +            return Optional.empty();
        +        }
        +        uniqueCombination[uniqueCombination.length - 1] = getValueWithoutContext(uniqueCombination).toLowerCase();
        +        return Optional.of(CommonMethods.arrayToSeparatedString(uniqueCombination, FORMATTED_UNIQUE_VALUE_SEPARATOR));
        +    }
        +
        +    private static String getValueWithoutContext(String... uniqueCombination) {
        +        return uniqueCombination[uniqueCombination.length - 1];
        +    }
        +
             /**
              * Create unique value.
              *
        @@ -49,7 +58,6 @@ public class UniqueValueUtil {
                 if (ArrayUtils.isNotEmpty(uniqueCombination)) {
                     originalEntityName = uniqueCombination[uniqueCombination.length - 1];
                 }
        -
                 Optional formattedValue = formatValue(uniqueCombination);
                 if (formattedValue.isPresent()) {
                     validateUniqueValue(type, formattedValue.get(), originalEntityName);
        @@ -64,9 +72,7 @@ public class UniqueValueUtil {
              * @param uniqueCombination the unique combination
              */
             public void deleteUniqueValue(String type, String... uniqueCombination) {
        -        formatValue(uniqueCombination).ifPresent(
        -                formattedValue -> uniqueValueDao.delete(new UniqueValueEntity(type, formattedValue)));
        -
        +        formatValue(uniqueCombination).ifPresent(formattedValue -> uniqueValueDao.delete(new UniqueValueEntity(type, formattedValue)));
             }
         
             /**
        @@ -77,11 +83,10 @@ public class UniqueValueUtil {
              * @param newValue      the new value
              * @param uniqueContext the unique context
              */
        -    public void updateUniqueValue(String type, String oldValue, String newValue,
        -                                  String... uniqueContext) {
        +    public void updateUniqueValue(String type, String oldValue, String newValue, String... uniqueContext) {
                 if (newValue == null || !newValue.equalsIgnoreCase(oldValue)) {
        -            createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[] {newValue}));
        -            deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[] {oldValue}));
        +            createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{newValue}));
        +            deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{oldValue}));
                 }
             }
         
        @@ -96,7 +101,6 @@ public class UniqueValueUtil {
                 if (ArrayUtils.isNotEmpty(uniqueCombination)) {
                     originalEntityName = uniqueCombination[uniqueCombination.length - 1];
                 }
        -
                 Optional formattedValue = formatValue(uniqueCombination);
                 if (formattedValue.isPresent()) {
                     validateUniqueValue(type, formattedValue.get(), originalEntityName);
        @@ -105,12 +109,8 @@ public class UniqueValueUtil {
         
             private void validateUniqueValue(String type, String formattedValue, String originalEntityName) {
                 if (isUniqueValueOccupied(type, formattedValue)) {
        -            throw new CoreException(new ErrorCode.ErrorCodeBuilder()
        -                    .withCategory(ErrorCategory.APPLICATION)
        -                    .withId(UNIQUE_VALUE_VIOLATION)
        -                    .withMessage(String
        -                            .format(UNIQUE_VALUE_VIOLATION_MSG, type, originalEntityName))
        -                    .build());
        +            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(UNIQUE_VALUE_VIOLATION)
        +                .withMessage(String.format(UNIQUE_VALUE_VIOLATION_MSG, type, originalEntityName)).build());
                 }
             }
         
        @@ -120,28 +120,10 @@ public class UniqueValueUtil {
              * @return true if the unique value is occupied, false otherwise
              */
             public boolean isUniqueValueOccupied(String type, String... uniqueCombination) {
        -        return formatValue(uniqueCombination)
        -                .map(formattedValue -> isUniqueValueOccupied(type, formattedValue))
        -                .orElse(false);
        +        return formatValue(uniqueCombination).map(formattedValue -> isUniqueValueOccupied(type, formattedValue)).orElse(false);
             }
         
             private boolean isUniqueValueOccupied(String type, String formattedValue) {
                 return uniqueValueDao.get(new UniqueValueEntity(type, formattedValue)) != null;
             }
        -
        -    private static Optional formatValue(String[] uniqueCombination) {
        -        if (uniqueCombination == null || uniqueCombination.length == 0
        -                || getValueWithoutContext(uniqueCombination) == null) {
        -            return Optional.empty();
        -        }
        -
        -        uniqueCombination[uniqueCombination.length - 1] =
        -                getValueWithoutContext(uniqueCombination).toLowerCase();
        -        return Optional.of(CommonMethods
        -                .arrayToSeparatedString(uniqueCombination, FORMATTED_UNIQUE_VALUE_SEPARATOR));
        -    }
        -
        -    private static String getValueWithoutContext(String... uniqueCombination) {
        -        return uniqueCombination[uniqueCombination.length - 1];
        -    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java
        index 1b3dbc4c6f..6205622cea 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/CassandraBaseDao.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,34 +17,34 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao.impl;
         
         import com.datastax.driver.mapping.Mapper;
         import org.openecomp.core.dao.BaseDao;
         
         public abstract class CassandraBaseDao implements BaseDao {
        -  protected abstract Mapper getMapper();
         
        -  protected abstract Object[] getKeys(T entity);
        +    protected abstract Mapper getMapper();
        +
        +    protected abstract Object[] getKeys(T entity);
         
        -  @Override
        -  public void create(T entity) {
        -    getMapper().save(entity);
        -  }
        +    @Override
        +    public void create(T entity) {
        +        getMapper().save(entity);
        +    }
         
        -  @Override
        -  public void update(T entity) {
        -    getMapper().save(entity);
        -  }
        +    @Override
        +    public void update(T entity) {
        +        getMapper().save(entity);
        +    }
         
        -  @Override
        -  public T get(T entity) {
        -    return getMapper().get(getKeys(entity));
        -  }
        +    @Override
        +    public T get(T entity) {
        +        return getMapper().get(getKeys(entity));
        +    }
         
        -  @Override
        -  public void delete(T entity) {
        -    getMapper().delete(entity);
        -  }
        +    @Override
        +    public void delete(T entity) {
        +        getMapper().delete(entity);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java
        index a2f34bd329..b80050b370 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueCassandraDaoImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,49 +17,43 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao.impl;
         
         import com.datastax.driver.mapping.Mapper;
         import com.datastax.driver.mapping.Result;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        +import java.util.Collection;
         import org.openecomp.core.dao.UniqueValueDao;
         import org.openecomp.core.dao.types.UniqueValueEntity;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         
        -import java.util.Collection;
        -
        -public class UniqueValueCassandraDaoImpl extends CassandraBaseDao implements
        -    UniqueValueDao {
        -
        -  private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        -  private static Mapper mapper =
        -      noSqlDb.getMappingManager().mapper(UniqueValueEntity.class);
        -  private static UniqueValueAccessor accessor =
        -      noSqlDb.getMappingManager().createAccessor(UniqueValueAccessor.class);
        +public class UniqueValueCassandraDaoImpl extends CassandraBaseDao implements UniqueValueDao {
         
        +    private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        +    private static Mapper mapper = noSqlDb.getMappingManager().mapper(UniqueValueEntity.class);
        +    private static UniqueValueAccessor accessor = noSqlDb.getMappingManager().createAccessor(UniqueValueAccessor.class);
         
        -  @Override
        -  protected Mapper getMapper() {
        -    return mapper;
        -  }
        +    @Override
        +    protected Mapper getMapper() {
        +        return mapper;
        +    }
         
        -  @Override
        -  protected Object[] getKeys(UniqueValueEntity entity) {
        -    return new Object[]{entity.getType(), entity.getValue()};
        -  }
        +    @Override
        +    protected Object[] getKeys(UniqueValueEntity entity) {
        +        return new Object[]{entity.getType(), entity.getValue()};
        +    }
         
        -  @Override
        -  public Collection list(UniqueValueEntity entity) {
        -    return accessor.listAll().all();
        -  }
        +    @Override
        +    public Collection list(UniqueValueEntity entity) {
        +        return accessor.listAll().all();
        +    }
         
        -  @Accessor
        -  interface UniqueValueAccessor {
        +    @Accessor
        +    interface UniqueValueAccessor {
         
        -    @Query("select * from unique_value")
        -    Result listAll();
        -  }
        +        @Query("select * from unique_value")
        +        Result listAll();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java
        index ac47de9b20..36c0b208c8 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/dao/impl/UniqueValueDaoFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,17 +17,17 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.dao.impl;
         
         import org.openecomp.core.dao.UniqueValueDao;
         import org.openecomp.core.dao.UniqueValueDaoFactory;
         
         public class UniqueValueDaoFactoryImpl extends UniqueValueDaoFactory {
        -  private static UniqueValueDao instance = new UniqueValueCassandraDaoImpl();
         
        -  @Override
        -  public UniqueValueDao createInterface() {
        -    return instance;
        -  }
        +    private static UniqueValueDao instance = new UniqueValueCassandraDaoImpl();
        +
        +    @Override
        +    public UniqueValueDao createInterface() {
        +        return instance;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java
        index 134d341d05..b62689d955 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,28 +17,25 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.nosqldb.impl.cassandra;
         
        -
         import com.datastax.driver.core.Session;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         
         public class CassandraNoSqlDbFactoryImpl extends NoSqlDbFactory {
         
        -  @Override
        -  public NoSqlDb createInterface() {
        -
        +    @Override
        +    public NoSqlDb createInterface() {
        +        return new CassandraNoSqlDbImpl(ReferenceHolder.CASSANDRA);
        +    }
         
        -    return new CassandraNoSqlDbImpl(ReferenceHolder.CASSANDRA);
        -  }
        +    protected void stop() {
        +        ReferenceHolder.CASSANDRA.close();
        +    }
         
        -  protected void stop() {
        -    ReferenceHolder.CASSANDRA.close();
        -  }
        +    private static class ReferenceHolder {
         
        -  private static class ReferenceHolder {
        -    private static final Session CASSANDRA = CassandraSessionFactory.getSession();
        -  }
        +        private static final Session CASSANDRA = CassandraSessionFactory.getSession();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java
        index 539fbcd92f..237c48d013 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java
        @@ -12,18 +12,17 @@
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
        -*/
        -
        + */
         package org.openecomp.core.nosqldb.impl.cassandra;
         
        -import com.datastax.driver.mapping.MappingManager;
         import com.datastax.driver.core.BoundStatement;
         import com.datastax.driver.core.Host;
         import com.datastax.driver.core.PreparedStatement;
         import com.datastax.driver.core.ResultSet;
         import com.datastax.driver.core.Session;
        -
        -
        +import com.datastax.driver.mapping.MappingManager;
        +import java.util.Set;
        +import java.util.stream.Collectors;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.util.CassandraUtils;
         import org.openecomp.core.utilities.CommonMethods;
        @@ -33,49 +32,34 @@ import org.openecomp.sdc.common.errors.ErrorCode;
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -import java.util.Set;
        -import java.util.stream.Collectors;
        -
         class CassandraNoSqlDbImpl implements NoSqlDb {
         
             private final Session session;
             private final String keySpace;
             private final MappingManager mappingManager;
        -
             private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
         
        -
             public CassandraNoSqlDbImpl(Session session) {
                 this.session = session;
                 this.keySpace = this.session.getLoggedKeyspace();
                 this.mappingManager = new MappingManager(this.session);
        -
             }
         
             @Override
             public void insert(String tableName, String[] colNames, Object[] values) {
                 if (colNames.length != values.length) {
        -            throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(
        -                    "number of colmuns[" + colNames.length + "] is not equal to the number of values["
        -                            + values.length + "].").withId("E0005").withCategory(ErrorCategory.APPLICATION)
        -                    .build());
        +            throw new CoreException((new ErrorCode.ErrorCodeBuilder())
        +                .withMessage("number of colmuns[" + colNames.length + "] is not equal to the number of values[" + values.length + "].")
        +                .withId("E0005").withCategory(ErrorCategory.APPLICATION).build());
                 }
        -
                 StringBuilder sb = new StringBuilder();
        -        sb.append("insert into ")
        -                .append(tableName)
        -                .append(" (")
        -                .append(CommonMethods.arrayToCommaSeparatedString(colNames))
        -                .append(") values (")
        -                .append(CommonMethods.duplicateStringWithDelimiter("?", ',', values.length))
        -                .append(")");
        +        sb.append("insert into ").append(tableName).append(" (").append(CommonMethods.arrayToCommaSeparatedString(colNames)).append(") values (")
        +            .append(CommonMethods.duplicateStringWithDelimiter("?", ',', values.length)).append(")");
                 log.info(sb.toString());
                 PreparedStatement prepared = session.prepare(sb.toString());
        -
                 BoundStatement bound;
                 bound = prepared.bind(values);
                 session.execute(bound);
        -
             }
         
             @Override
        @@ -85,21 +69,18 @@ class CassandraNoSqlDbImpl implements NoSqlDb {
         
             @Override
             public ResultSet execute(String statementName, Object... values) {
        -
                 String statement = CassandraUtils.getStatement(statementName);
                 if (statement == null) {
                     statement = statementName;
                 }
                 if (values != null) {
                     PreparedStatement prepared = session.prepare(statement);
        -
                     BoundStatement bound;
                     bound = prepared.bind(values);
                     return session.execute(bound);
                 } else {
                     return session.execute(statement);
                 }
        -
             }
         
             @Override
        @@ -111,10 +92,9 @@ class CassandraNoSqlDbImpl implements NoSqlDb {
             public String getVersion() {
                 try {
                     Set allHosts = this.session.getCluster().getMetadata().getAllHosts();
        -            Set versions = allHosts.stream().map(host -> host.getCassandraVersion().toString())
        -                    .collect(Collectors.toSet());
        +            Set versions = allHosts.stream().map(host -> host.getCassandraVersion().toString()).collect(Collectors.toSet());
                     return versions.stream().collect(Collectors.joining(","));
        -        } catch (Exception e){
        +        } catch (Exception e) {
                     log.error("Failed to retrieve version", e);
                     return "Failed to retrieve version";
                 }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java
        index a507017888..8f3d51d618 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraSessionFactory.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.nosqldb.impl.cassandra;
         
         import com.datastax.driver.core.Cluster;
        @@ -22,22 +21,23 @@ import com.datastax.driver.core.QueryOptions;
         import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
         import com.datastax.driver.core.SSLOptions;
         import com.datastax.driver.core.Session;
        -
        -
        -import com.datastax.driver.core.policies.*;
        -import org.openecomp.core.nosqldb.util.CassandraUtils;
        -import org.openecomp.sdc.common.errors.SdcConfigurationException;
        -import org.openecomp.sdc.common.session.SessionContextProviderFactory;
        -import org.openecomp.sdc.logging.api.Logger;
        -import org.openecomp.sdc.logging.api.LoggerFactory;
        -
        -import javax.net.ssl.SSLContext;
        -import javax.net.ssl.TrustManagerFactory;
        +import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
        +import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy;
        +import com.datastax.driver.core.policies.DefaultRetryPolicy;
        +import com.datastax.driver.core.policies.LoadBalancingPolicy;
        +import com.datastax.driver.core.policies.TokenAwarePolicy;
         import java.io.FileInputStream;
         import java.security.KeyStore;
         import java.security.SecureRandom;
         import java.util.Objects;
         import java.util.Optional;
        +import javax.net.ssl.SSLContext;
        +import javax.net.ssl.TrustManagerFactory;
        +import org.openecomp.core.nosqldb.util.CassandraUtils;
        +import org.openecomp.sdc.common.errors.SdcConfigurationException;
        +import org.openecomp.sdc.common.session.SessionContextProviderFactory;
        +import org.openecomp.sdc.logging.api.Logger;
        +import org.openecomp.sdc.logging.api.LoggerFactory;
         
         public class CassandraSessionFactory {
         
        @@ -60,57 +60,42 @@ public class CassandraSessionFactory {
                 String[] addresses = CassandraUtils.getAddresses();
                 int cassandraPort = CassandraUtils.getCassandraPort();
                 Long reconnectTimeout = CassandraUtils.getReconnectTimeout();
        -
                 Cluster.Builder builder = Cluster.builder();
        -
        -        if(null != reconnectTimeout) {
        -            builder.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout))
        -                    .withRetryPolicy(DefaultRetryPolicy.INSTANCE);
        +        if (null != reconnectTimeout) {
        +            builder.withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectTimeout)).withRetryPolicy(DefaultRetryPolicy.INSTANCE);
                 }
        -
                 builder.withPort(cassandraPort);
        -
                 for (String address : addresses) {
                     builder.addContactPoint(address);
                 }
        -
                 //Check if ssl
                 Boolean isSsl = CassandraUtils.isSsl();
                 if (isSsl) {
                     builder.withSSL(getSslOptions());
                 }
        -
                 //Check if user/pass
                 Boolean isAuthenticate = CassandraUtils.isAuthenticate();
                 if (isAuthenticate) {
                     builder.withCredentials(CassandraUtils.getUser(), CassandraUtils.getPassword());
                 }
        -
                 setConsistencyLevel(builder, addresses);
        -
                 setLocalDataCenter(builder);
        -
                 Cluster cluster = builder.build();
        -        String keyStore = SessionContextProviderFactory.getInstance().createInterface().get()
        -            .getTenant();
        -        LOGGER.info("Cassandra client created hosts: {} port: {} SSL enabled: {} reconnectTimeout",
        -                addresses, cassandraPort, isSsl, reconnectTimeout);
        +        String keyStore = SessionContextProviderFactory.getInstance().createInterface().get().getTenant();
        +        LOGGER
        +            .info("Cassandra client created hosts: {} port: {} SSL enabled: {} reconnectTimeout", addresses, cassandraPort, isSsl, reconnectTimeout);
                 return cluster.connect(keyStore);
             }
         
             private static void setLocalDataCenter(Cluster.Builder builder) {
                 String localDataCenter = CassandraUtils.getLocalDataCenter();
                 if (Objects.nonNull(localDataCenter)) {
        -            LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as local.",
        -                    localDataCenter);
        -
        -            LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(
        -                    DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
        +            LOGGER.info("localDatacenter was provided, setting Cassndra client to use datacenter: {} as local.", localDataCenter);
        +            LoadBalancingPolicy tokenAwarePolicy = new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc(localDataCenter).build());
                     builder.withLoadBalancingPolicy(tokenAwarePolicy);
                 } else {
        -            LOGGER.info(
        -                    "localDatacenter was provided,  the driver will use the datacenter of the first contact " +
        -                            "point that was reached at initialization");
        +            LOGGER.info("localDatacenter was provided,  the driver will use the datacenter of the first contact "
        +                + "point that was reached at initialization");
                 }
             }
         
        @@ -118,54 +103,42 @@ public class CassandraSessionFactory {
                 if (addresses != null && addresses.length > 1) {
                     String consistencyLevel = CassandraUtils.getConsistencyLevel();
                     if (Objects.nonNull(consistencyLevel)) {
        -                LOGGER.info(
        -                        "consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" +
        -                                " as "
        -                        , consistencyLevel);
        -                builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf
        -                        (consistencyLevel)));
        +                LOGGER.info("consistencyLevel was provided, setting Cassandra client to use consistencyLevel: {}" + " as ", consistencyLevel);
        +                builder.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.valueOf(consistencyLevel)));
                     }
                 }
             }
         
             private static SSLOptions getSslOptions() {
        -
                 Optional trustStorePath = Optional.ofNullable(CassandraUtils.getTruststore());
                 if (!trustStorePath.isPresent()) {
                     throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePath");
                 }
        -
                 Optional trustStorePassword = Optional.ofNullable(CassandraUtils.getTruststorePassword());
                 if (!trustStorePassword.isPresent()) {
                     throw new SdcConfigurationException("Missing configuration for Cassandra trustStorePassword");
                 }
        -
                 SSLContext context = getSslContext(trustStorePath.get(), trustStorePassword.get());
                 String[] css = new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"};
                 return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(context).withCipherSuites(css).build();
             }
         
             private static SSLContext getSslContext(String truststorePath, String trustStorePassword) {
        -
                 try (FileInputStream tsf = new FileInputStream(truststorePath)) {
        -
                     SSLContext ctx = SSLContext.getInstance("TLS");
        -
                     KeyStore ts = KeyStore.getInstance("JKS");
                     ts.load(tsf, trustStorePassword.toCharArray());
        -            TrustManagerFactory tmf =
        -                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        +            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                     tmf.init(ts);
        -
                     ctx.init(null, tmf.getTrustManagers(), new SecureRandom());
                     return ctx;
        -
                 } catch (Exception exception) {
                     throw new SdcConfigurationException("Failed to get SSL Contexts for Cassandra connection", exception);
                 }
             }
         
             private static class ReferenceHolder {
        +
                 private static final Session CASSANDRA = newCassandraSession();
         
                 private ReferenceHolder() {
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java
        index 30bc0a72a3..d6840fedd1 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/CassandraUtils.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,90 +17,76 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.nosqldb.util;
         
        -import org.openecomp.core.utilities.file.FileUtils;
        -import org.openecomp.core.utilities.json.JsonUtil;
        -
         import java.util.HashMap;
         import java.util.Map;
        +import org.openecomp.core.utilities.file.FileUtils;
        +import org.openecomp.core.utilities.json.JsonUtil;
         
         public class CassandraUtils {
         
        +    private static final String CASSANDRA_STATEMENT_DEFINITION_FILE = "cassandraStatements.json";
        +    private static Map statementMap = new HashMap<>();
         
        -  private static final String CASSANDRA_STATEMENT_DEFINITION_FILE = "cassandraStatements.json";
        -  private static Map statementMap = new HashMap<>();
        -
        -  public static String[] getAddresses() {
        -    return ConfigurationManager.getInstance().getAddresses();
        -  }
        -
        -  public static Long getReconnectTimeout() {
        -    return ConfigurationManager.getInstance().getReconnectTimeout();
        -  }
        -
        -  public static String getKeySpace() {
        -    return ConfigurationManager.getInstance().getKeySpace();
        -  }
        -
        -  /**
        -   * Gets statement.
        -   *
        -   * @param statementName the statement name
        -   * @return the statement
        -   */
        -  public static String getStatement(String statementName) {
        -
        -    if (statementMap.size() == 0) {
        -      statementMap = FileUtils.readViaInputStream(CASSANDRA_STATEMENT_DEFINITION_FILE,
        -          stream -> JsonUtil.json2Object(stream, Map.class));
        +    public static String[] getAddresses() {
        +        return ConfigurationManager.getInstance().getAddresses();
             }
         
        -    return statementMap.get(statementName);
        -  }
        -
        -  public static String getUser() {
        -
        -    return ConfigurationManager.getInstance().getUsername();
        -  }
        -
        -  public static String getPassword() {
        -    return ConfigurationManager.getInstance().getPassword();
        -
        -  }
        -
        -  public static String getTruststore() {
        -    return ConfigurationManager.getInstance().getTruststorePath();
        -
        -  }
        +    public static Long getReconnectTimeout() {
        +        return ConfigurationManager.getInstance().getReconnectTimeout();
        +    }
         
        -  public static String getTruststorePassword() {
        -    return ConfigurationManager.getInstance().getTruststorePassword();
        +    public static String getKeySpace() {
        +        return ConfigurationManager.getInstance().getKeySpace();
        +    }
         
        -  }
        +    /**
        +     * Gets statement.
        +     *
        +     * @param statementName the statement name
        +     * @return the statement
        +     */
        +    public static String getStatement(String statementName) {
        +        if (statementMap.size() == 0) {
        +            statementMap = FileUtils.readViaInputStream(CASSANDRA_STATEMENT_DEFINITION_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
        +        }
        +        return statementMap.get(statementName);
        +    }
         
        -  public static int getCassandraPort() {
        -    return ConfigurationManager.getInstance().getCassandraPort();
        +    public static String getUser() {
        +        return ConfigurationManager.getInstance().getUsername();
        +    }
         
        -  }
        +    public static String getPassword() {
        +        return ConfigurationManager.getInstance().getPassword();
        +    }
         
        -  public static boolean isSsl() {
        -    return ConfigurationManager.getInstance().isSsl();
        +    public static String getTruststore() {
        +        return ConfigurationManager.getInstance().getTruststorePath();
        +    }
         
        -  }
        +    public static String getTruststorePassword() {
        +        return ConfigurationManager.getInstance().getTruststorePassword();
        +    }
         
        -  public static boolean isAuthenticate() {
        -    return ConfigurationManager.getInstance().isAuthenticate();
        -  }
        +    public static int getCassandraPort() {
        +        return ConfigurationManager.getInstance().getCassandraPort();
        +    }
         
        -  public static String getConsistencyLevel() {
        +    public static boolean isSsl() {
        +        return ConfigurationManager.getInstance().isSsl();
        +    }
         
        -    return ConfigurationManager.getInstance().getConsistencyLevel();
        +    public static boolean isAuthenticate() {
        +        return ConfigurationManager.getInstance().isAuthenticate();
        +    }
         
        -  }
        +    public static String getConsistencyLevel() {
        +        return ConfigurationManager.getInstance().getConsistencyLevel();
        +    }
         
        -  public static String getLocalDataCenter() {
        -    return ConfigurationManager.getInstance().getLocalDataCenter();
        -  }
        +    public static String getLocalDataCenter() {
        +        return ConfigurationManager.getInstance().getLocalDataCenter();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java
        index a1d5246eee..666901edfe 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/util/ConfigurationManager.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,15 +17,8 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.nosqldb.util;
         
        -import org.apache.commons.collections4.CollectionUtils;
        -import org.onap.sdc.tosca.services.YamlUtil;
        -import org.openecomp.core.utilities.file.FileUtils;
        -import org.openecomp.sdc.logging.api.Logger;
        -import org.openecomp.sdc.logging.api.LoggerFactory;
        -
         import java.io.FileInputStream;
         import java.io.IOException;
         import java.io.InputStream;
        @@ -35,248 +28,241 @@ import java.util.List;
         import java.util.Map;
         import java.util.Objects;
         import java.util.function.Function;
        +import org.apache.commons.collections4.CollectionUtils;
        +import org.onap.sdc.tosca.services.YamlUtil;
        +import org.openecomp.core.utilities.file.FileUtils;
        +import org.openecomp.sdc.logging.api.Logger;
        +import org.openecomp.sdc.logging.api.LoggerFactory;
         
         /**
          * The type Configuration manager.
          */
         public class ConfigurationManager {
         
        -  static final String CONFIGURATION_YAML_FILE = "configuration.yaml";
        -  static private final Integer DEFAULT_CASSANDRA_PORT = 9042;
        -  private static final String CASSANDRA = "cassandra";
        -  private static final String CASSANDRA_KEY = CASSANDRA + "Config";
        -  private static final String DEFAULT_KEYSPACE_NAME = "dox";
        -  private static final String CASSANDRA_ADDRESSES = CASSANDRA + ".addresses";
        -  private static final String CASSANDRA_DOX_KEY_STORE = CASSANDRA + ".dox.keystore";
        -  private static final String CASSANDRA_AUTHENTICATE = CASSANDRA + ".authenticate";
        -  private static final String CASSANDRA_USER = CASSANDRA + ".user";
        -  private static final String CASSANDRA_PASSWORD = CASSANDRA + ".password";
        -  private static final String CASSANDRA_SSL = CASSANDRA + ".ssl";
        -  private static final String CASSANDRA_TRUSTSTORE = CASSANDRA + ".Truststore";
        -  private static final String CASSANDRA_TRUSTSTORE_PASSWORD = CASSANDRA + ".TruststorePassword";
        -  private static final String CASSANDRA_HOSTS_KEY = CASSANDRA + "Hosts";
        -  private static final String CASSANDRA_PORT_KEY = "cassandraPort";
        -  private static final String CASSANDRA_USERNAME_KEY = "username";
        -  private static final String CASSANDRA_RECONNECT_TIMEOUT = "reconnectTimeout";
        -  @SuppressWarnings("squid:S2068")
        -  private static final String CASSANDRA_PASSWORD_KEY = "password";          
        -  private static final String CASSANDRA_AUTHENTICATE_KEY = "authenticate";
        -  private static final String CASSANDRA_SSL_KEY = "ssl";
        -  private static final String CASSANDRA_TRUSTSTORE_PATH_KEY = "truststorePath";
        -  @SuppressWarnings("squid:S2068")
        -  private static final String CASSANDRA_TRUSTSTORE_PASSWORD_KEY = "truststorePassword";   
        -  private static final String CONSISTENCY_LEVEL = CASSANDRA + ".consistencyLevel";
        -  private static final String CONSISTENCY_LEVEL_KEY = "consistencyLevel";
        -  private static final String LOCAL_DATA_CENTER_KEY = "localDataCenter";
        -  private static final String LOCAL_DATA_CENTER = CASSANDRA + ".localDataCenter";
        -  private static ConfigurationManager instance = null;
        -  private final LinkedHashMap cassandraConfiguration;
        -
        -  private static final Logger LOG = LoggerFactory.getLogger(ConfigurationManager.class);
        -
        -
        -  private ConfigurationManager() {
        -
        -    String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE);
        -
        -    Function>> reader = is -> {
        -      YamlUtil yamlUtil = new YamlUtil();
        -      return yamlUtil.yamlToMap(is);
        -    };
        -
        -    try {
        -
        -      Map> configurationMap = configurationYamlFile != null
        -          ? readFromFile(configurationYamlFile, reader) // load from file
        -          : FileUtils.readViaInputStream(CONFIGURATION_YAML_FILE, reader); // or from resource
        -      cassandraConfiguration = configurationMap.get(CASSANDRA_KEY);
        -
        -    } catch (IOException e) {
        -      throw new RuntimeException("Failed to read configuration", e);
        +    static final String CONFIGURATION_YAML_FILE = "configuration.yaml";
        +    static private final Integer DEFAULT_CASSANDRA_PORT = 9042;
        +    private static final String CASSANDRA = "cassandra";
        +    private static final String CASSANDRA_KEY = CASSANDRA + "Config";
        +    private static final String DEFAULT_KEYSPACE_NAME = "dox";
        +    private static final String CASSANDRA_ADDRESSES = CASSANDRA + ".addresses";
        +    private static final String CASSANDRA_DOX_KEY_STORE = CASSANDRA + ".dox.keystore";
        +    private static final String CASSANDRA_AUTHENTICATE = CASSANDRA + ".authenticate";
        +    private static final String CASSANDRA_USER = CASSANDRA + ".user";
        +    private static final String CASSANDRA_PASSWORD = CASSANDRA + ".password";
        +    private static final String CASSANDRA_SSL = CASSANDRA + ".ssl";
        +    private static final String CASSANDRA_TRUSTSTORE = CASSANDRA + ".Truststore";
        +    private static final String CASSANDRA_TRUSTSTORE_PASSWORD = CASSANDRA + ".TruststorePassword";
        +    private static final String CASSANDRA_HOSTS_KEY = CASSANDRA + "Hosts";
        +    private static final String CASSANDRA_PORT_KEY = "cassandraPort";
        +    private static final String CASSANDRA_USERNAME_KEY = "username";
        +    private static final String CASSANDRA_RECONNECT_TIMEOUT = "reconnectTimeout";
        +    @SuppressWarnings("squid:S2068")
        +    private static final String CASSANDRA_PASSWORD_KEY = "password";
        +    private static final String CASSANDRA_AUTHENTICATE_KEY = "authenticate";
        +    private static final String CASSANDRA_SSL_KEY = "ssl";
        +    private static final String CASSANDRA_TRUSTSTORE_PATH_KEY = "truststorePath";
        +    @SuppressWarnings("squid:S2068")
        +    private static final String CASSANDRA_TRUSTSTORE_PASSWORD_KEY = "truststorePassword";
        +    private static final String CONSISTENCY_LEVEL = CASSANDRA + ".consistencyLevel";
        +    private static final String CONSISTENCY_LEVEL_KEY = "consistencyLevel";
        +    private static final String LOCAL_DATA_CENTER_KEY = "localDataCenter";
        +    private static final String LOCAL_DATA_CENTER = CASSANDRA + ".localDataCenter";
        +    private static final Logger LOG = LoggerFactory.getLogger(ConfigurationManager.class);
        +    private static ConfigurationManager instance = null;
        +    private final LinkedHashMap cassandraConfiguration;
        +
        +    private ConfigurationManager() {
        +        String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE);
        +        Function>> reader = is -> {
        +            YamlUtil yamlUtil = new YamlUtil();
        +            return yamlUtil.yamlToMap(is);
        +        };
        +        try {
        +            Map> configurationMap = configurationYamlFile != null
        +                ? readFromFile(configurationYamlFile, reader) // load from file
        +
        +                : FileUtils.readViaInputStream(CONFIGURATION_YAML_FILE, reader); // or from resource
        +            cassandraConfiguration = configurationMap.get(CASSANDRA_KEY);
        +        } catch (IOException e) {
        +            throw new RuntimeException("Failed to read configuration", e);
        +        }
             }
        -  }
         
        -  /**
        -   * Gets instance.
        -   *
        -   * @return the instance
        -   */
        -  public static ConfigurationManager getInstance() {
        -    if (Objects.isNull(instance)) {
        -      instance = new ConfigurationManager();
        +    /**
        +     * Gets instance.
        +     *
        +     * @return the instance
        +     */
        +    public static ConfigurationManager getInstance() {
        +        if (Objects.isNull(instance)) {
        +            instance = new ConfigurationManager();
        +        }
        +        return instance;
             }
        -    return instance;
        -  }
        -
        -  /**
        -   * Get addresses string [ ].
        -   *
        -   * @return the string [ ]
        -   */
        -  public String[] getAddresses() {
         
        -    String addresses = System.getProperty(CASSANDRA_ADDRESSES);
        -    if (Objects.nonNull(addresses)) {
        -      return addresses.split(",");
        +    /**
        +     * Get addresses string [ ].
        +     *
        +     * @return the string [ ]
        +     */
        +    public String[] getAddresses() {
        +        String addresses = System.getProperty(CASSANDRA_ADDRESSES);
        +        if (Objects.nonNull(addresses)) {
        +            return addresses.split(",");
        +        }
        +        List lsAddresses = (ArrayList) cassandraConfiguration.get(CASSANDRA_HOSTS_KEY);
        +        if (CollectionUtils.isEmpty(lsAddresses)) {
        +            LOG.info("No Cassandra hosts are defined.");
        +        }
        +        String[] addressesArray;
        +        addressesArray = (String[]) lsAddresses.toArray(new String[lsAddresses.size()]);
        +        return addressesArray;
             }
        -    List lsAddresses = (ArrayList) cassandraConfiguration.get(CASSANDRA_HOSTS_KEY);
        -    if (CollectionUtils.isEmpty(lsAddresses)) {
        -      LOG.info("No Cassandra hosts are defined.");
        -    }
        -
        -    String[] addressesArray;
        -    addressesArray = (String[]) lsAddresses.toArray(new String[lsAddresses.size()]);
        -    return addressesArray;
         
        -  }
        -
        -  /**
        -   * Gets Cassandra port.
        -   *
        -   * @return the port
        -   */
        -  public int getCassandraPort() {
        -    Integer cassandraPort = (Integer) cassandraConfiguration.get(CASSANDRA_PORT_KEY);
        -    if (Objects.isNull(cassandraPort)) {
        -        cassandraPort = DEFAULT_CASSANDRA_PORT;
        +    /**
        +     * Gets Cassandra port.
        +     *
        +     * @return the port
        +     */
        +    public int getCassandraPort() {
        +        Integer cassandraPort = (Integer) cassandraConfiguration.get(CASSANDRA_PORT_KEY);
        +        if (Objects.isNull(cassandraPort)) {
        +            cassandraPort = DEFAULT_CASSANDRA_PORT;
        +        }
        +        return cassandraPort;
             }
        -    return cassandraPort;
        -  }
         
        -  /**
        -   * Gets Cassandra reconnection timeout
        -   *
        -   * @return
        -   */
        -  public Long getReconnectTimeout() {
        -    Integer cassandraReconnectTimeout = (Integer) cassandraConfiguration.get(CASSANDRA_RECONNECT_TIMEOUT);
        -    if (Objects.isNull(cassandraReconnectTimeout)) {
        -      LOG.info("No Cassandra reconnect timeout are defined.");
        -      return null;
        +    /**
        +     * Gets Cassandra reconnection timeout
        +     *
        +     * @return
        +     */
        +    public Long getReconnectTimeout() {
        +        Integer cassandraReconnectTimeout = (Integer) cassandraConfiguration.get(CASSANDRA_RECONNECT_TIMEOUT);
        +        if (Objects.isNull(cassandraReconnectTimeout)) {
        +            LOG.info("No Cassandra reconnect timeout are defined.");
        +            return null;
        +        }
        +        return cassandraReconnectTimeout.longValue();
             }
        -    return cassandraReconnectTimeout.longValue();
        -  }
         
        -  /**
        -   * Gets key space.
        -   *
        -   * @return the key space
        -   */
        -  public String getKeySpace() {
        -    String keySpace = System.getProperty(CASSANDRA_DOX_KEY_STORE);
        -    if (Objects.isNull(keySpace)) {
        -      keySpace = DEFAULT_KEYSPACE_NAME;
        +    /**
        +     * Gets key space.
        +     *
        +     * @return the key space
        +     */
        +    public String getKeySpace() {
        +        String keySpace = System.getProperty(CASSANDRA_DOX_KEY_STORE);
        +        if (Objects.isNull(keySpace)) {
        +            keySpace = DEFAULT_KEYSPACE_NAME;
        +        }
        +        return keySpace;
             }
        -    return keySpace;
        -  }
         
        -  /**
        -   * Gets username.
        -   *
        -   * @return the username
        -   */
        -  public String getUsername() {
        -    String username = System.getProperty(CASSANDRA_USER);
        -    if (Objects.isNull(username)) {
        -      username = (String) cassandraConfiguration.get(CASSANDRA_USERNAME_KEY);
        +    /**
        +     * Gets username.
        +     *
        +     * @return the username
        +     */
        +    public String getUsername() {
        +        String username = System.getProperty(CASSANDRA_USER);
        +        if (Objects.isNull(username)) {
        +            username = (String) cassandraConfiguration.get(CASSANDRA_USERNAME_KEY);
        +        }
        +        return username;
             }
        -    return username;
        -  }
         
        -  /**
        -   * Gets password.
        -   *
        -   * @return the password
        -   */
        -  public String getPassword() {
        -    String password = System.getProperty(CASSANDRA_PASSWORD);
        -    if (Objects.isNull(password)) {
        -      password = (String) cassandraConfiguration.get(CASSANDRA_PASSWORD_KEY);
        +    /**
        +     * Gets password.
        +     *
        +     * @return the password
        +     */
        +    public String getPassword() {
        +        String password = System.getProperty(CASSANDRA_PASSWORD);
        +        if (Objects.isNull(password)) {
        +            password = (String) cassandraConfiguration.get(CASSANDRA_PASSWORD_KEY);
        +        }
        +        return password;
             }
        -    return password;
        -  }
         
        -  /**
        -   * Gets truststore path.
        -   *
        -   * @return the truststore path
        -   */
        -  public String getTruststorePath() {
        -    String truststorePath = System.getProperty(CASSANDRA_TRUSTSTORE);
        -    if (Objects.isNull(truststorePath)) {
        -      truststorePath = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PATH_KEY);
        +    /**
        +     * Gets truststore path.
        +     *
        +     * @return the truststore path
        +     */
        +    public String getTruststorePath() {
        +        String truststorePath = System.getProperty(CASSANDRA_TRUSTSTORE);
        +        if (Objects.isNull(truststorePath)) {
        +            truststorePath = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PATH_KEY);
        +        }
        +        return truststorePath;
             }
        -    return truststorePath;
        -  }
         
        -  /**
        -   * Gets truststore password.
        -   *
        -   * @return the truststore password
        -   */
        -  public String getTruststorePassword() {
        -    String truststorePassword = System.getProperty(CASSANDRA_TRUSTSTORE_PASSWORD);
        -    if (Objects.isNull(truststorePassword)) {
        -      truststorePassword = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PASSWORD_KEY);
        +    /**
        +     * Gets truststore password.
        +     *
        +     * @return the truststore password
        +     */
        +    public String getTruststorePassword() {
        +        String truststorePassword = System.getProperty(CASSANDRA_TRUSTSTORE_PASSWORD);
        +        if (Objects.isNull(truststorePassword)) {
        +            truststorePassword = (String) cassandraConfiguration.get(CASSANDRA_TRUSTSTORE_PASSWORD_KEY);
        +        }
        +        return truststorePassword;
             }
        -    return truststorePassword;
        -  }
        -
        -  /**
        -   * Is ssl boolean.
        -   *
        -   * @return the boolean
        -   */
        -  public boolean isSsl() {
        -    return getBooleanResult(CASSANDRA_SSL, CASSANDRA_SSL_KEY);
        -  }
         
        -  /**
        -   * Is authenticate boolean.
        -   *
        -   * @return the boolean
        -   */
        -  public boolean isAuthenticate() {
        -    return getBooleanResult(CASSANDRA_AUTHENTICATE, CASSANDRA_AUTHENTICATE_KEY);
        -  }
        -
        -  private Boolean getBooleanResult(String property, String key) {
        -    Boolean res;
        -    String value;
        -    if (System.getProperty(property) == null) {
        -      value = String.valueOf(cassandraConfiguration.get(key));
        -    } else {
        -      value = System.getProperty(property);
        +    /**
        +     * Is ssl boolean.
        +     *
        +     * @return the boolean
        +     */
        +    public boolean isSsl() {
        +        return getBooleanResult(CASSANDRA_SSL, CASSANDRA_SSL_KEY);
             }
         
        -    res = Boolean.valueOf(value);
        -
        -    return res;
        -  }
        +    /**
        +     * Is authenticate boolean.
        +     *
        +     * @return the boolean
        +     */
        +    public boolean isAuthenticate() {
        +        return getBooleanResult(CASSANDRA_AUTHENTICATE, CASSANDRA_AUTHENTICATE_KEY);
        +    }
         
        -  private  T readFromFile(String file, Function reader) throws IOException {
        -    try (InputStream is = new FileInputStream(file)) {
        -      return reader.apply(is);
        +    private Boolean getBooleanResult(String property, String key) {
        +        Boolean res;
        +        String value;
        +        if (System.getProperty(property) == null) {
        +            value = String.valueOf(cassandraConfiguration.get(key));
        +        } else {
        +            value = System.getProperty(property);
        +        }
        +        res = Boolean.valueOf(value);
        +        return res;
             }
        -  }
         
        -  public String getConsistencyLevel() {
        -    String consistencyLevel = System.getProperty(CONSISTENCY_LEVEL);
        -    if (Objects.isNull(consistencyLevel)) {
        -      consistencyLevel = (String) cassandraConfiguration.get(CONSISTENCY_LEVEL_KEY);
        +    private  T readFromFile(String file, Function reader) throws IOException {
        +        try (InputStream is = new FileInputStream(file)) {
        +            return reader.apply(is);
        +        }
             }
         
        -    if (Objects.isNull(consistencyLevel)) {
        -      consistencyLevel = "LOCAL_QUORUM";
        +    public String getConsistencyLevel() {
        +        String consistencyLevel = System.getProperty(CONSISTENCY_LEVEL);
        +        if (Objects.isNull(consistencyLevel)) {
        +            consistencyLevel = (String) cassandraConfiguration.get(CONSISTENCY_LEVEL_KEY);
        +        }
        +        if (Objects.isNull(consistencyLevel)) {
        +            consistencyLevel = "LOCAL_QUORUM";
        +        }
        +        return consistencyLevel;
             }
        -    return consistencyLevel;
        -  }
         
        -  public String getLocalDataCenter() {
        -    String localDataCenter = System.getProperty(LOCAL_DATA_CENTER);
        -    if (Objects.isNull(localDataCenter)) {
        -      localDataCenter = (String) cassandraConfiguration.get(LOCAL_DATA_CENTER_KEY);
        +    public String getLocalDataCenter() {
        +        String localDataCenter = System.getProperty(LOCAL_DATA_CENTER);
        +        if (Objects.isNull(localDataCenter)) {
        +            localDataCenter = (String) cassandraConfiguration.get(LOCAL_DATA_CENTER_KEY);
        +        }
        +        return localDataCenter;
             }
        -    return localDataCenter;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java
        index c9e6379793..8670d58a22 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java
        @@ -13,7 +13,6 @@
          *  See the License for the specific language governing permissions and
          *  limitations under the License.
          */
        -
         package org.openecomp.sdc.common.session;
         
         public interface SessionContext {
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java
        index 9b74cb0060..bfe94e4263 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java
        @@ -13,7 +13,6 @@
          *  See the License for the specific language governing permissions and
          *  limitations under the License.
          */
        -
         package org.openecomp.sdc.common.session;
         
         public interface SessionContextProvider {
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java
        index d08c6dd94a..d82ff40ab7 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java
        @@ -17,14 +17,12 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.common.session;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         
        -public abstract class SessionContextProviderFactory
        -        extends AbstractComponentFactory {
        +public abstract class SessionContextProviderFactory extends AbstractComponentFactory {
         
             public static SessionContextProviderFactory getInstance() {
                 return AbstractFactory.getInstance(SessionContextProviderFactory.class);
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java
        index bbda545f80..89a7557958 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java
        @@ -13,7 +13,6 @@
          *  See the License for the specific language governing permissions and
          *  limitations under the License.
          */
        -
         package org.openecomp.sdc.common.session;
         
         import lombok.AllArgsConstructor;
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java
        index 1d23410b89..179c9c0e3a 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java
        @@ -13,8 +13,6 @@
          *  See the License for the specific language governing permissions and
          *  limitations under the License.
          */
        -
        -
         package org.openecomp.sdc.common.session.impl;
         
         import lombok.AllArgsConstructor;
        @@ -39,15 +37,11 @@ public class AsdcSessionContextProvider implements SessionContextProvider {
             @Override
             public SessionContext get() {
                 if (threadUserId.get() == null) {
        -            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage("UserId was not set "
        -                    + "for this thread").build());
        +            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage("UserId was not set " + "for this thread").build());
                 }
        -
                 if (threadTenant.get() == null) {
        -            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage("Tenant was not set "
        -                    + "for this thread").build());
        +            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage("Tenant was not set " + "for this thread").build());
                 }
        -
                 return new AsdcSessionContext(new User(threadUserId.get()), threadTenant.get());
             }
         
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java
        index 9367530bf3..02b6be4490 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.common.session.impl;
         
         import org.openecomp.sdc.common.session.SessionContextProvider;
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
        index 0bcdf8ebbf..6065426e9a 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.utilities;
         
         import java.lang.reflect.Array;
        @@ -27,7 +26,6 @@ import java.util.Map;
         import java.util.Objects;
         import java.util.Set;
         import java.util.UUID;
        -
         import org.apache.commons.collections4.MapUtils;
         import org.apache.commons.lang3.ArrayUtils;
         import org.apache.commons.lang3.StringUtils;
        @@ -38,10 +36,7 @@ import org.openecomp.core.utilities.exception.NewInstanceRuntimeException;
          */
         public class CommonMethods {
         
        -    private static final char[] CHARS = new char[] {
        -            '0', '1', '2', '3', '4', '5', '6', '7',
        -            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        -    };
        +    private static final char[] CHARS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
         
             /**
              * Private default constructor to prevent instantiation of the class objects.
        @@ -56,11 +51,9 @@ public class CommonMethods {
              */
             public static String nextUuId() {
                 UUID uuid = UUID.randomUUID();
        -
                 StringBuilder buff = new StringBuilder(32);
                 long2string(uuid.getMostSignificantBits(), buff);
                 long2string(uuid.getLeastSignificantBits(), buff);
        -
                 return buff.toString();
             }
         
        @@ -71,32 +64,27 @@ public class CommonMethods {
                     value <<= 4;
                     boolean isNegative = nextByte < 0;
                     nextByte = nextByte >>> 60;
        -
                     if (isNegative) {
                         nextByte |= 0x08;
                     }
        -
                     buff.append(CHARS[(int) nextByte]);
                 }
             }
         
             /**
        -     * Concatenates two Java arrays. The method allocates a new array and copies
        -     * all elements to it or returns one of input arrays if another one is
        +     * Concatenates two Java arrays. The method allocates a new array and copies all elements to it or returns one of input arrays if another one is
              * empty.
              *
              * @param    the type parameter
        -     * @param left  Elements of this array will be copied to positions from 0 to left.length -
        -     *              1 in the target array.
        +     * @param left  Elements of this array will be copied to positions from 0 to left.length - 1 in the target array.
              * @param right Elements of this array will be copied to positions from left.length to
              *              left.length + right.length
        -     * @return A newly allocate Java array that accommodates elements of source (left/right) arrays
        -     * or one of source arrays if another is empty, null - otherwise.
        +     * @return A newly allocate Java array that accommodates elements of source (left/right) arrays or one of source arrays if another is empty,
        +     * null - otherwise.
              */
             @SuppressWarnings("unchecked")
             public static  T[] concat(T[] left, T[] right) {
                 T[] res;
        -
                 if (ArrayUtils.isEmpty(left)) {
                     res = right;
                 } else if (ArrayUtils.isEmpty(right)) {
        @@ -106,7 +94,6 @@ public class CommonMethods {
                     System.arraycopy(left, 0, res, 0, left.length);
                     System.arraycopy(right, 0, res, left.length, right.length);
                 }
        -
                 return res;
             } // concat
         
        @@ -130,25 +117,18 @@ public class CommonMethods {
              */
             @SuppressWarnings("unchecked")
             public static  T newInstance(String classname, Class cls) {
        -
                 if (StringUtils.isEmpty(classname)) {
                     throw new IllegalArgumentException();
                 }
        -
                 if (cls == null) {
                     throw new IllegalArgumentException();
                 }
        -
                 try {
                     Class temp = Class.forName(classname);
        -
                     if (!cls.isAssignableFrom(temp)) {
        -                throw new ClassCastException(
        -                        String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
        +                throw new ClassCastException(String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
                     }
        -
                     Class impl = (Class) temp;
        -
                     return newInstance(impl);
                 } catch (ClassNotFoundException exception) {
                     throw new IllegalArgumentException(exception);
        @@ -166,8 +146,7 @@ public class CommonMethods {
                 try {
                     return cls.getDeclaredConstructor().newInstance();
                 } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
        -            throw new NewInstanceRuntimeException(String.format("Could not create instance for '%s'", cls.getName())
        -                , ex);
        +            throw new NewInstanceRuntimeException(String.format("Could not create instance for '%s'", cls.getName()), ex);
                 }
             }
         
        @@ -236,10 +215,8 @@ public class CommonMethods {
              * @param numberOfDuplications the number of duplications
              * @return the string
              */
        -    public static String duplicateStringWithDelimiter(String arg, char separator,
        -                                                      int numberOfDuplications) {
        +    public static String duplicateStringWithDelimiter(String arg, char separator, int numberOfDuplications) {
                 StringBuilder sb = new StringBuilder();
        -
                 for (int i = 0; i < numberOfDuplications; i++) {
                     if (i > 0) {
                         sb.append(separator);
        @@ -254,12 +231,10 @@ public class CommonMethods {
              *
              * @param      the class of the objects in the set
              * @param element the single element to be contained in the returned Set
        -     * @return an immutable set containing only the specified object. The returned set is
        -     * serializable.
        +     * @return an immutable set containing only the specified object. The returned set is serializable.
              */
             public static  Set toSingleElementSet(T element) {
                 return Collections.singleton(element);
        -
             }
         
             /**
        @@ -271,13 +246,11 @@ public class CommonMethods {
              * @param source the source
              * @return the list
              */
        -    public static  List> mergeListsOfMap(List> target,
        -                                                         List> source) {
        +    public static  List> mergeListsOfMap(List> target, List> source) {
                 List> retList = new ArrayList<>();
                 if (Objects.nonNull(target)) {
                     retList.addAll(target);
                 }
        -
                 if (Objects.nonNull(source)) {
                     for (Map sourceMap : source) {
                         for (Map.Entry entry : sourceMap.entrySet()) {
        @@ -298,14 +271,12 @@ public class CommonMethods {
              */
             public static  List mergeLists(List target, List source) {
                 List retList = new ArrayList<>();
        -
                 if (Objects.nonNull(source)) {
                     retList.addAll(source);
                 }
                 if (Objects.nonNull(target)) {
                     retList.addAll(target);
                 }
        -
                 return retList;
             }
         
        @@ -326,7 +297,6 @@ public class CommonMethods {
                         found = true;
                     }
                 }
        -
                 if (!found) {
                     Map newMap = new HashMap<>();
                     newMap.put(key, value);
        @@ -334,7 +304,6 @@ public class CommonMethods {
                 }
             }
         
        -
             /**
              * Merge maps map.
              *
        @@ -342,8 +311,7 @@ public class CommonMethods {
              * @param        the type parameter
              * @param firstMap  the firstMap
              * @param secondMap the secondMap
        -     * @return the map
        -     * Second Map is overridden data from the first map
        +     * @return the map Second Map is overridden data from the first map
              */
             public static  Map mergeMaps(Map firstMap, Map secondMap) {
                 Map retMap = new HashMap<>();
        @@ -355,6 +323,4 @@ public class CommonMethods {
                 }
                 return retMap;
             }
        -
         }
        -
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java
        index 1176a6ba8b..93bc29c958 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java
        @@ -19,85 +19,68 @@
          */
         package org.openecomp.core.utilities.deserializers;
         
        -import java.lang.reflect.Type;
        -import java.util.Objects;
        -import java.util.Optional;
        -import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
         import com.google.gson.JsonArray;
         import com.google.gson.JsonDeserializationContext;
         import com.google.gson.JsonDeserializer;
         import com.google.gson.JsonElement;
         import com.google.gson.JsonObject;
         import com.google.gson.JsonPrimitive;
        +import java.lang.reflect.Type;
        +import java.util.Objects;
        +import java.util.Optional;
        +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
         
         public class RequirementDefinitionDeserializer implements JsonDeserializer {
         
        -  static final String CAPABILITY = "capability";
        -  static final String NODE = "node";
        -  static final String RELATIONSHIP = "relationship";
        -  private static final String OCCURRENCES = "occurrences";
        -
        -  @Override
        -  public RequirementDefinition deserialize(JsonElement jsonElement, Type type,
        -                                           JsonDeserializationContext jsonDeserializationContext) {
        -
        -    JsonObject jsonObject = jsonElement.getAsJsonObject();
        -
        -    RequirementDefinition requirementDefinition = new RequirementDefinition();
        -    setRequirementValues(jsonObject, requirementDefinition);
        -
        -    Optional occurrences = handleOccurrences(jsonObject);
        -    occurrences.ifPresent(requirementDefinition::setOccurrences);
        -
        -    return requirementDefinition;
        -  }
        -
        -
        -  private void setRequirementValues(JsonObject jsonObject,
        -                                    RequirementDefinition requirementDefinition) {
        -
        -    JsonElement capabilityElement = jsonObject.get(CAPABILITY);
        -    if (!Objects.isNull(capabilityElement)) {
        -      requirementDefinition.setCapability(capabilityElement.getAsString());
        -    }
        -
        -    JsonElement nodeElement = jsonObject.get(NODE);
        -    if (!Objects.isNull(nodeElement)) {
        -      requirementDefinition.setNode(nodeElement.getAsString());
        -    }
        -
        -    JsonElement relationshipElement = jsonObject.get(RELATIONSHIP);
        -    if (!Objects.isNull(relationshipElement)) {
        -      requirementDefinition.setRelationship(relationshipElement.getAsString());
        +    static final String CAPABILITY = "capability";
        +    static final String NODE = "node";
        +    static final String RELATIONSHIP = "relationship";
        +    private static final String OCCURRENCES = "occurrences";
        +
        +    @Override
        +    public RequirementDefinition deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
        +        JsonObject jsonObject = jsonElement.getAsJsonObject();
        +        RequirementDefinition requirementDefinition = new RequirementDefinition();
        +        setRequirementValues(jsonObject, requirementDefinition);
        +        Optional occurrences = handleOccurrences(jsonObject);
        +        occurrences.ifPresent(requirementDefinition::setOccurrences);
        +        return requirementDefinition;
             }
        -  }
        -
        -  private Optional handleOccurrences(JsonObject jsonObject) {
         
        -    JsonElement occurrencesElement = jsonObject.get(OCCURRENCES);
        -
        -    if(Objects.isNull(occurrencesElement)){
        -      return Optional.empty();
        +    private void setRequirementValues(JsonObject jsonObject, RequirementDefinition requirementDefinition) {
        +        JsonElement capabilityElement = jsonObject.get(CAPABILITY);
        +        if (!Objects.isNull(capabilityElement)) {
        +            requirementDefinition.setCapability(capabilityElement.getAsString());
        +        }
        +        JsonElement nodeElement = jsonObject.get(NODE);
        +        if (!Objects.isNull(nodeElement)) {
        +            requirementDefinition.setNode(nodeElement.getAsString());
        +        }
        +        JsonElement relationshipElement = jsonObject.get(RELATIONSHIP);
        +        if (!Objects.isNull(relationshipElement)) {
        +            requirementDefinition.setRelationship(relationshipElement.getAsString());
        +        }
             }
         
        -    JsonArray occurrences = occurrencesElement.getAsJsonArray();
        -    Object[] fixedOccurrences = new Object[occurrences.size()];
        -
        -    for (int i = 0; i < occurrences.size(); i++) {
        -      JsonElement currElement = occurrences.get(i);
        -
        -      // values inside occurrences array can be either String or Integer
        -      if (currElement.isJsonPrimitive()) {
        -        JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive();
        -
        -        if (jsonPrimitive.isNumber()) {
        -          fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue();
        -        } else {
        -          fixedOccurrences[i] = jsonPrimitive.getAsString();
        +    private Optional handleOccurrences(JsonObject jsonObject) {
        +        JsonElement occurrencesElement = jsonObject.get(OCCURRENCES);
        +        if (Objects.isNull(occurrencesElement)) {
        +            return Optional.empty();
        +        }
        +        JsonArray occurrences = occurrencesElement.getAsJsonArray();
        +        Object[] fixedOccurrences = new Object[occurrences.size()];
        +        for (int i = 0; i < occurrences.size(); i++) {
        +            JsonElement currElement = occurrences.get(i);
        +            // values inside occurrences array can be either String or Integer
        +            if (currElement.isJsonPrimitive()) {
        +                JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive();
        +                if (jsonPrimitive.isNumber()) {
        +                    fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue();
        +                } else {
        +                    fixedOccurrences[i] = jsonPrimitive.getAsString();
        +                }
        +            }
                 }
        -      }
        +        return Optional.of(fixedOccurrences);
             }
        -
        -    return Optional.of(fixedOccurrences);
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java
        index 386486ff9e..97191fd2a5 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java
        @@ -16,7 +16,6 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.utilities.exception;
         
         public class NewInstanceRuntimeException extends RuntimeException {
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java
        index 2a3a3bd19e..89f1f3a293 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.utilities.file;
         
         import java.io.ByteArrayInputStream;
        @@ -54,7 +53,6 @@ public class FileContentHandler {
                 if (content == null || content.length == 0) {
                     return null;
                 }
        -
                 return new ByteArrayInputStream(content);
             }
         
        @@ -101,7 +99,7 @@ public class FileContentHandler {
              * Adds a file.
              *
              * @param filePath the file path
        -     * @param content the file content
        +     * @param content  the file content
              */
             public void addFile(final String filePath, final byte[] content) {
                 files.put(filePath, content == null ? new byte[0] : content);
        @@ -110,7 +108,7 @@ public class FileContentHandler {
             /**
              * Adds a file.
              *
        -     * @param filePath the file path
        +     * @param filePath        the file path
              * @param fileInputStream the file input stream
              */
             public void addFile(final String filePath, final InputStream fileInputStream) {
        @@ -123,8 +121,7 @@ public class FileContentHandler {
              * @return a file path:content map
              */
             public Map getFiles() {
        -        return files.entrySet().stream().filter(entry -> entry.getValue() != null)
        -            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        +        return files.entrySet().stream().filter(entry -> entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
             }
         
             public void setFiles(final Map files) {
        @@ -190,5 +187,4 @@ public class FileContentHandler {
             public boolean containsFile(final String filePath) {
                 return files.containsKey(filePath);
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java
        index f69a2a060a..60ff1c172a 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.utilities.file;
         
         import java.io.ByteArrayInputStream;
        @@ -43,284 +42,262 @@ import org.openecomp.sdc.common.zip.exception.ZipException;
          */
         public class FileUtils {
         
        -  /**
        -   * Allows to consume an input stream open against a resource with a given file name.
        -   *
        -   * @param fileName the file name
        -   * @param function logic to be applied to the input stream
        -   */
        -  public static  T readViaInputStream(String fileName, Function function) {
        -
        -    Objects.requireNonNull(fileName);
        -
        -    // the leading slash doesn't make sense and doesn't work when used with a class loader
        -    URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/")
        -        ? fileName.substring(1) : fileName);
        -    if (resource == null) {
        -      throw new IllegalArgumentException("Resource not found: " + fileName);
        +    /**
        +     * Allows to consume an input stream open against a resource with a given file name.
        +     *
        +     * @param fileName the file name
        +     * @param function logic to be applied to the input stream
        +     */
        +    public static  T readViaInputStream(String fileName, Function function) {
        +        Objects.requireNonNull(fileName);
        +        // the leading slash doesn't make sense and doesn't work when used with a class loader
        +        URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") ? fileName.substring(1) : fileName);
        +        if (resource == null) {
        +            throw new IllegalArgumentException("Resource not found: " + fileName);
        +        }
        +        return readViaInputStream(resource, function);
             }
         
        -    return readViaInputStream(resource, function);
        -  }
        -
        -  /**
        -   * Allows to consume an input stream open against a resource with a given URL.
        -   *
        -   * @param urlFile the url file
        -   * @param function logic to be applied to the input stream
        -   */
        -  public static  T readViaInputStream(URL urlFile, Function function) {
        -
        -    Objects.requireNonNull(urlFile);
        -    try (InputStream is = urlFile.openStream()) {
        -      return function.apply(is);
        -    } catch (IOException exception) {
        -      throw new RuntimeException(exception);
        +    /**
        +     * Allows to consume an input stream open against a resource with a given URL.
        +     *
        +     * @param urlFile  the url file
        +     * @param function logic to be applied to the input stream
        +     */
        +    public static  T readViaInputStream(URL urlFile, Function function) {
        +        Objects.requireNonNull(urlFile);
        +        try (InputStream is = urlFile.openStream()) {
        +            return function.apply(is);
        +        } catch (IOException exception) {
        +            throw new RuntimeException(exception);
        +        }
             }
        -  }
        -
        -  /**
        -   * Gets file input streams.
        -   *
        -   * @param fileName the file name
        -   * @return the file input streams
        -   */
        -  public static List getAllLocations(String fileName) {
        -
        -    List urls = new LinkedList<>();
        -    Enumeration urlFiles;
        -
        -    try {
        -      urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
        -      while (urlFiles.hasMoreElements()) {
        -        urls.add(urlFiles.nextElement());
        -      }
        -
         
        -    } catch (IOException exception) {
        -      throw new RuntimeException(exception);
        +    /**
        +     * Gets file input streams.
        +     *
        +     * @param fileName the file name
        +     * @return the file input streams
        +     */
        +    public static List getAllLocations(String fileName) {
        +        List urls = new LinkedList<>();
        +        Enumeration urlFiles;
        +        try {
        +            urlFiles = FileUtils.class.getClassLoader().getResources(fileName);
        +            while (urlFiles.hasMoreElements()) {
        +                urls.add(urlFiles.nextElement());
        +            }
        +        } catch (IOException exception) {
        +            throw new RuntimeException(exception);
        +        }
        +        return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
             }
         
        -    return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls);
        -  }
        -
        -  /**
        -   * Convert to bytes byte [ ].
        -   *
        -   * @param object    the object
        -   * @param extension the extension
        -   * @return the byte [ ]
        -   */
        -  public static byte[] convertToBytes(Object object, FileExtension extension) {
        -    if (object != null) {
        -      if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
        -        return new YamlUtil().objectToYaml(object).getBytes();
        -      } else {
        -        return JsonUtil.object2Json(object).getBytes();
        -      }
        -    } else {
        -      return new byte[]{};
        +    /**
        +     * Convert to bytes byte [ ].
        +     *
        +     * @param object    the object
        +     * @param extension the extension
        +     * @return the byte [ ]
        +     */
        +    public static byte[] convertToBytes(Object object, FileExtension extension) {
        +        if (object != null) {
        +            if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
        +                return new YamlUtil().objectToYaml(object).getBytes();
        +            } else {
        +                return JsonUtil.object2Json(object).getBytes();
        +            }
        +        } else {
        +            return new byte[]{};
        +        }
             }
        -  }
        -
        -  /**
        -   * Convert to input stream input stream.
        -   *
        -   * @param object    the object
        -   * @param extension the extension
        -   * @return the input stream
        -   */
        -  public static InputStream convertToInputStream(Object object, FileExtension extension) {
        -    if (object != null) {
         
        -      byte[] content;
        -
        -      if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
        -        content = new YamlUtil().objectToYaml(object).getBytes();
        -      } else {
        -        content = JsonUtil.object2Json(object).getBytes();
        -
        -      }
        -      return new ByteArrayInputStream(content);
        -    } else {
        -      return null;
        +    /**
        +     * Convert to input stream input stream.
        +     *
        +     * @param object    the object
        +     * @param extension the extension
        +     * @return the input stream
        +     */
        +    public static InputStream convertToInputStream(Object object, FileExtension extension) {
        +        if (object != null) {
        +            byte[] content;
        +            if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) {
        +                content = new YamlUtil().objectToYaml(object).getBytes();
        +            } else {
        +                content = JsonUtil.object2Json(object).getBytes();
        +            }
        +            return new ByteArrayInputStream(content);
        +        } else {
        +            return null;
        +        }
             }
        -  }
         
        -  /**
        -   * Load file to input stream input stream.
        -   *
        -   * @param fileName the file name
        -   * @return the input stream
        -   */
        -  public static InputStream loadFileToInputStream(String fileName) {
        -    URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
        -    try {
        -      Enumeration en = Thread.currentThread().getContextClassLoader().getResources(fileName);
        -      while (en.hasMoreElements()) {
        -        urlFile = en.nextElement();
        -      }
        -    } catch (IOException | NullPointerException exception) {
        -      throw new RuntimeException(exception);
        -    }
        -    try {
        -      if (urlFile != null) {
        -        return urlFile.openStream();
        -      } else {
        -        throw new RuntimeException();
        -      }
        -    } catch (IOException | NullPointerException exception) {
        -      throw new RuntimeException(exception);
        +    /**
        +     * Load file to input stream input stream.
        +     *
        +     * @param fileName the file name
        +     * @return the input stream
        +     */
        +    public static InputStream loadFileToInputStream(String fileName) {
        +        URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName);
        +        try {
        +            Enumeration en = Thread.currentThread().getContextClassLoader().getResources(fileName);
        +            while (en.hasMoreElements()) {
        +                urlFile = en.nextElement();
        +            }
        +        } catch (IOException | NullPointerException exception) {
        +            throw new RuntimeException(exception);
        +        }
        +        try {
        +            if (urlFile != null) {
        +                return urlFile.openStream();
        +            } else {
        +                throw new RuntimeException();
        +            }
        +        } catch (IOException | NullPointerException exception) {
        +            throw new RuntimeException(exception);
        +        }
             }
         
        -  }
        -
        -  /**
        -   * To byte array byte [ ].
        -   *
        -   * @param input the input
        -   * @return the byte [ ]
        -   */
        -  public static byte[] toByteArray(InputStream input) {
        -    if (input == null) {
        -      return new byte[0];
        -    }
        -    try {
        -      return IOUtils.toByteArray(input);
        -    } catch (IOException exception) {
        -      throw new RuntimeException(
        -          "error while converting input stream to byte array", exception);
        +    /**
        +     * To byte array byte [ ].
        +     *
        +     * @param input the input
        +     * @return the byte [ ]
        +     */
        +    public static byte[] toByteArray(InputStream input) {
        +        if (input == null) {
        +            return new byte[0];
        +        }
        +        try {
        +            return IOUtils.toByteArray(input);
        +        } catch (IOException exception) {
        +            throw new RuntimeException("error while converting input stream to byte array", exception);
        +        }
             }
        -  }
         
        -  /**
        -   * Gets file without extention.
        -   *
        -   * @param fileName the file name
        -   * @return the file without extention
        -   */
        -  public static String getFileWithoutExtention(String fileName) {
        -    if (!fileName.contains(".")) {
        -      return fileName;
        +    /**
        +     * Gets file without extention.
        +     *
        +     * @param fileName the file name
        +     * @return the file without extention
        +     */
        +    public static String getFileWithoutExtention(String fileName) {
        +        if (!fileName.contains(".")) {
        +            return fileName;
        +        }
        +        return fileName.substring(0, fileName.lastIndexOf('.'));
             }
        -    return fileName.substring(0, fileName.lastIndexOf('.'));
        -  }
         
        -  public static String getFileExtension(String filename) {
        -      return FilenameUtils.getExtension(filename);
        -  }
        -
        -  public static String getNetworkPackageName(String filename) {
        -    String[] split = filename.split("\\.");
        -    String name = null;
        -    if (split.length > 1) {
        -      name = split[0];
        +    public static String getFileExtension(String filename) {
        +        return FilenameUtils.getExtension(filename);
             }
        -    return name;
        -  }
        -
        -  /**
        -   * Gets file content map from zip.
        -   *
        -   * @param zipData the zip data
        -   * @return the file content map from zip
        -   * @throws ZipException when an error occurs while extracting zip files
        -   */
        -  public static FileContentHandler getFileContentMapFromZip(byte[] zipData)
        -      throws ZipException {
        -    final Map zipFileAndByteMap = ZipUtils.readZip(zipData, true);
        -    final FileContentHandler fileContentHandler = new FileContentHandler();
        -    zipFileAndByteMap.forEach((path, bytes) -> {
        -      if (bytes == null) {
        -        fileContentHandler.addFolder(path);
        -      } else {
        -        fileContentHandler.addFile(path, bytes);
        -      }
        -    });
        -    return fileContentHandler;
        -  }
         
        -
        -  /**
        -   * The enum File extension.
        -   */
        -  public enum FileExtension {
        +    public static String getNetworkPackageName(String filename) {
        +        String[] split = filename.split("\\.");
        +        String name = null;
        +        if (split.length > 1) {
        +            name = split[0];
        +        }
        +        return name;
        +    }
         
             /**
        -     * Json file extension.
        -     */
        -    JSON("json"),
        -    /**
        -     * Yaml file extension.
        +     * Gets file content map from zip.
        +     *
        +     * @param zipData the zip data
        +     * @return the file content map from zip
        +     * @throws ZipException when an error occurs while extracting zip files
              */
        -    YAML("yaml"),
        +    public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws ZipException {
        +        final Map zipFileAndByteMap = ZipUtils.readZip(zipData, true);
        +        final FileContentHandler fileContentHandler = new FileContentHandler();
        +        zipFileAndByteMap.forEach((path, bytes) -> {
        +            if (bytes == null) {
        +                fileContentHandler.addFolder(path);
        +            } else {
        +                fileContentHandler.addFile(path, bytes);
        +            }
        +        });
        +        return fileContentHandler;
        +    }
        +
             /**
        -     * Yml file extension.
        +     * Write files and folders map to disk in the given path
        +     *
        +     * @param fileContentHandler the file content handler
        +     * @param dir                the dir
        +     * @return a map containing file names and their absolute paths
        +     * @throws IOException the io exception
              */
        -    YML("yml");
        -
        -    private final String displayName;
        -
        -    FileExtension(String displayName) {
        -      this.displayName = displayName;
        +    public static Map writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler, final Path dir)
        +        throws IOException {
        +        final File dirFile = dir.toFile();
        +        final Map filePaths = new HashMap<>();
        +        File file;
        +        for (final String folderPath : fileContentHandler.getFolderList()) {
        +            file = new File(dirFile, folderPath);
        +            filePaths.put(folderPath, file.getAbsolutePath());
        +            if (!file.exists() && !file.mkdirs()) {
        +                throw new IOException("Could not create directory " + file.getAbsolutePath());
        +            }
        +        }
        +        for (final Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) {
        +            file = new File(dirFile, fileEntry.getKey());
        +            filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
        +            final byte[] fileBytes = fileEntry.getValue();
        +            if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        +                throw new IOException("Could not create parent directory for " + file.getAbsolutePath());
        +            }
        +            try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
        +                fop.write(fileBytes);
        +                fop.flush();
        +            }
        +        }
        +        return filePaths;
             }
         
             /**
        -     * Gets display name.
        +     * Verify whether the provided extension is valid Yaml/Yml extension or not.
              *
        -     * @return the display name
        +     * @param fileExtension the file extension
        +     * @return the boolean
              */
        -    public String getDisplayName() {
        -      return displayName;
        +    public static boolean isValidYamlExtension(String fileExtension) {
        +        return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) || fileExtension
        +            .equalsIgnoreCase(FileExtension.YAML.getDisplayName());
             }
        -  }
         
        -
        -  /**
        -   * Write files and folders map to disk in the given path
        -   *
        -   * @param fileContentHandler the file content handler
        -   * @param dir                the dir
        -   * @return a map containing file names and their absolute paths
        -   * @throws IOException the io exception
        -   */
        -  public static Map writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler,
        -                                                                     final Path dir) throws IOException {
        -    final File dirFile = dir.toFile();
        -    final Map filePaths = new HashMap<>();
        -    File file;
        -    for (final String folderPath : fileContentHandler.getFolderList()) {
        -      file = new File(dirFile, folderPath);
        -      filePaths.put(folderPath, file.getAbsolutePath());
        -      if (!file.exists() && !file.mkdirs()) {
        -        throw new IOException("Could not create directory " + file.getAbsolutePath());
        -      }
        -    }
        -    for (final Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) {
        -      file = new File(dirFile, fileEntry.getKey());
        -      filePaths.put(fileEntry.getKey(), file.getAbsolutePath());
        -      final byte[] fileBytes = fileEntry.getValue();
        -      if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
        -        throw new IOException("Could not create parent directory for " + file.getAbsolutePath());
        -      }
        -      try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) {
        -        fop.write(fileBytes);
        -        fop.flush();
        -      }
        +    /**
        +     * The enum File extension.
        +     */
        +    public enum FileExtension {
        +        /**
        +         * Json file extension.
        +         */
        +        JSON("json"),
        +        /**
        +         * Yaml file extension.
        +         */
        +        YAML("yaml"),
        +        /**
        +         * Yml file extension.
        +         */
        +        YML("yml");
        +        private final String displayName;
        +
        +        FileExtension(String displayName) {
        +            this.displayName = displayName;
        +        }
        +
        +        /**
        +         * Gets display name.
        +         *
        +         * @return the display name
        +         */
        +        public String getDisplayName() {
        +            return displayName;
        +        }
             }
        -
        -    return filePaths;
        -  }
        -
        -  /**
        -   * Verify whether the provided extension is valid Yaml/Yml extension or not.
        -   *
        -   * @param fileExtension the file extension
        -   * @return the boolean
        -   */
        -  public static boolean isValidYamlExtension(String fileExtension){
        -    return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) ||
        -        fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName());
        -  }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java
        index 2db691a781..fceef8bb51 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,160 +17,149 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.utilities.json;
         
        +import java.util.HashMap;
        +import java.util.Map;
         import org.json.JSONException;
         import org.json.JSONObject;
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -import java.util.HashMap;
        -import java.util.Map;
        -
         public class JsonSchemaDataGenerator {
         
        -  private static final String ROOT = "root";
        -  private static final Logger logger =
        -      LoggerFactory.getLogger(JsonSchemaDataGenerator.class);
        -  boolean includeDefaults = true;
        -  private JSONObject root;
        -  private Map referencesData;
        -
        -  /**
        -   * Instantiates a new Json schema data generator.
        -   *
        -   * @param jsonSchema the json schema
        -   */
        -  public JsonSchemaDataGenerator(String jsonSchema) {
        -    if (jsonSchema == null) {
        -      throw new IllegalArgumentException("Input string jsonSchema can not be null");
        +    private static final String ROOT = "root";
        +    private static final Logger logger = LoggerFactory.getLogger(JsonSchemaDataGenerator.class);
        +    boolean includeDefaults = true;
        +    private JSONObject root;
        +    private Map referencesData;
        +
        +    /**
        +     * Instantiates a new Json schema data generator.
        +     *
        +     * @param jsonSchema the json schema
        +     */
        +    public JsonSchemaDataGenerator(String jsonSchema) {
        +        if (jsonSchema == null) {
        +            throw new IllegalArgumentException("Input string jsonSchema can not be null");
        +        }
        +        root = new JSONObject(jsonSchema);
             }
        -    root = new JSONObject(jsonSchema);
        -  }
         
        -  public void setIncludeDefaults(boolean includeDefaults) {
        -    this.includeDefaults = includeDefaults;
        -  }
        -
        -  /**
        -   * Generates json data that conform to the schema according to turned on flags.
        -   *
        -   * @return json that conform to the schema
        -   */
        -  public String generateData() {
        -    referencesData = new HashMap<>();
        -    JSONObject data = new JSONObject();
        -
        -    generateData(ROOT, root,
        -        data);
        -    // "root" is dummy name to represent the top level object
        -    // (which, as apposed to inner objects, doesn't have a name in the schema)
        -    return data.has(ROOT) ? data.get(ROOT).toString() : data.toString();
        -  }
        -
        -  private void generateData(String propertyName, JSONObject property, JSONObject propertyData) {
        -    if (property.has(JsonSchemaKeyword.TYPE)) {
        -      String propertyType = property.getString(JsonSchemaKeyword.TYPE);
        -      if (JsonSchemaKeyword.OBJECT.equals(propertyType)) {
        -        generateObjectData(propertyName, property, propertyData);
        -      } else {
        -        generatePrimitiveData(propertyType, propertyName, property, propertyData);
        -      }
        -    } else if (property.has(JsonSchemaKeyword.REF)) {
        -      generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData);
        +    public void setIncludeDefaults(boolean includeDefaults) {
        +        this.includeDefaults = includeDefaults;
             }
        -  }
        -
        -  private void generateObjectData(String propertyName, JSONObject property,
        -                                  JSONObject propertyData) {
        -    JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES);
         
        -    JSONObject subPropertiesData = new JSONObject();
        -    for (String subPropertyName : subProperties.keySet()) {
        -      generateData(subPropertyName, subProperties.getJSONObject(subPropertyName),
        -          subPropertiesData);
        +    /**
        +     * Generates json data that conform to the schema according to turned on flags.
        +     *
        +     * @return json that conform to the schema
        +     */
        +    public String generateData() {
        +        referencesData = new HashMap<>();
        +        JSONObject data = new JSONObject();
        +        generateData(ROOT, root, data);
        +        // "root" is dummy name to represent the top level object
        +
        +        // (which, as apposed to inner objects, doesn't have a name in the schema)
        +        return data.has(ROOT) ? data.get(ROOT).toString() : data.toString();
             }
         
        -    if (subPropertiesData.length() > 0) {
        -      propertyData.put(propertyName, subPropertiesData);
        +    private void generateData(String propertyName, JSONObject property, JSONObject propertyData) {
        +        if (property.has(JsonSchemaKeyword.TYPE)) {
        +            String propertyType = property.getString(JsonSchemaKeyword.TYPE);
        +            if (JsonSchemaKeyword.OBJECT.equals(propertyType)) {
        +                generateObjectData(propertyName, property, propertyData);
        +            } else {
        +                generatePrimitiveData(propertyType, propertyName, property, propertyData);
        +            }
        +        } else if (property.has(JsonSchemaKeyword.REF)) {
        +            generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData);
        +        }
             }
        -  }
         
        -  private void generateReferenceData(String propertyName, String referencePath,
        -                                     JSONObject propertyData) {
        -    if (referencesData.containsKey(referencePath)) {
        -      Object referenceData = referencesData.get(referencePath);
        -      if (referenceData != null) {
        -        propertyData.put(propertyName, referenceData);
        -      }
        -    } else {
        -      generateData(propertyName, resolveReference(referencePath), propertyData);
        -      referencesData.put(referencePath, propertyData.opt(propertyName));
        +    private void generateObjectData(String propertyName, JSONObject property, JSONObject propertyData) {
        +        JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES);
        +        JSONObject subPropertiesData = new JSONObject();
        +        for (String subPropertyName : subProperties.keySet()) {
        +            generateData(subPropertyName, subProperties.getJSONObject(subPropertyName), subPropertiesData);
        +        }
        +        if (subPropertiesData.length() > 0) {
        +            propertyData.put(propertyName, subPropertiesData);
        +        }
             }
        -  }
         
        -  private JSONObject resolveReference(String referencePath) {
        -    String[] keys = referencePath.replaceFirst("#/", "").split("/");
        -
        -    JSONObject reference = root;
        -    for (String key : keys) {
        -      reference = reference.getJSONObject(key);
        +    private void generateReferenceData(String propertyName, String referencePath, JSONObject propertyData) {
        +        if (referencesData.containsKey(referencePath)) {
        +            Object referenceData = referencesData.get(referencePath);
        +            if (referenceData != null) {
        +                propertyData.put(propertyName, referenceData);
        +            }
        +        } else {
        +            generateData(propertyName, resolveReference(referencePath), propertyData);
        +            referencesData.put(referencePath, propertyData.opt(propertyName));
        +        }
             }
        -    return reference;
        -  }
         
        -  private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property,
        -                                     JSONObject propertyData) {
        -    if (includeDefaults) {
        -      populateWithDefaultValue(propertyType, propertyName, property, propertyData);
        +    private JSONObject resolveReference(String referencePath) {
        +        String[] keys = referencePath.replaceFirst("#/", "").split("/");
        +        JSONObject reference = root;
        +        for (String key : keys) {
        +            reference = reference.getJSONObject(key);
        +        }
        +        return reference;
             }
        -  }
         
        -  private void populateWithDefaultValue(String propertyType, String propertyName,
        -                                        JSONObject property, JSONObject propertyData) {
        -    if (!property.has(JsonSchemaKeyword.DEFAULT)) {
        -      return;
        +    private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, JSONObject propertyData) {
        +        if (includeDefaults) {
        +            populateWithDefaultValue(propertyType, propertyName, property, propertyData);
        +        }
             }
        -    try {
        -      switch (propertyType) {
        -        case JsonSchemaKeyword.ARRAY:
        -          propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT));
        -          break;
        -        case JsonSchemaKeyword.BOOLEAN:
        -          propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT));
        -          break;
        -        case JsonSchemaKeyword.INTEGER:
        -          propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT));
        -          break;
        -        case JsonSchemaKeyword.NUMBER:
        -          propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT));
        -          break;
        -        case JsonSchemaKeyword.STRING:
        -          propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT));
        -          break;
        -        default:
        -          break;
        -      }
        -    } catch (JSONException exception) {
        -      Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT);
        -      logger.error(String.format(
        -          "Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.",
        -          propertyName, propertyType, defaultValue), exception);
        -      throw exception;
        +
        +    private void populateWithDefaultValue(String propertyType, String propertyName, JSONObject property, JSONObject propertyData) {
        +        if (!property.has(JsonSchemaKeyword.DEFAULT)) {
        +            return;
        +        }
        +        try {
        +            switch (propertyType) {
        +                case JsonSchemaKeyword.ARRAY:
        +                    propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT));
        +                    break;
        +                case JsonSchemaKeyword.BOOLEAN:
        +                    propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT));
        +                    break;
        +                case JsonSchemaKeyword.INTEGER:
        +                    propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT));
        +                    break;
        +                case JsonSchemaKeyword.NUMBER:
        +                    propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT));
        +                    break;
        +                case JsonSchemaKeyword.STRING:
        +                    propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT));
        +                    break;
        +                default:
        +                    break;
        +            }
        +        } catch (JSONException exception) {
        +            Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT);
        +            logger.error(String
        +                .format("Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.", propertyName, propertyType,
        +                    defaultValue), exception);
        +            throw exception;
        +        }
             }
        -  }
         
        -  private static class JsonSchemaKeyword {
        -    private static final String DEFAULT = "default";
        -    private static final String TYPE = "type";
        -    private static final String PROPERTIES = "properties";
        -    private static final String ARRAY = "array";
        -    private static final String BOOLEAN = "boolean";
        -    private static final String INTEGER = "integer";
        -    private static final String NUMBER = "number";
        -    private static final String STRING = "string";
        -    private static final String OBJECT = "object";
        -    private static final String REF = "$ref";
        -  }
        +    private static class JsonSchemaKeyword {
        +
        +        private static final String DEFAULT = "default";
        +        private static final String TYPE = "type";
        +        private static final String PROPERTIES = "properties";
        +        private static final String ARRAY = "array";
        +        private static final String BOOLEAN = "boolean";
        +        private static final String INTEGER = "integer";
        +        private static final String NUMBER = "number";
        +        private static final String STRING = "string";
        +        private static final String OBJECT = "object";
        +        private static final String REF = "$ref";
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
        index b83ad2782d..b148d6457d 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.utilities.json;
         
         import com.google.gson.Gson;
        @@ -21,7 +20,6 @@ import com.google.gson.GsonBuilder;
         import com.google.gson.JsonIOException;
         import com.google.gson.JsonParser;
         import com.google.gson.JsonSyntaxException;
        -
         import java.io.BufferedReader;
         import java.io.IOException;
         import java.io.InputStream;
        @@ -32,7 +30,6 @@ import java.util.Collections;
         import java.util.List;
         import java.util.Set;
         import java.util.stream.Collectors;
        -
         import org.apache.commons.collections4.CollectionUtils;
         import org.everit.json.schema.EnumSchema;
         import org.everit.json.schema.Schema;
        @@ -46,7 +43,6 @@ import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeseriali
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -
         /**
          * The type Json util.
          */
        @@ -58,8 +54,7 @@ public class JsonUtil {
         
             static {
                 gsonBuilder = new GsonBuilder();
        -        gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
        -                RequirementDefinitionDeserializer());
        +        gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new RequirementDefinitionDeserializer());
                 gson = gsonBuilder.create();
             }
         
        @@ -74,7 +69,6 @@ public class JsonUtil {
              */
             public static String object2Json(Object obj) {
                 return sbObject2Json(obj).toString();
        -
             }
         
             /**
        @@ -125,13 +119,13 @@ public class JsonUtil {
                 return type;
             }
         
        -
             /**
              * Is valid json boolean.
              *
              * @param json the json
              * @return the boolean
              */
        +
             //todo check https://github.com/stleary/JSON-java as replacement for this code
             public static boolean isValidJson(String json) {
                 try {
        @@ -152,30 +146,25 @@ public class JsonUtil {
             public static List validate(String json, String jsonSchema) {
                 List validationErrors = validateUsingEverit(json, jsonSchema);
                 return validationErrors == null ? null
        -                : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
        -                        .collect(Collectors.toList());
        +            : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage).collect(Collectors.toList());
             }
         
             private static String mapValidationExceptionToMessage(ValidationException exception) {
                 Object schema = exception.getViolatedSchema();
        -
                 if (schema instanceof EnumSchema) {
                     return mapEnumViolationToMessage(exception);
                 } else if (schema instanceof StringSchema) {
                     return mapStringViolationToMessage(exception);
                 }
        -
                 return exception.getMessage();
             }
         
             private static String mapEnumViolationToMessage(ValidationException exception) {
                 Set possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
        -        return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
        -                ? String.format("value. %s is the only possible value for this field",
        -                possibleValues.iterator().next())
        -                : String.format("value. Possible values: %s", CommonMethods
        -                        .collectionToCommaSeparatedString(
        -                                possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
        +        return exception.getMessage().replaceFirst("enum value",
        +            possibleValues.size() == 1 ? String.format("value. %s is the only possible value for this field", possibleValues.iterator().next())
        +                : String.format("value. Possible values: %s",
        +                    CommonMethods.collectionToCommaSeparatedString(possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
             }
         
             private static String mapStringViolationToMessage(ValidationException validationException) {
        @@ -188,25 +177,21 @@ public class JsonUtil {
             }
         
             private static List validateUsingEverit(String json, String jsonSchema) {
        -        LOGGER.debug(
        -                String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
        +        LOGGER.debug(String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
                 if (json == null || jsonSchema == null) {
                     throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
                 }
        -
                 Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
                 try {
                     schemaObj.validate(new JSONObject(json));
                 } catch (ValidationException ve) {
        -            return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
        -                    : ve.getCausingExceptions();
        +            return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve) : ve.getCausingExceptions();
                 }
                 return null;
             }
         
             private enum ValidationType {
                 PATTERN("pattern");
        -
                 private String keyword;
         
                 ValidationType(String keyword) {
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java
        index 1fa96103ab..4ed85f939b 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java
        @@ -13,11 +13,11 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.utilities.orchestration;
         
         import java.util.Arrays;
         import org.apache.commons.lang3.StringUtils;
        +
         public enum OnboardingTypesEnum {
             CSAR("csar"), ZIP("zip"), MANUAL("manual"), NONE("none"), SIGNED_CSAR("signed-csar");
             private final String type;
        @@ -26,19 +26,16 @@ public enum OnboardingTypesEnum {
                 this.type = type;
             }
         
        -    @Override
        -    public String toString() {
        -        return type;
        -    }
        -
             public static OnboardingTypesEnum getOnboardingTypesEnum(final String type) {
                 if (StringUtils.isEmpty(type)) {
                     return null;
                 }
        -
        -        return Arrays.stream(OnboardingTypesEnum.values())
        -            .filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equalsIgnoreCase(type))
        +        return Arrays.stream(OnboardingTypesEnum.values()).filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equalsIgnoreCase(type))
                     .findAny().orElse(null);
             }
         
        +    @Override
        +    public String toString() {
        +        return type;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java
        index 2da562f4ea..932adbfe59 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java
        @@ -28,29 +28,25 @@ import org.openecomp.types.ElementPropertyName;
         
         public abstract class ElementConvertor {
         
        -  public static ElementType getElementType(Element element) {
        -    return ElementType
        -        .valueOf(element.getInfo().getProperty(ElementPropertyName.elementType.name()));
        -  }
        +    public static ElementType getElementType(Element element) {
        +        return ElementType.valueOf(element.getInfo().getProperty(ElementPropertyName.elementType.name()));
        +    }
         
        -  public static String getElementName(Element element) {
        -    return element.getInfo().getName();
        -  }
        +    public static String getElementName(Element element) {
        +        return element.getInfo().getName();
        +    }
         
        +    abstract public T convert(Element element);
         
        -  abstract public T convert(Element element);
        +    public T convert(ElementInfo elementInfo) {
        +        throw new UnsupportedOperationException("convert elementInfo item is not supported ");
        +    }
         
        -  public T convert( ElementInfo elementInfo) {
        -    throw new UnsupportedOperationException("convert elementInfo item is not supported ");
        -  }
        +    public T convert(Item item) {
        +        throw new UnsupportedOperationException("convert from item is not supported ");
        +    }
         
        -
        -  public T convert( Item item) {
        -    throw new UnsupportedOperationException("convert from item is not supported ");
        -  }
        -
        -
        -  public T convert( ItemVersion itemVersion) {
        -    throw new UnsupportedOperationException("convert from itemVersion is not supported ");
        -  }
        +    public T convert(ItemVersion itemVersion) {
        +        throw new UnsupportedOperationException("convert from itemVersion is not supported ");
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java
        index 32630df115..0583bed12f 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java
        @@ -13,99 +13,95 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.zusammen.api;
         
        -import com.amdocs.zusammen.adaptor.inbound.api.types.item.*;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement;
         import com.amdocs.zusammen.commons.health.data.HealthInfo;
         import com.amdocs.zusammen.datatypes.Id;
         import com.amdocs.zusammen.datatypes.SessionContext;
        -import com.amdocs.zusammen.datatypes.item.*;
        +import com.amdocs.zusammen.datatypes.item.ElementContext;
        +import com.amdocs.zusammen.datatypes.item.Info;
        +import com.amdocs.zusammen.datatypes.item.Item;
        +import com.amdocs.zusammen.datatypes.item.ItemVersion;
        +import com.amdocs.zusammen.datatypes.item.ItemVersionData;
        +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus;
        +import com.amdocs.zusammen.datatypes.item.Resolution;
         import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions;
         import com.amdocs.zusammen.datatypes.itemversion.Tag;
        -
         import java.util.Collection;
         import java.util.Optional;
         
         public interface ZusammenAdaptor {
         
        -  Collection listItems(SessionContext context);
        +    Collection listItems(SessionContext context);
         
        -  Item getItem(SessionContext context, Id itemId);
        +    Item getItem(SessionContext context, Id itemId);
         
        -  void deleteItem(SessionContext context, Id itemId);
        +    void deleteItem(SessionContext context, Id itemId);
         
        -  Id createItem(SessionContext context, Info info);
        +    Id createItem(SessionContext context, Info info);
         
        -  void updateItem(SessionContext context, Id itemId, Info info);
        +    void updateItem(SessionContext context, Id itemId, Info info);
         
        -  Collection listPublicVersions(SessionContext context, Id itemId);
        +    Collection listPublicVersions(SessionContext context, Id itemId);
         
        -  ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId);
        +    ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId);
         
        -  Id createVersion(SessionContext context, Id itemId, Id baseVersionId,
        -                   ItemVersionData itemVersionData);
        +    Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData);
         
        -  void updateVersion(SessionContext context, Id itemId, Id versionId,
        -                     ItemVersionData itemVersionData);
        +    void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData);
         
        -  ItemVersion getVersion(SessionContext context, Id itemId, Id versionId);
        +    ItemVersion getVersion(SessionContext context, Id itemId, Id versionId);
         
        -  ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId);
        +    ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId);
         
        -  ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId);
        +    ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId);
         
        -  void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag);
        +    void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag);
         
        -  void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String version);
        +    void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String version);
         
        -  void publishVersion(SessionContext context, Id itemId, Id versionId, String message);
        +    void publishVersion(SessionContext context, Id itemId, Id versionId, String message);
         
        -  void syncVersion(SessionContext context, Id itemId, Id versionId);
        +    void syncVersion(SessionContext context, Id itemId, Id versionId);
         
        -  void forceSyncVersion(SessionContext context, Id itemId, Id versionId);
        +    void forceSyncVersion(SessionContext context, Id itemId, Id versionId);
         
        -  void cleanVersion(SessionContext context, Id itemId, Id versionId);
        +    void cleanVersion(SessionContext context, Id itemId, Id versionId);
         
        -  Optional getElementInfo(SessionContext context, ElementContext elementContext,
        -                                       Id elementId);
        +    Optional getElementInfo(SessionContext context, ElementContext elementContext, Id elementId);
         
        -  Optional getElement(SessionContext context, ElementContext elementContext,
        -                               String elementId); // TODO: 4/3/2017 change to Id
        +    Optional getElement(SessionContext context, ElementContext elementContext,
        +                                 String elementId); // TODO: 4/3/2017 change to Id
         
        -  Optional getElementByName(SessionContext context, ElementContext elementContext,
        -                                     Id parentElementId, String elementName);
        +    Optional getElementByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName);
         
        -  Collection listElements(SessionContext context, ElementContext elementContext,
        -                                       Id parentElementId);
        +    Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId);
         
        -  Collection listElementData(SessionContext context, ElementContext elementContext,
        -                                      Id parentElementId);
        +    Collection listElementData(SessionContext context, ElementContext elementContext, Id parentElementId);
         
        -  /**
        -   * Lists the sub elements of the element named elementName which is a sub element of
        -   * parentElementId
        -   */
        -  Collection listElementsByName(SessionContext context, ElementContext elementContext,
        -                                             Id parentElementId, String elementName);
        +    /**
        +     * Lists the sub elements of the element named elementName which is a sub element of parentElementId
        +     */
        +    Collection listElementsByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName);
         
        -  Optional getElementInfoByName(SessionContext context, ElementContext elementContext,
        -                                             Id parentElementId, String elementName);
        +    Optional getElementInfoByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName);
         
        -  Optional getElementConflict(SessionContext context,
        -                                               ElementContext elementContext, Id elementId);
        +    Optional getElementConflict(SessionContext context, ElementContext elementContext, Id elementId);
         
        -  Element saveElement(SessionContext context, ElementContext elementContext,
        -                      ZusammenElement element, String message);
        +    Element saveElement(SessionContext context, ElementContext elementContext, ZusammenElement element, String message);
         
        -  void resolveElementConflict(SessionContext context, ElementContext elementContext,
        -                              ZusammenElement element, Resolution resolution);
        +    void resolveElementConflict(SessionContext context, ElementContext elementContext, ZusammenElement element, Resolution resolution);
         
        -  void revert(SessionContext context, Id itemId, Id versionId, Id revisionId);
        +    void revert(SessionContext context, Id itemId, Id versionId, Id revisionId);
         
        -  ItemVersionRevisions listRevisions(SessionContext context, Id itemId, Id versionId);
        +    ItemVersionRevisions listRevisions(SessionContext context, Id itemId, Id versionId);
         
        -  Collection checkHealth(SessionContext context);
        +    Collection checkHealth(SessionContext context);
         
        -  String getVersion(SessionContext context);
        +    String getVersion(SessionContext context);
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptorFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptorFactory.java
        index 53981ba478..1f0bbe58ec 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptorFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptorFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.zusammen.api;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory;
         
         public abstract class ZusammenAdaptorFactory extends AbstractComponentFactory {
         
        -  public static ZusammenAdaptorFactory getInstance() {
        -    return AbstractFactory.getInstance(ZusammenAdaptorFactory.class);
        -  }
        +    public static ZusammenAdaptorFactory getInstance() {
        +        return AbstractFactory.getInstance(ZusammenAdaptorFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java
        index f6f8b2b5d9..a6595699f5 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java
        @@ -31,43 +31,39 @@ import org.openecomp.types.ElementPropertyName;
         
         public class ZusammenUtil {
         
        -  private ZusammenUtil() {
        -    throw new IllegalStateException("Utility class");
        -  }
        +    private ZusammenUtil() {
        +        throw new IllegalStateException("Utility class");
        +    }
         
        -  public static SessionContext createSessionContext() {
        -    org.openecomp.sdc.common.session.SessionContext asdcSessionContext =
        -        SessionContextProviderFactory.getInstance().createInterface().get();
        +    public static SessionContext createSessionContext() {
        +        org.openecomp.sdc.common.session.SessionContext asdcSessionContext = SessionContextProviderFactory.getInstance().createInterface().get();
        +        return createSessionContext(asdcSessionContext.getUser().getUserId(), asdcSessionContext.getTenant());
        +    }
         
        -    return createSessionContext(asdcSessionContext.getUser().getUserId(), asdcSessionContext
        -        .getTenant());
        -  }
        +    private static SessionContext createSessionContext(String user, String tenant) {
        +        SessionContext sessionContext = new SessionContext();
        +        sessionContext.setUser(new UserInfo(user));
        +        sessionContext.setTenant(tenant);
        +        return sessionContext;
        +    }
         
        -  private static SessionContext createSessionContext(String user, String tenant) {
        -    SessionContext sessionContext = new SessionContext();
        -    sessionContext.setUser(new UserInfo(user));
        -    sessionContext.setTenant(tenant);
        -    return sessionContext;
        -  }
        +    public static ZusammenElement buildStructuralElement(ElementType elementType, Action action) {
        +        return buildStructuralElement(elementType.name(), action);
        +    }
         
        -  public static ZusammenElement buildStructuralElement(ElementType elementType, Action action) {
        -    return buildStructuralElement(elementType.name(), action);
        -  }
        +    public static ZusammenElement buildStructuralElement(String elementType, Action action) {
        +        ZusammenElement element = buildElement(null, action);
        +        Info info = new Info();
        +        info.setName(elementType);
        +        info.addProperty(ElementPropertyName.elementType.name(), elementType);
        +        element.setInfo(info);
        +        return element;
        +    }
         
        -
        -  public static ZusammenElement buildStructuralElement(String elementType, Action action) {
        -    ZusammenElement element = buildElement(null, action);
        -    Info info = new Info();
        -    info.setName(elementType);
        -    info.addProperty(ElementPropertyName.elementType.name(), elementType);
        -    element.setInfo(info);
        -    return element;
        -  }
        -
        -  public static ZusammenElement buildElement(Id elementId, Action action) {
        -    ZusammenElement element = new ZusammenElement();
        -    element.setElementId(elementId);
        -    element.setAction(action);
        -    return element;
        -  }
        +    public static ZusammenElement buildElement(Id elementId, Action action) {
        +        ZusammenElement element = new ZusammenElement();
        +        element.setElementId(elementId);
        +        element.setAction(action);
        +        return element;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java
        index 557226377e..6a3caa0210 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java
        @@ -25,7 +25,6 @@ import com.amdocs.zusammen.datatypes.item.Action;
         import com.amdocs.zusammen.datatypes.item.Info;
         import com.amdocs.zusammen.datatypes.item.Relation;
         import com.amdocs.zusammen.utils.fileutils.FileUtils;
        -
         import java.io.InputStream;
         import java.util.ArrayList;
         import java.util.Collection;
        @@ -33,118 +32,115 @@ import java.util.Map;
         
         public class AsdcElement implements Element {
         
        -  private String type;
        -  private String name;
        -  private String description;
        -
        -  private Map properties;
        -  private byte[] data;
        -  private Collection relations;
        -  private Collection subElements = new ArrayList<>();
        -  private Action action;
        -  private Id elementId;
        -
        -  @Override
        -  public Action getAction() {
        -    return this.action;
        -  }
        -
        -  @Override
        -  public Id getElementId() {
        -    return this.elementId;
        -  }
        -
        -  @Override
        -  public Info getInfo() {
        -    Info info = new Info();
        -    info.setProperties(this.properties);
        -    info.addProperty(ElementPropertyName.elementType.name(), this.type != null ? this.type : this.name);
        -    info.setName(this.name);
        -    info.setDescription(this.description);
        -
        -    return info;
        -  }
        -
        -  @Override
        -  public Collection getRelations() {
        -    return this.relations;
        -  }
        -
        -  @Override
        -  public InputStream getData() {
        -    return FileUtils.toInputStream(this.data);
        -  }
        -
        -  @Override
        -  public InputStream getSearchableData() {
        -    return null;
        -  }
        -
        -  @Override
        -  public InputStream getVisualization() {
        -    return null;
        -  }
        -
        -
        -  @Override
        -  public Collection getSubElements() {
        -    return this.subElements;
        -  }
        -
        -  public void setElementId(Id elementId) {
        -    this.elementId = elementId;
        -  }
        -
        -  public void setData(InputStream data) {
        -    this.data = FileUtils.toByteArray(data);
        -  }
        -
        -  public void setRelations(Collection relations) {
        -    this.relations = relations;
        -  }
        -
        -  public void setSubElements(Collection subElements) {
        -    this.subElements = subElements;
        -  }
        -
        -  public void setAction(Action action) {
        -    this.action = action;
        -  }
        -
        -  public AsdcElement addSubElement(Element element) {
        -    this.subElements.add(element);
        -    return this;
        -  }
        -
        -  public String getType() {
        -    return type;
        -  }
        -
        -  public void setType(String type) {
        -    this.type = type;
        -  }
        -
        -  public String getName() {
        -    return name;
        -  }
        -
        -  public void setName(String name) {
        -    this.name = name;
        -  }
        -
        -  public String getDescription() {
        -    return description;
        -  }
        -
        -  public void setDescription(String description) {
        -    this.description = description;
        -  }
        -
        -  public Map getProperties() {
        -    return properties;
        -  }
        -
        -  public void setProperties(Map properties) {
        -    this.properties = properties;
        -  }
        +    private String type;
        +    private String name;
        +    private String description;
        +    private Map properties;
        +    private byte[] data;
        +    private Collection relations;
        +    private Collection subElements = new ArrayList<>();
        +    private Action action;
        +    private Id elementId;
        +
        +    @Override
        +    public Action getAction() {
        +        return this.action;
        +    }
        +
        +    public void setAction(Action action) {
        +        this.action = action;
        +    }
        +
        +    @Override
        +    public Id getElementId() {
        +        return this.elementId;
        +    }
        +
        +    public void setElementId(Id elementId) {
        +        this.elementId = elementId;
        +    }
        +
        +    @Override
        +    public Info getInfo() {
        +        Info info = new Info();
        +        info.setProperties(this.properties);
        +        info.addProperty(ElementPropertyName.elementType.name(), this.type != null ? this.type : this.name);
        +        info.setName(this.name);
        +        info.setDescription(this.description);
        +        return info;
        +    }
        +
        +    @Override
        +    public Collection getRelations() {
        +        return this.relations;
        +    }
        +
        +    public void setRelations(Collection relations) {
        +        this.relations = relations;
        +    }
        +
        +    @Override
        +    public InputStream getData() {
        +        return FileUtils.toInputStream(this.data);
        +    }
        +
        +    public void setData(InputStream data) {
        +        this.data = FileUtils.toByteArray(data);
        +    }
        +
        +    @Override
        +    public InputStream getSearchableData() {
        +        return null;
        +    }
        +
        +    @Override
        +    public InputStream getVisualization() {
        +        return null;
        +    }
        +
        +    @Override
        +    public Collection getSubElements() {
        +        return this.subElements;
        +    }
        +
        +    public void setSubElements(Collection subElements) {
        +        this.subElements = subElements;
        +    }
        +
        +    public AsdcElement addSubElement(Element element) {
        +        this.subElements.add(element);
        +        return this;
        +    }
        +
        +    public String getType() {
        +        return type;
        +    }
        +
        +    public void setType(String type) {
        +        this.type = type;
        +    }
        +
        +    public String getName() {
        +        return name;
        +    }
        +
        +    public void setName(String name) {
        +        this.name = name;
        +    }
        +
        +    public String getDescription() {
        +        return description;
        +    }
        +
        +    public void setDescription(String description) {
        +        this.description = description;
        +    }
        +
        +    public Map getProperties() {
        +        return properties;
        +    }
        +
        +    public void setProperties(Map properties) {
        +        this.properties = properties;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java
        index 6dad2a8316..895726c08f 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java
        @@ -20,6 +20,5 @@
         package org.openecomp.types;
         
         public enum ElementPropertyName {
        -  elementType,
        -  compositionData
        +    elementType, compositionData
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java
        index 7932902dad..b65051cc52 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java
        @@ -13,84 +13,83 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.zusammen.db;
         
        -import com.amdocs.zusammen.adaptor.inbound.api.types.item.*;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo;
        +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict;
         import com.amdocs.zusammen.commons.health.data.HealthInfo;
         import com.amdocs.zusammen.datatypes.Id;
         import com.amdocs.zusammen.datatypes.SessionContext;
        -import com.amdocs.zusammen.datatypes.item.*;
        +import com.amdocs.zusammen.datatypes.item.ElementContext;
        +import com.amdocs.zusammen.datatypes.item.Info;
        +import com.amdocs.zusammen.datatypes.item.Item;
        +import com.amdocs.zusammen.datatypes.item.ItemVersion;
        +import com.amdocs.zusammen.datatypes.item.ItemVersionData;
        +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus;
        +import com.amdocs.zusammen.datatypes.item.Resolution;
         import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions;
         import com.amdocs.zusammen.datatypes.itemversion.Tag;
        -
         import java.util.Collection;
         
         public interface ZusammenConnector {
         
        -  Collection checkHealth(SessionContext sessionContext);
        -
        -  String getVersion(SessionContext sessionContext);
        -
        -  Collection listItems(SessionContext context);
        +    Collection checkHealth(SessionContext sessionContext);
         
        -  Item getItem(SessionContext context, Id itemId);
        +    String getVersion(SessionContext sessionContext);
         
        -  Id createItem(SessionContext context, Info info);
        +    Collection listItems(SessionContext context);
         
        -  void deleteItem(SessionContext context, Id itemId);
        +    Item getItem(SessionContext context, Id itemId);
         
        -  void updateItem(SessionContext context, Id itemId, Info info);
        +    Id createItem(SessionContext context, Info info);
         
        +    void deleteItem(SessionContext context, Id itemId);
         
        -  Collection listPublicVersions(SessionContext context, Id itemId);
        +    void updateItem(SessionContext context, Id itemId, Info info);
         
        -  ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId);
        +    Collection listPublicVersions(SessionContext context, Id itemId);
         
        -  Id createVersion(SessionContext context, Id itemId, Id baseVersionId,
        -                   ItemVersionData itemVersionData);
        +    ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId);
         
        -  void updateVersion(SessionContext context, Id itemId, Id versionId,
        -                     ItemVersionData itemVersionData);
        +    Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData);
         
        -  ItemVersion getVersion(SessionContext context, Id itemId, Id versionId);
        +    void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData);
         
        -  ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId);
        +    ItemVersion getVersion(SessionContext context, Id itemId, Id versionId);
         
        -  void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag);
        +    ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId);
         
        -  void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId);
        +    void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag);
         
        -  void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId);
        +    void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId);
         
        -  ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId);
        +    void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId);
         
        -  void publishVersion(SessionContext context, Id itemId, Id versionId, String message);
        +    ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId);
         
        -  void syncVersion(SessionContext context, Id itemId, Id versionId);
        +    void publishVersion(SessionContext context, Id itemId, Id versionId, String message);
         
        -  void forceSyncVersion(SessionContext context, Id itemId, Id versionId);
        +    void syncVersion(SessionContext context, Id itemId, Id versionId);
         
        -  void cleanVersion(SessionContext context, Id itemId, Id versionId);
        +    void forceSyncVersion(SessionContext context, Id itemId, Id versionId);
         
        -  ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId);
        +    void cleanVersion(SessionContext context, Id itemId, Id versionId);
         
        +    ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId);
         
        -  Collection listElements(SessionContext context, ElementContext elementContext,
        -                                       Id parentElementId);
        +    Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId);
         
        -  ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId);
        +    ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId);
         
        -  Element getElement(SessionContext context, ElementContext elementContext, Id elementId);
        +    Element getElement(SessionContext context, ElementContext elementContext, Id elementId);
         
        -  ElementConflict getElementConflict(SessionContext context, ElementContext elementContext,
        -                                     Id elementId);
        +    ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, Id elementId);
         
        -  Element saveElement(SessionContext context, ElementContext elementContext,
        -                      Element element, String message);
        +    Element saveElement(SessionContext context, ElementContext elementContext, Element element, String message);
         
        -  void resolveElementConflict(SessionContext context, ElementContext elementContext,
        -                              Element element, Resolution resolution);
        +    void resolveElementConflict(SessionContext context, ElementContext elementContext, Element element, Resolution resolution);
         
        -  void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef);
        +    void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef);
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnectorFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnectorFactory.java
        index 31a8bf598d..4f72386345 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnectorFactory.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnectorFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.zusammen.db;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory;
         
         public abstract class ZusammenConnectorFactory extends AbstractComponentFactory {
         
        -  public static ZusammenConnectorFactory getInstance() {
        -    return AbstractFactory.getInstance(ZusammenConnectorFactory.class);
        -  }
        +    public static ZusammenConnectorFactory getInstance() {
        +        return AbstractFactory.getInstance(ZusammenConnectorFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorFactoryImpl.java
        index e6f9380c2b..d27475f73a 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.zusammen.db.impl;
         
         import com.amdocs.zusammen.adaptor.inbound.api.health.HealthAdaptorFactory;
        @@ -28,13 +27,12 @@ import org.openecomp.core.zusammen.db.ZusammenConnector;
         import org.openecomp.core.zusammen.db.ZusammenConnectorFactory;
         
         public class ZusammenConnectorFactoryImpl extends ZusammenConnectorFactory {
        -  private static final ZusammenConnector INSTANCE =
        -      new ZusammenConnectorImpl(ItemAdaptorFactory.getInstance(),
        -          ItemVersionAdaptorFactory.getInstance(),
        -          ElementAdaptorFactory.getInstance(), HealthAdaptorFactory.getInstance());
         
        -  @Override
        -  public ZusammenConnector createInterface() {
        -    return INSTANCE;
        -  }
        +    private static final ZusammenConnector INSTANCE = new ZusammenConnectorImpl(ItemAdaptorFactory.getInstance(),
        +        ItemVersionAdaptorFactory.getInstance(), ElementAdaptorFactory.getInstance(), HealthAdaptorFactory.getInstance());
        +
        +    @Override
        +    public ZusammenConnector createInterface() {
        +        return INSTANCE;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java
        index 474b7303ab..f604d45287 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java
        @@ -45,364 +45,302 @@ import org.openecomp.sdc.common.errors.SdcRuntimeException;
         
         public class ZusammenConnectorImpl implements ZusammenConnector {
         
        -  private static final String GET_ELEMENT_ERR_MSG =
        -      "Failed to get element. Item Id: %s, version Id: %s, element Id: %s message: %s";
        -  private static final String GET_ELEMENT_IN_REV_ERR_MSG =
        -      "Failed to get element. Item Id: %s, version Id: %s, revision Id: %s, element Id: %s message: %s";
        -  private final ItemAdaptorFactory itemAdaptorFactory;
        -  private final ItemVersionAdaptorFactory versionAdaptorFactory;
        -  private final ElementAdaptorFactory elementAdaptorFactory;
        -  private final HealthAdaptorFactory healthAdaptorFactory;
        -
        -  public ZusammenConnectorImpl(
        -      ItemAdaptorFactory itemAdaptorFactory,
        -      ItemVersionAdaptorFactory versionAdaptorFactory,
        -      ElementAdaptorFactory elementAdaptorFactory,
        -      HealthAdaptorFactory healthAdaptorFactory) {
        -    this.itemAdaptorFactory = itemAdaptorFactory;
        -    this.versionAdaptorFactory = versionAdaptorFactory;
        -    this.elementAdaptorFactory = elementAdaptorFactory;
        -    this.healthAdaptorFactory = healthAdaptorFactory;
        -    CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem();
        -  }
        -
        -  @Override
        -  public Collection checkHealth(SessionContext sessionContext) {
        -    return healthAdaptorFactory.createInterface(sessionContext).getHealthStatus(sessionContext);
        -  }
        -
        -  @Override
        -  public String getVersion(SessionContext sessionContext) {
        -    return healthAdaptorFactory.createInterface(sessionContext).getVersion();
        -  }
        -
        -  @Override
        -  public Collection listItems(SessionContext context) {
        -    Response> response = itemAdaptorFactory.createInterface(context).list(context);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          "Failed to list Items. message:" + response.getReturnCode().toString());
        +    private static final String GET_ELEMENT_ERR_MSG = "Failed to get element. Item Id: %s, version Id: %s, element Id: %s message: %s";
        +    private static final String GET_ELEMENT_IN_REV_ERR_MSG = "Failed to get element. Item Id: %s, version Id: %s, revision Id: %s, element Id: %s message: %s";
        +    private final ItemAdaptorFactory itemAdaptorFactory;
        +    private final ItemVersionAdaptorFactory versionAdaptorFactory;
        +    private final ElementAdaptorFactory elementAdaptorFactory;
        +    private final HealthAdaptorFactory healthAdaptorFactory;
        +
        +    public ZusammenConnectorImpl(ItemAdaptorFactory itemAdaptorFactory, ItemVersionAdaptorFactory versionAdaptorFactory,
        +                                 ElementAdaptorFactory elementAdaptorFactory, HealthAdaptorFactory healthAdaptorFactory) {
        +        this.itemAdaptorFactory = itemAdaptorFactory;
        +        this.versionAdaptorFactory = versionAdaptorFactory;
        +        this.elementAdaptorFactory = elementAdaptorFactory;
        +        this.healthAdaptorFactory = healthAdaptorFactory;
        +        CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem();
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Item getItem(SessionContext context, Id itemId) {
        -    Response response = itemAdaptorFactory.createInterface(context).get(context, itemId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          "Failed to get Item. message:" + response.getReturnCode().toString());
        +
        +    @Override
        +    public Collection checkHealth(SessionContext sessionContext) {
        +        return healthAdaptorFactory.createInterface(sessionContext).getHealthStatus(sessionContext);
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Id createItem(SessionContext context, Info info) {
        -    Response response = itemAdaptorFactory.createInterface(context).create(context, info);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          "Failed to create Item. message:" + response.getReturnCode().toString());
        +
        +    @Override
        +    public String getVersion(SessionContext sessionContext) {
        +        return healthAdaptorFactory.createInterface(sessionContext).getVersion();
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public void deleteItem(SessionContext context, Id itemId){
        -    Response response = itemAdaptorFactory.createInterface(context).delete(context, itemId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          "Failed to delete Item. message:" + response.getReturnCode().toString());
        +
        +    @Override
        +    public Collection listItems(SessionContext context) {
        +        Response> response = itemAdaptorFactory.createInterface(context).list(context);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("Failed to list Items. message:" + response.getReturnCode().toString());
        +        }
        +        return response.getValue();
             }
        -  }
         
        -  @Override
        -  public void updateItem(SessionContext context, Id itemId, Info info) {
        -    Response response =
        -        itemAdaptorFactory.createInterface(context).update(context, itemId, info);
        +    @Override
        +    public Item getItem(SessionContext context, Id itemId) {
        +        Response response = itemAdaptorFactory.createInterface(context).get(context, itemId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("Failed to get Item. message:" + response.getReturnCode().toString());
        +        }
        +        return response.getValue();
        +    }
         
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException("failed to update Item . ItemId:" + itemId + "" +
        -          " message:" + response.getReturnCode().toString());
        +    @Override
        +    public Id createItem(SessionContext context, Info info) {
        +        Response response = itemAdaptorFactory.createInterface(context).create(context, info);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("Failed to create Item. message:" + response.getReturnCode().toString());
        +        }
        +        return response.getValue();
             }
        -  }
        -
        -  @Override
        -  public Collection listPublicVersions(SessionContext context, Id itemId) {
        -    Response> versions =
        -        versionAdaptorFactory.createInterface(context).list(context, Space.PUBLIC, itemId);
        -    if (!versions.isSuccessful()) {
        -      throw new SdcRuntimeException("failed to list public versions. message: " +
        -              versions.getReturnCode().toString());
        +
        +    @Override
        +    public void deleteItem(SessionContext context, Id itemId) {
        +        Response response = itemAdaptorFactory.createInterface(context).delete(context, itemId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("Failed to delete Item. message:" + response.getReturnCode().toString());
        +        }
             }
        -    return versions.getValue();
        -  }
        -
        -  @Override
        -  public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .get(context, Space.PUBLIC, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          String.format("failed to get public Item Version. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void updateItem(SessionContext context, Id itemId, Info info) {
        +        Response response = itemAdaptorFactory.createInterface(context).update(context, itemId, info);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("failed to update Item . ItemId:" + itemId + "" + " message:" + response.getReturnCode().toString());
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Id createVersion(SessionContext context, Id itemId, Id baseVersionId,
        -                          ItemVersionData itemVersionData) {
        -    Response response = versionAdaptorFactory.createInterface(context).create(context, itemId,
        -        baseVersionId, itemVersionData);
        -    if (response.isSuccessful()) {
        -      return response.getValue();
        -    } else {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to create Item Version. ItemId: %s, base versionId: %s, message: %s",
        -          itemId.getValue(), baseVersionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public Collection listPublicVersions(SessionContext context, Id itemId) {
        +        Response> versions = versionAdaptorFactory.createInterface(context).list(context, Space.PUBLIC, itemId);
        +        if (!versions.isSuccessful()) {
        +            throw new SdcRuntimeException("failed to list public versions. message: " + versions.getReturnCode().toString());
        +        }
        +        return versions.getValue();
             }
        -  }
        -
        -  @Override
        -  public void updateVersion(SessionContext context, Id itemId, Id versionId,
        -                            ItemVersionData itemVersionData) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .update(context, itemId, versionId, itemVersionData);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          String.format("failed to update Item Version. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).get(context, Space.PUBLIC, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to get public Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -  }
        -
        -  @Override
        -  public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .get(context, Space.PRIVATE, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          String.format("failed to get Item Version. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData) {
        +        Response response = versionAdaptorFactory.createInterface(context).create(context, itemId, baseVersionId, itemVersionData);
        +        if (response.isSuccessful()) {
        +            return response.getValue();
        +        } else {
        +            throw new SdcRuntimeException(String
        +                .format("failed to create Item Version. ItemId: %s, base versionId: %s, message: %s", itemId.getValue(), baseVersionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context).getStatus(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          String.format("failed to get Item Version status. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) {
        +        Response response = versionAdaptorFactory.createInterface(context).update(context, itemId, versionId, itemVersionData);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to update Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .tag(context, itemId, versionId, null, tag);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to tag Item Version with tag %s. ItemId: %s, versionId: %s, message: %s",
        -          tag.getName(), itemId.getValue(), versionId.getValue(),
        -          response.getReturnCode().toString()));
        +
        +    @Override
        +    public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).get(context, Space.PRIVATE, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to get Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -  }
        -
        -  @Override
        -  public void resetVersionRevision(SessionContext context, Id itemId, Id versionId,
        -                                   Id revisionId) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .resetRevision(context, itemId, versionId, revisionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to reset Item Version back to revision: %s. ItemId: %s, versionId: %s, message:" +
        -              " %s",
        -          revisionId.getValue(), itemId.getValue(), versionId.getValue(),
        -          response.getReturnCode().toString()));
        +
        +    @Override
        +    public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).getStatus(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to get Item Version status. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -  }
        -
        -  @Override
        -  public void revertVersionRevision(SessionContext context, Id itemId, Id versionId,
        -                                    Id revisionId) {
        -    Response response = versionAdaptorFactory.createInterface(context)
        -        .revertRevision(context, itemId, versionId, revisionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to revert Item Version back to revision: %s. ItemId: %s, versionId: %s, " +
        -              "message: %s",
        -          revisionId.getValue(), itemId.getValue(), versionId.getValue(),
        -          response.getReturnCode().toString()));
        +
        +    @Override
        +    public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) {
        +        Response response = versionAdaptorFactory.createInterface(context).tag(context, itemId, versionId, null, tag);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to tag Item Version with tag %s. ItemId: %s, versionId: %s, message: %s", tag.getName(), itemId.getValue(),
        +                    versionId.getValue(), response.getReturnCode().toString()));
        +        }
             }
        -  }
        -
        -  @Override
        -  public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId,
        -                                                   Id versionId) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context)
        -            .listRevisions(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to list revisions of Item Version. ItemId: %s, versionId: %s, message: %s",
        -          itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).resetRevision(context, itemId, versionId, revisionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to reset Item Version back to revision: %s. ItemId: %s, versionId: %s, message:" + " %s", revisionId.getValue(),
        +                    itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -
        -  @Override
        -  public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context).publish(context, itemId, versionId, message);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to publish item Version. ItemId: %s, versionId: %s, message: %s",
        -          itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).revertRevision(context, itemId, versionId, revisionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to revert Item Version back to revision: %s. ItemId: %s, versionId: %s, " + "message: %s", revisionId.getValue(),
        +                    itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +        }
             }
        -  }
        -
        -  @Override
        -  public void syncVersion(SessionContext context, Id itemId, Id versionId) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context).sync(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to sync item Version. ItemId: %s, versionId: %s, message: %s",
        -          itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).listRevisions(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to list revisions of Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -  }
        -
        -  @Override
        -  public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context).forceSync(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "failed to force sync item Version. ItemId: %s, versionId: %s, message: %s",
        -          itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) {
        +        Response response = versionAdaptorFactory.createInterface(context).publish(context, itemId, versionId, message);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to publish item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
             }
        -  }
        -
        -  @Override
        -  public void cleanVersion(SessionContext context, Id itemId, Id versionId) {
        -    Response response =
        -            versionAdaptorFactory.createInterface(context).delete(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -              "failed to clean item Version. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void syncVersion(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).sync(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to sync item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
             }
        -  }
        -
        -  @Override
        -  public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) {
        -    Response response =
        -        versionAdaptorFactory.createInterface(context).getConflict(context, itemId, versionId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String
        -          .format("failed to get Item Version conflict. ItemId: %s, versionId: %s, message: %s",
        -              itemId.getValue(), versionId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).forceSync(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to force sync item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Collection listElements(SessionContext context,
        -                                              ElementContext elementContext,
        -                                              Id parentElementId) {
        -    Response> response = elementAdaptorFactory
        -        .createInterface(context).list(context, elementContext, parentElementId);
        -    if (response.isSuccessful()) {
        -      return response.getValue();
        -    } else {
        -      throw new SdcRuntimeException(response.getReturnCode().toString());
        +
        +    @Override
        +    public void cleanVersion(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).delete(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to clean item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +    }
        +
        +    @Override
        +    public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) {
        +        Response response = versionAdaptorFactory.createInterface(context).getConflict(context, itemId, versionId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("failed to get Item Version conflict. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(),
        +                    response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -  }
         
        +    @Override
        +    public Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId) {
        +        Response> response = elementAdaptorFactory.createInterface(context).list(context, elementContext, parentElementId);
        +        if (response.isSuccessful()) {
        +            return response.getValue();
        +        } else {
        +            throw new SdcRuntimeException(response.getReturnCode().toString());
        +        }
        +    }
         
        -  @Override
        -  public ElementInfo getElementInfo(SessionContext context, ElementContext elementContext,
        -                                    Id elementId) {
        -    Response response =
        -        elementAdaptorFactory.createInterface(context).getInfo(context, elementContext, elementId);
        -    if (!response.isSuccessful()) {
        -      throw buildGetElementException(elementContext, elementId,
        -          response.getReturnCode().toString());
        +    @Override
        +    public ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId) {
        +        Response response = elementAdaptorFactory.createInterface(context).getInfo(context, elementContext, elementId);
        +        if (!response.isSuccessful()) {
        +            throw buildGetElementException(elementContext, elementId, response.getReturnCode().toString());
        +        }
        +        return response.getValue();
        +    }
         
        +    @Override
        +    public Element getElement(SessionContext context, ElementContext elementContext, Id elementId) {
        +        Response response = elementAdaptorFactory.createInterface(context).get(context, elementContext, elementId);
        +        if (!response.isSuccessful()) {
        +            throw buildGetElementException(elementContext, elementId, response.getReturnCode().toString());
        +        }
        +        return response.getValue();
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Element getElement(SessionContext context, ElementContext elementContext,
        -                            Id elementId) {
        -    Response response =
        -        elementAdaptorFactory.createInterface(context).get(context, elementContext, elementId);
        -    if (!response.isSuccessful()) {
        -      throw buildGetElementException(elementContext, elementId,
        -          response.getReturnCode().toString());
        +
        +    @Override
        +    public ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, Id elementId) {
        +        Response response = elementAdaptorFactory.createInterface(context).getConflict(context, elementContext, elementId);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String.format("Failed to get element conflict. Item Id: %s, version Id: %s, element Id: %s message: %s",
        +                elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), elementId.getValue(),
        +                response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public ElementConflict getElementConflict(SessionContext context, ElementContext elementContext,
        -                                            Id elementId) {
        -    Response response = elementAdaptorFactory.createInterface(context)
        -        .getConflict(context, elementContext, elementId);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String.format(
        -          "Failed to get element conflict. Item Id: %s, version Id: %s, element Id: %s message: %s",
        -          elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(),
        -          elementId.getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public Element saveElement(SessionContext context, ElementContext elementContext, Element element, String message) {
        +        Response response = elementAdaptorFactory.createInterface(context).save(context, elementContext, element, message);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException(String
        +                .format("Failed to create element %s. ItemId: %s, versionId: %s, message: %s", element.getElementId().getValue(),
        +                    elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), response.getReturnCode().toString()));
        +        }
        +        return response.getValue();
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public Element saveElement(SessionContext context, ElementContext elementContext, Element element, String message) {
        -    Response response = elementAdaptorFactory.createInterface(context)
        -        .save(context, elementContext, element, message);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(String
        -          .format("Failed to create element %s. ItemId: %s, versionId: %s, message: %s",
        -              element.getElementId().getValue(), elementContext.getItemId().getValue(),
        -              elementContext.getVersionId().getValue(), response.getReturnCode().toString()));
        +
        +    @Override
        +    public void resolveElementConflict(SessionContext context, ElementContext elementContext, Element element, Resolution resolution) {
        +        Response response = elementAdaptorFactory.createInterface(context).resolveConflict(context, elementContext, element, resolution);
        +        if (!response.isSuccessful()) {
        +            throw new SdcRuntimeException("Failed to resolve conflict. message:" + response.getReturnCode().toString());
        +        }
             }
        -    return response.getValue();
        -  }
        -
        -  @Override
        -  public void resolveElementConflict(SessionContext context, ElementContext elementContext, Element element,
        -          Resolution resolution) {
        -    Response response = elementAdaptorFactory.createInterface(context)
        -        .resolveConflict(context, elementContext, element, resolution);
        -    if (!response.isSuccessful()) {
        -      throw new SdcRuntimeException(
        -          "Failed to resolve conflict. message:" + response.getReturnCode().toString());
        +
        +    @Override
        +    public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String revisionId) {
        +        // no-op, required by the interface
             }
        -  }
        -
        -  @Override
        -  public void resetVersionHistory(SessionContext context, Id itemId, Id versionId,
        -                                  String revisionId) {
        -    // no-op, required by the interface
        -  }
        -
        -  private SdcRuntimeException buildGetElementException(ElementContext elementContext, Id elementId,
        -                                                    String zusammenErrorMessage) {
        -    if (elementContext.getRevisionId() == null) {
        -      return new SdcRuntimeException(String.format(GET_ELEMENT_ERR_MSG,
        -          elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(),
        -          elementId.getValue(), zusammenErrorMessage));
        +
        +    private SdcRuntimeException buildGetElementException(ElementContext elementContext, Id elementId, String zusammenErrorMessage) {
        +        if (elementContext.getRevisionId() == null) {
        +            return new SdcRuntimeException(String
        +                .format(GET_ELEMENT_ERR_MSG, elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), elementId.getValue(),
        +                    zusammenErrorMessage));
        +        }
        +        return new SdcRuntimeException(String
        +            .format(GET_ELEMENT_IN_REV_ERR_MSG, elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(),
        +                elementContext.getRevisionId().getValue(), elementId.getValue(), zusammenErrorMessage));
             }
        -    return new SdcRuntimeException(String.format(GET_ELEMENT_IN_REV_ERR_MSG,
        -        elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(),
        -        elementContext.getRevisionId().getValue(),
        -        elementId.getValue(), zusammenErrorMessage));
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/CassandraConnectionInitializer.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/CassandraConnectionInitializer.java
        index 05c7a1a72a..3d4af282b5 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/CassandraConnectionInitializer.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/CassandraConnectionInitializer.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.zusammen.impl;
         
         import java.util.function.Supplier;
        @@ -24,16 +23,14 @@ public class CassandraConnectionInitializer {
         
             private static final String CASSANDRA_PREFIX = "cassandra.";
             private static final String DATA_CENTER_PROPERTY_NAME = CASSANDRA_PREFIX + "datacenter";
        -    private static final String CONSISTENCY_LEVEL_PROPERTY_NAME =
        -            CASSANDRA_PREFIX + "consistency.level";
        +    private static final String CONSISTENCY_LEVEL_PROPERTY_NAME = CASSANDRA_PREFIX + "consistency.level";
             private static final String CASSANDRA_RECONNECT_TIMEOUT = CASSANDRA_PREFIX + "reconnection.delay";
             private static final String NODES_PROPERTY_NAME = CASSANDRA_PREFIX + "nodes";
             private static final String CASSANDRA_PORT_PROPERTY_NAME = CASSANDRA_PREFIX + "port";
             private static final String AUTHENTICATE_PROPERTY_NAME = CASSANDRA_PREFIX + "authenticate";
             private static final String SSL_PROPERTY_NAME = CASSANDRA_PREFIX + "ssl";
             private static final String TRUSTSTORE_PROPERTY_NAME = CASSANDRA_PREFIX + "truststore";
        -    private static final String TRUSTSTORE_PASSWORD_PROPERTY_NAME =
        -            CASSANDRA_PREFIX + "truststore.password";
        +    private static final String TRUSTSTORE_PASSWORD_PROPERTY_NAME = CASSANDRA_PREFIX + "truststore.password";
             private static final String USER_PROPERTY_NAME = CASSANDRA_PREFIX + "user";
             private static final String PASSWORD_PROPERTY_NAME = CASSANDRA_PREFIX + "password";
             private static final String KEYSPACE_PROPERTY_NAME = CASSANDRA_PREFIX + "keyspace";
        @@ -50,8 +47,7 @@ public class CassandraConnectionInitializer {
             private static class DeferredInitializer {
         
                 static {
        -            setSystemProperty(NODES_PROPERTY_NAME, () ->
        -                                                           StringUtils.join(CassandraUtils.getAddresses(), ','));
        +            setSystemProperty(NODES_PROPERTY_NAME, () -> StringUtils.join(CassandraUtils.getAddresses(), ','));
                     setSystemProperty(CASSANDRA_PORT_PROPERTY_NAME, () -> Integer.toString(CassandraUtils.getCassandraPort()));
                     setBooleanSystemProperty(AUTHENTICATE_PROPERTY_NAME, CassandraUtils::isAuthenticate);
                     setBooleanSystemProperty(SSL_PROPERTY_NAME, CassandraUtils::isSsl);
        @@ -61,12 +57,12 @@ public class CassandraConnectionInitializer {
                     setSystemProperty(PASSWORD_PROPERTY_NAME, CassandraUtils::getPassword);
                     setSystemProperty(KEYSPACE_PROPERTY_NAME, () -> ZUSAMMEN);
                     setNullableSystemProperty(DATA_CENTER_PROPERTY_NAME, CassandraUtils::getLocalDataCenter);
        -            setNullableSystemProperty(CONSISTENCY_LEVEL_PROPERTY_NAME,
        -                    CassandraUtils::getConsistencyLevel);
        +            setNullableSystemProperty(CONSISTENCY_LEVEL_PROPERTY_NAME, CassandraUtils::getConsistencyLevel);
                     setSystemProperty(CASSANDRA_RECONNECT_TIMEOUT, () -> Long.toString(CassandraUtils.getReconnectTimeout()));
                 }
         
        -        private DeferredInitializer() { }
        +        private DeferredInitializer() {
        +        }
         
                 @SuppressWarnings("EmptyMethod")
                 static void init() {
        @@ -74,7 +70,6 @@ public class CassandraConnectionInitializer {
                 }
         
                 private static void setSystemProperty(String name, Supplier valueSupplier) {
        -
                     if (System.getProperty(name) == null) {
                         System.setProperty(name, valueSupplier.get());
                     }
        @@ -85,7 +80,6 @@ public class CassandraConnectionInitializer {
                 }
         
                 private static void setNullableSystemProperty(String name, Supplier valueSupplier) {
        -
                     if ((System.getProperty(name) == null) && (valueSupplier.get() != null)) {
                         System.setProperty(name, valueSupplier.get());
                     }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ItemElementLoggerTargetServiceName.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ItemElementLoggerTargetServiceName.java
        index 9ac46fda8b..b93e110768 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ItemElementLoggerTargetServiceName.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ItemElementLoggerTargetServiceName.java
        @@ -21,15 +21,16 @@ import lombok.Getter;
         @Getter
         @AllArgsConstructor
         public enum ItemElementLoggerTargetServiceName {
        -  ITEM_CREATION("Item Creation"),
        -  ITEM_VERSION_CREATION("Item Version Creation"),
        -  ELEMENT_CREATION("Element Creation"),
        -  ELEMENT_UPDATE("Element Update"),
        -  ELEMENT_LIST("Element List"),
        -  ELEMENT_GET("Element Get"),
        -  ELEMENT_GET_BY_PROPERTY("Element Get By Property"),
        -  ITEM_RETRIEVAL("Item retrieval"),
        -  ITEM_VERSION_RETRIEVAL("Item version retrieval)");
        -
        -  private final String description;
        +    // @formatter:off
        +    ITEM_CREATION("Item Creation"),
        +    ITEM_VERSION_CREATION("Item Version Creation"),
        +    ELEMENT_CREATION("Element Creation"),
        +    ELEMENT_UPDATE("Element Update"),
        +    ELEMENT_LIST("Element List"),
        +    ELEMENT_GET("Element Get"),
        +    ELEMENT_GET_BY_PROPERTY("Element Get By Property"),
        +    ITEM_RETRIEVAL("Item retrieval"),
        +    ITEM_VERSION_RETRIEVAL("Item version retrieval)");
        +    // @formatter:on
        +    private final String description;
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorFactoryImpl.java
        index edc1abf108..982f7869fc 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.zusammen.impl;
         
         import org.openecomp.core.zusammen.api.ZusammenAdaptor;
        @@ -25,11 +24,11 @@ import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory;
         import org.openecomp.core.zusammen.db.ZusammenConnectorFactory;
         
         public class ZusammenAdaptorFactoryImpl extends ZusammenAdaptorFactory {
        -  private static final ZusammenAdaptor INSTANCE =
        -      new ZusammenAdaptorImpl(ZusammenConnectorFactory.getInstance().createInterface());
         
        -  @Override
        -  public ZusammenAdaptor createInterface() {
        -    return INSTANCE;
        -  }
        +    private static final ZusammenAdaptor INSTANCE = new ZusammenAdaptorImpl(ZusammenConnectorFactory.getInstance().createInterface());
        +
        +    @Override
        +    public ZusammenAdaptor createInterface() {
        +        return INSTANCE;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java
        index 4efa2486a2..a5d61f4189 100644
        --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java
        +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java
        @@ -43,249 +43,211 @@ import org.openecomp.core.zusammen.db.ZusammenConnector;
         
         public class ZusammenAdaptorImpl implements ZusammenAdaptor {
         
        -  private ZusammenConnector connector;
        -
        -  public ZusammenAdaptorImpl(ZusammenConnector connector) {
        -    this.connector = connector;
        -  }
        -
        -  @Override
        -  public Optional getElementInfo(SessionContext context, ElementContext elementContext,
        -                                              Id elementId) {
        -    return Optional.ofNullable(connector.getElementInfo(context, elementContext, elementId));
        -  }
        -
        -  @Override
        -  public Optional getElement(SessionContext context, ElementContext elementContext,
        -                                      String elementId) {
        -    return Optional.ofNullable(connector.getElement(context, elementContext, new Id(elementId)));
        -  }
        -
        -  @Override
        -  public Optional getElementByName(
        -      SessionContext context, ElementContext elementContext, Id parentElementId,
        -      String elementName) {
        -    Collection elementInfos =
        -        connector.listElements(context, elementContext, parentElementId);
        -    Predicate elementInfoPredicate = elementInfo -> elementInfo.getInfo() != null
        -        && elementName.equals(elementInfo.getInfo().getName());
        -    return getFirstElementInfo(elementInfos, elementInfoPredicate)
        -        .flatMap(elementInfo -> getElement(context, elementContext,
        -            elementInfo.getId().getValue()));
        -  }
        -
        -  @Override
        -  public Collection listElements(SessionContext context, ElementContext elementContext,
        -                                              Id parentElementId) {
        -    return connector.listElements(context, elementContext, parentElementId);
        -  }
        -
        -  @Override
        -  public Collection listElementData(SessionContext context,
        -                                             ElementContext elementContext,
        -                                             Id parentElementId) {
        -    Collection elementInfoList = connector.listElements(context, elementContext,
        -        parentElementId);
        -
        -    return elementInfoList == null
        -        ? new ArrayList<>()
        -        : elementInfoList.stream()
        -            .map(elementInfo -> connector.getElement(context, elementContext, elementInfo.getId()))
        -            .collect(Collectors.toList());
        -  }
        -
        -
        -  @Override
        -  public Collection listElementsByName(
        -      SessionContext context, ElementContext elementContext, Id parentElementId,
        -      String elementName) {
        -    Optional elementInfoByName =
        -        getElementInfoByName(context, elementContext, parentElementId, elementName);
        -
        -    return elementInfoByName.isPresent()
        -        ? connector.listElements(context, elementContext, elementInfoByName.get().getId())
        -        : new ArrayList<>();
        -  }
        -
        -  @Override
        -  public Optional getElementInfoByName(
        -      SessionContext context, ElementContext elementContext, Id parentElementId,
        -      String elementName) {
        -    Collection elementInfos =
        -        connector.listElements(context, elementContext, parentElementId);
        -    return getFirstElementInfo(elementInfos,
        -        elementInfo -> elementInfo.getInfo() != null
        -           && elementName.equals(elementInfo.getInfo().getName()));
        -  }
        -
        -  @Override
        -  public Optional getElementConflict(SessionContext context,
        -                                                      ElementContext elementContext,
        -                                                      Id elementId) {
        -    return Optional.ofNullable(connector.getElementConflict(context, elementContext, elementId));
        -  }
        -
        -  @Override
        -  public Element saveElement(SessionContext context, ElementContext elementContext,
        -                             ZusammenElement element, String message) {
        -    enrichElementHierarchyRec(context, elementContext, null, element);
        -    return connector.saveElement(context, elementContext, element, message);
        -  }
        -
        -  @Override
        -  public void resolveElementConflict(SessionContext context, ElementContext elementContext,
        -                                     ZusammenElement element, Resolution resolution) {
        -    connector.resolveElementConflict(context, elementContext, element, resolution);
        -  }
        -
        -  private void enrichElementHierarchyRec(SessionContext context, ElementContext
        -      elementContext, Id parentElementId, ZusammenElement element) {
        -    if (element.getAction() == Action.CREATE) {
        -      return;
        -    }
        -    locateElementAndUpdateAction(context, elementContext, parentElementId, element);
        -    element.getSubElements().forEach(subElement -> enrichElementHierarchyRec(
        -        context, elementContext, element.getElementId(), (ZusammenElement) subElement));
        -  }
        -
        -  // should be applied only for structural elements
        -  private void locateElementAndUpdateAction(SessionContext context, ElementContext elementContext,
        -                                            Id parentElementId, ZusammenElement element) {
        -    if (element.getElementId() != null) {
        -      return;
        -    }
        -    if (element.getInfo() == null || element.getInfo().getName() == null) {
        -      throw new IllegalArgumentException("When saving element to zusammen - its Id or name must be supplied");
        -    }
        -    Optional elementInfo =
        -        getElementInfoByName(context, elementContext, parentElementId, element.getInfo().getName());
        -    if (elementInfo.isPresent()) {
        -      element.setElementId(elementInfo.get().getId());
        -      if (element.getAction() == null) {
        -        element.setAction(Action.IGNORE);
        -      }
        -    } else {
        -      element.setAction(Action.CREATE);
        -    }
        -  }
        -
        -  private Optional getFirstElementInfo(Collection elementInfos,
        -                                                    Predicate elementInfoPredicate) {
        -    return elementInfos.stream()
        -        .filter(elementInfoPredicate)
        -        .findFirst();
        -  }
        -
        -  @Override
        -  public Collection listItems(SessionContext context) {
        -    return connector.listItems(context);
        -  }
        -
        -  @Override
        -  public Item getItem(SessionContext context, Id itemId) {
        -    return connector.getItem(context, itemId);
        -  }
        -
        -  @Override
        -  public Id createItem(SessionContext context, Info info) {
        -    return connector.createItem(context, info);
        -  }
        -
        -  @Override
        -  public void deleteItem(SessionContext context, Id itemId){
        -    connector.deleteItem(context,itemId);
        -  }
        -
        -  @Override
        -  public void updateItem(SessionContext context, Id itemId, Info info) {
        -    connector.updateItem(context, itemId, info);
        -  }
        -
        -  @Override
        -  public Collection listPublicVersions(SessionContext context, Id itemId) {
        -    return connector.listPublicVersions(context, itemId);
        -  }
        -
        -  @Override
        -  public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) {
        -    return connector.getPublicVersion(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) {
        -    return connector.getVersion(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) {
        -    return connector.getVersionStatus(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) {
        -    return connector.getVersionConflict(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData
        -      itemVersionData) {
        -    return connector.createVersion(context, itemId, baseVersionId, itemVersionData);
        -  }
        -
        -  @Override
        -  public void updateVersion(SessionContext context, Id itemId, Id versionId,
        -                            ItemVersionData itemVersionData) {
        -    connector.updateVersion(context, itemId, versionId, itemVersionData);
        -  }
        -
        -  @Override
        -  public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) {
        -    connector.tagVersion(context, itemId, versionId, tag);
        -  }
        -
        -  @Override
        -  public void resetVersionHistory(SessionContext context, Id itemId, Id versionId,
        -                                  String changeRef) {
        -    connector.resetVersionHistory(context, itemId, versionId, changeRef);
        -  }
        -
        -  @Override
        -  public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) {
        -    connector.publishVersion(context, itemId, versionId, message);
        -  }
        -
        -  @Override
        -  public void syncVersion(SessionContext context, Id itemId, Id versionId) {
        -    connector.syncVersion(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) {
        -    connector.forceSyncVersion(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public void cleanVersion(SessionContext context, Id itemId, Id versionId) {
        -    connector.cleanVersion(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public void revert(SessionContext context, Id itemId, Id versionId, Id revisionId) {
        -    connector.revertVersionRevision(context, itemId, versionId, revisionId);
        -  }
        -
        -  @Override
        -  public ItemVersionRevisions listRevisions(SessionContext context, Id itemId, Id versionId) {
        -    return connector.listVersionRevisions(context, itemId, versionId);
        -  }
        -
        -  @Override
        -  public Collection checkHealth(SessionContext context) {
        -    return connector.checkHealth(context);
        -  }
        -
        -  @Override
        -  public String getVersion(SessionContext context) {
        -    return connector.getVersion(context);
        -  }
        +    private ZusammenConnector connector;
        +
        +    public ZusammenAdaptorImpl(ZusammenConnector connector) {
        +        this.connector = connector;
        +    }
        +
        +    @Override
        +    public Optional getElementInfo(SessionContext context, ElementContext elementContext, Id elementId) {
        +        return Optional.ofNullable(connector.getElementInfo(context, elementContext, elementId));
        +    }
        +
        +    @Override
        +    public Optional getElement(SessionContext context, ElementContext elementContext, String elementId) {
        +        return Optional.ofNullable(connector.getElement(context, elementContext, new Id(elementId)));
        +    }
        +
        +    @Override
        +    public Optional getElementByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName) {
        +        Collection elementInfos = connector.listElements(context, elementContext, parentElementId);
        +        Predicate elementInfoPredicate = elementInfo -> elementInfo.getInfo() != null && elementName
        +            .equals(elementInfo.getInfo().getName());
        +        return getFirstElementInfo(elementInfos, elementInfoPredicate)
        +            .flatMap(elementInfo -> getElement(context, elementContext, elementInfo.getId().getValue()));
        +    }
        +
        +    @Override
        +    public Collection listElements(SessionContext context, ElementContext elementContext, Id parentElementId) {
        +        return connector.listElements(context, elementContext, parentElementId);
        +    }
        +
        +    @Override
        +    public Collection listElementData(SessionContext context, ElementContext elementContext, Id parentElementId) {
        +        Collection elementInfoList = connector.listElements(context, elementContext, parentElementId);
        +        return elementInfoList == null ? new ArrayList<>()
        +            : elementInfoList.stream().map(elementInfo -> connector.getElement(context, elementContext, elementInfo.getId()))
        +                .collect(Collectors.toList());
        +    }
        +
        +    @Override
        +    public Collection listElementsByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName) {
        +        Optional elementInfoByName = getElementInfoByName(context, elementContext, parentElementId, elementName);
        +        return elementInfoByName.isPresent() ? connector.listElements(context, elementContext, elementInfoByName.get().getId()) : new ArrayList<>();
        +    }
        +
        +    @Override
        +    public Optional getElementInfoByName(SessionContext context, ElementContext elementContext, Id parentElementId, String elementName) {
        +        Collection elementInfos = connector.listElements(context, elementContext, parentElementId);
        +        return getFirstElementInfo(elementInfos, elementInfo -> elementInfo.getInfo() != null && elementName.equals(elementInfo.getInfo().getName()));
        +    }
        +
        +    @Override
        +    public Optional getElementConflict(SessionContext context, ElementContext elementContext, Id elementId) {
        +        return Optional.ofNullable(connector.getElementConflict(context, elementContext, elementId));
        +    }
        +
        +    @Override
        +    public Element saveElement(SessionContext context, ElementContext elementContext, ZusammenElement element, String message) {
        +        enrichElementHierarchyRec(context, elementContext, null, element);
        +        return connector.saveElement(context, elementContext, element, message);
        +    }
        +
        +    @Override
        +    public void resolveElementConflict(SessionContext context, ElementContext elementContext, ZusammenElement element, Resolution resolution) {
        +        connector.resolveElementConflict(context, elementContext, element, resolution);
        +    }
        +
        +    private void enrichElementHierarchyRec(SessionContext context, ElementContext elementContext, Id parentElementId, ZusammenElement element) {
        +        if (element.getAction() == Action.CREATE) {
        +            return;
        +        }
        +        locateElementAndUpdateAction(context, elementContext, parentElementId, element);
        +        element.getSubElements()
        +            .forEach(subElement -> enrichElementHierarchyRec(context, elementContext, element.getElementId(), (ZusammenElement) subElement));
        +    }
        +
        +    // should be applied only for structural elements
        +    private void locateElementAndUpdateAction(SessionContext context, ElementContext elementContext, Id parentElementId, ZusammenElement element) {
        +        if (element.getElementId() != null) {
        +            return;
        +        }
        +        if (element.getInfo() == null || element.getInfo().getName() == null) {
        +            throw new IllegalArgumentException("When saving element to zusammen - its Id or name must be supplied");
        +        }
        +        Optional elementInfo = getElementInfoByName(context, elementContext, parentElementId, element.getInfo().getName());
        +        if (elementInfo.isPresent()) {
        +            element.setElementId(elementInfo.get().getId());
        +            if (element.getAction() == null) {
        +                element.setAction(Action.IGNORE);
        +            }
        +        } else {
        +            element.setAction(Action.CREATE);
        +        }
        +    }
        +
        +    private Optional getFirstElementInfo(Collection elementInfos, Predicate elementInfoPredicate) {
        +        return elementInfos.stream().filter(elementInfoPredicate).findFirst();
        +    }
        +
        +    @Override
        +    public Collection listItems(SessionContext context) {
        +        return connector.listItems(context);
        +    }
        +
        +    @Override
        +    public Item getItem(SessionContext context, Id itemId) {
        +        return connector.getItem(context, itemId);
        +    }
        +
        +    @Override
        +    public Id createItem(SessionContext context, Info info) {
        +        return connector.createItem(context, info);
        +    }
        +
        +    @Override
        +    public void deleteItem(SessionContext context, Id itemId) {
        +        connector.deleteItem(context, itemId);
        +    }
        +
        +    @Override
        +    public void updateItem(SessionContext context, Id itemId, Info info) {
        +        connector.updateItem(context, itemId, info);
        +    }
        +
        +    @Override
        +    public Collection listPublicVersions(SessionContext context, Id itemId) {
        +        return connector.listPublicVersions(context, itemId);
        +    }
        +
        +    @Override
        +    public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) {
        +        return connector.getPublicVersion(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) {
        +        return connector.getVersion(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) {
        +        return connector.getVersionStatus(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) {
        +        return connector.getVersionConflict(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData) {
        +        return connector.createVersion(context, itemId, baseVersionId, itemVersionData);
        +    }
        +
        +    @Override
        +    public void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) {
        +        connector.updateVersion(context, itemId, versionId, itemVersionData);
        +    }
        +
        +    @Override
        +    public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) {
        +        connector.tagVersion(context, itemId, versionId, tag);
        +    }
        +
        +    @Override
        +    public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef) {
        +        connector.resetVersionHistory(context, itemId, versionId, changeRef);
        +    }
        +
        +    @Override
        +    public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) {
        +        connector.publishVersion(context, itemId, versionId, message);
        +    }
        +
        +    @Override
        +    public void syncVersion(SessionContext context, Id itemId, Id versionId) {
        +        connector.syncVersion(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) {
        +        connector.forceSyncVersion(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public void cleanVersion(SessionContext context, Id itemId, Id versionId) {
        +        connector.cleanVersion(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public void revert(SessionContext context, Id itemId, Id versionId, Id revisionId) {
        +        connector.revertVersionRevision(context, itemId, versionId, revisionId);
        +    }
        +
        +    @Override
        +    public ItemVersionRevisions listRevisions(SessionContext context, Id itemId, Id versionId) {
        +        return connector.listVersionRevisions(context, itemId, versionId);
        +    }
        +
        +    @Override
        +    public Collection checkHealth(SessionContext context) {
        +        return connector.checkHealth(context);
        +    }
        +
        +    @Override
        +    public String getVersion(SessionContext context) {
        +        return connector.getVersion(context);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java
        index 38d7d84ce7..ed63a29913 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,22 +17,19 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.api;
         
        +import java.util.Optional;
         import org.openecomp.sdc.datatypes.model.ItemType;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.Optional;
        -
         /**
          * Created by Talio on 11/29/2016.
          */
         public interface HealingManager {
         
        -  /**
        -   * @return healed version, if healing was not performed - Optional.empty.
        -   */
        -  Optional healItemVersion(String itemId, Version version, ItemType itemType,
        -                                    boolean force);
        +    /**
        +     * @return healed version, if healing was not performed - Optional.empty.
        +     */
        +    Optional healItemVersion(String itemId, Version version, ItemType itemType, boolean force);
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java
        index 9ea6a53b2c..b8c1f27b1d 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.dao;
         
         import java.util.Optional;
        @@ -27,7 +26,7 @@ import java.util.Optional;
          */
         public interface HealingDao {
         
        -  Optional getItemHealingFlag(String space, String itemId, String versionId);
        +    Optional getItemHealingFlag(String space, String itemId, String versionId);
         
        -  void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, String versionId);
        +    void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, String versionId);
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java
        index 5e375ee046..e76f2d1580 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.factory;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        @@ -28,7 +27,8 @@ import org.openecomp.sdc.healing.api.HealingManager;
          * Created by Talio on 11/29/2016.
          */
         public abstract class HealingManagerFactory extends AbstractComponentFactory {
        -    public static HealingManagerFactory getInstance(){
        +
        +    public static HealingManagerFactory getInstance() {
                 return AbstractFactory.getInstance(HealingManagerFactory.class);
             }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java
        index 46ed591f8c..97fe393fd1 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java
        @@ -13,14 +13,13 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.healing.interfaces;
         
         import org.openecomp.sdc.versioning.dao.types.Version;
         
         public interface Healer {
         
        -  boolean isHealingNeeded(String itemId, Version version);
        +    boolean isHealingNeeded(String itemId, Version version);
         
        -  void heal(String itemId, Version version) throws Exception;
        +    void heal(String itemId, Version version) throws Exception;
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java
        index becf7b8ae8..b6889d17e2 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.types;
         
         public class ConfigConstants {
        -  public static final String HEALING_NAMESPACE = "healing";
        +
        +    public static final String HEALING_NAMESPACE = "healing";
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java
        index 420d75621f..fb9f795817 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,15 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.types;
         
         /**
          * Created by Talio on 11/29/2016.
          */
         public enum HealCode {
        -  FILE_DATA_STRUCTURE_HEALER,
        -  QUESTIONNAIRE_HEALER,
        -  COMPOSITION_DATA_HEALER,
        -  SUB_ENTITIES_QUESTIONNAIRE_HEALER;
        +    FILE_DATA_STRUCTURE_HEALER, QUESTIONNAIRE_HEALER, COMPOSITION_DATA_HEALER, SUB_ENTITIES_QUESTIONNAIRE_HEALER;
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java
        index 2e1093e0ab..2f62a5cacd 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,8 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.types;
         
         public enum HealerType {
        -  data,
        -  structure
        +    data, structure
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java
        index d813c41448..0e60932392 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,50 +17,42 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.dao.impl;
         
         import com.datastax.driver.core.ResultSet;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        +import java.util.Optional;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         import org.openecomp.sdc.healing.dao.HealingDao;
         
        -import java.util.Optional;
        -
         /**
          * Created by ayalaben on 10/17/2017
          */
         public class HealingDaoImpl implements HealingDao {
         
        -  private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        -  private static HealingAccessor accessor =
        -      noSqlDb.getMappingManager().createAccessor(HealingAccessor.class);
        -
        -  @Override
        -  public Optional getItemHealingFlag(String space, String itemId, String versionId) {
        -    ResultSet result = accessor.getItemHealingFlag(space, itemId, versionId);
        -    return result.getAvailableWithoutFetching() < 1
        -        ? Optional.empty()
        -        : Optional.of(result.one().getBool("healing_needed"));
        -  }
        -
        -  @Override
        -  public void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId,
        -                                 String versionId) {
        -    accessor.setItemHealingFlag(healingNeededFlag, space, itemId, versionId);
        -  }
        +    private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        +    private static HealingAccessor accessor = noSqlDb.getMappingManager().createAccessor(HealingAccessor.class);
         
        +    @Override
        +    public Optional getItemHealingFlag(String space, String itemId, String versionId) {
        +        ResultSet result = accessor.getItemHealingFlag(space, itemId, versionId);
        +        return result.getAvailableWithoutFetching() < 1 ? Optional.empty() : Optional.of(result.one().getBool("healing_needed"));
        +    }
         
        -  @Accessor
        -  interface HealingAccessor {
        +    @Override
        +    public void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, String versionId) {
        +        accessor.setItemHealingFlag(healingNeededFlag, space, itemId, versionId);
        +    }
         
        -    @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?")
        -    ResultSet getItemHealingFlag(String space, String itemId, String versionId);
        +    @Accessor
        +    interface HealingAccessor {
         
        -    @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?")
        -    void setItemHealingFlag(boolean flag, String space, String itemId, String versionId);
        +        @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?")
        +        ResultSet getItemHealingFlag(String space, String itemId, String versionId);
         
        -  }
        +        @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?")
        +        void setItemHealingFlag(boolean flag, String space, String itemId, String versionId);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java
        index 5a283f954b..9fff4f4698 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.impl;
         
         import org.openecomp.sdc.healing.api.HealingManager;
        @@ -29,9 +28,9 @@ import org.openecomp.sdc.versioning.VersioningManagerFactory;
          * Created by Talio on 11/29/2016.
          */
         public class HealingManagerFactoryImpl extends HealingManagerFactory {
        +
             @Override
             public HealingManager createInterface() {
        -        return new HealingManagerImpl(
        -            VersioningManagerFactory.getInstance().createInterface(), new HealingDaoImpl());
        +        return new HealingManagerImpl(VersioningManagerFactory.getInstance().createInterface(), new HealingDaoImpl());
             }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java
        index fa9c6d1cdf..4478c00a63 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java
        @@ -17,10 +17,17 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.impl;
         
        -
        +import java.util.Collection;
        +import java.util.Collections;
        +import java.util.LinkedList;
        +import java.util.List;
        +import java.util.Map;
        +import java.util.Objects;
        +import java.util.Optional;
        +import java.util.stream.Collectors;
        +import java.util.stream.Stream;
         import org.openecomp.core.utilities.CommonMethods;
         import org.openecomp.core.utilities.file.FileUtils;
         import org.openecomp.core.utilities.json.JsonUtil;
        @@ -39,235 +46,178 @@ import org.openecomp.sdc.versioning.dao.types.Version;
         import org.openecomp.sdc.versioning.dao.types.VersionStatus;
         import org.openecomp.sdc.versioning.types.VersionCreationMethod;
         
        -import java.util.*;
        -import java.util.stream.Collectors;
        -import java.util.stream.Stream;
        -
         public class HealingManagerImpl implements HealingManager {
         
        -  private static final String HEALERS_BY_ENTITY_TYPE_FILE = "entityHealingConfiguration.json";
        -  private static final String HEALING_USER_SUFFIX = "_healer";
        -  private static final String PUBLIC_USER = "public";
        -
        -  private HealingDao healingDao;
        -  private VersioningManager versioningManager;
        +    private static final String HEALERS_BY_ENTITY_TYPE_FILE = "entityHealingConfiguration.json";
        +    private static final String HEALING_USER_SUFFIX = "_healer";
        +    private static final String PUBLIC_USER = "public";
        +    private HealingDao healingDao;
        +    private VersioningManager versioningManager;
         
        -  public HealingManagerImpl(VersioningManager versioningManager, HealingDao healingDao) {
        -    this.versioningManager = versioningManager;
        -    this.healingDao = healingDao;
        -  }
        -
        -  @Override
        -  public Optional healItemVersion(final String itemId, final Version version,
        -                                           final ItemType itemType, final boolean force) {
        -    String user = getUser();
        -    populateVersionInfo(itemId, version);
        -
        -    if (!isHealingNeeded(itemId, version, force, user)) {
        -      return Optional.empty();
        +    public HealingManagerImpl(VersioningManager versioningManager, HealingDao healingDao) {
        +        this.versioningManager = versioningManager;
        +        this.healingDao = healingDao;
             }
         
        -    Map> healersByType = getItemHealers(itemType);
        -    List failureMessages = new LinkedList<>();
        -    List structureHealersToRun =
        -        getHealersToRun(healersByType.get(HealerType.structure.name()), itemId, version,
        -            failureMessages);
        -    List dataHealersToRun =
        -        getHealersToRun(healersByType.get(HealerType.data.name()), itemId, version,
        -            failureMessages);
        -
        -    if (structureHealersToRun.isEmpty() && dataHealersToRun.isEmpty()) {
        -      markAsHealed(itemId, version.getId(), user);
        -      markAsHealed(itemId, version.getId(), PUBLIC_USER);
        -      return Optional.empty();
        +    @Override
        +    public Optional healItemVersion(final String itemId, final Version version, final ItemType itemType, final boolean force) {
        +        String user = getUser();
        +        populateVersionInfo(itemId, version);
        +        if (!isHealingNeeded(itemId, version, force, user)) {
        +            return Optional.empty();
        +        }
        +        Map> healersByType = getItemHealers(itemType);
        +        List failureMessages = new LinkedList<>();
        +        List structureHealersToRun = getHealersToRun(healersByType.get(HealerType.structure.name()), itemId, version, failureMessages);
        +        List dataHealersToRun = getHealersToRun(healersByType.get(HealerType.data.name()), itemId, version, failureMessages);
        +        if (structureHealersToRun.isEmpty() && dataHealersToRun.isEmpty()) {
        +            markAsHealed(itemId, version.getId(), user);
        +            markAsHealed(itemId, version.getId(), PUBLIC_USER);
        +            return Optional.empty();
        +        }
        +        Optional healVersion = getHealVersion(itemId, version);
        +        if (!healVersion.isPresent()) {
        +            // do NOT turn off flag here (in thought of saving version calculate performance next
        +
        +            // time) because maybe next time the next version will be available (due to deletion of
        +
        +            // the taken one)
        +            return Optional.empty();
        +        }
        +        failureMessages.addAll(doHeal(itemId, healVersion.get(), version, structureHealersToRun, dataHealersToRun, user, force));
        +        handleFailures(failureMessages);
        +        return healVersion;
             }
         
        -    Optional healVersion = getHealVersion(itemId, version);
        -    if (!healVersion.isPresent()) {
        -      // do NOT turn off flag here (in thought of saving version calculate performance next
        -      // time) because maybe next time the next version will be available (due to deletion of
        -      // the taken one)
        -      return Optional.empty();
        +    private void populateVersionInfo(String itemId, Version version) {
        +        if (version.getStatus() != null) {
        +            return;
        +        }
        +        Version retrievedVersion = versioningManager.get(itemId, version);
        +        version.setStatus(retrievedVersion.getStatus());
        +        version.setBaseId(retrievedVersion.getBaseId());
             }
         
        -    failureMessages.addAll(
        -        doHeal(itemId, healVersion.get(), version, structureHealersToRun, dataHealersToRun, user,
        -            force));
        -    handleFailures(failureMessages);
        -
        -    return healVersion;
        -  }
        -
        -  private void populateVersionInfo(String itemId, Version version) {
        -    if (version.getStatus() != null) {
        -      return;
        +    private boolean isHealingNeeded(String itemId, Version version, boolean force, String user) {
        +        return force || isHealingFlagOn(itemId, version.getId(), user).orElse(isHealingFlagOn(itemId, version.getId(), PUBLIC_USER).orElse(
        +            version.getStatus() == VersionStatus.Draft && version.getBaseId() != null && isHealingFlagOn(itemId, version.getBaseId(), user)
        +                .orElse(isHealingFlagOn(itemId, version.getBaseId(), PUBLIC_USER).orElse(false))));
             }
         
        -    Version retrievedVersion = versioningManager.get(itemId, version);
        -    version.setStatus(retrievedVersion.getStatus());
        -    version.setBaseId(retrievedVersion.getBaseId());
        -  }
        -
        -  private boolean isHealingNeeded(String itemId, Version version, boolean force, String user) {
        -    return force || isHealingFlagOn(itemId, version.getId(), user)
        -        .orElse(isHealingFlagOn(itemId, version.getId(), PUBLIC_USER)
        -            .orElse(version.getStatus() == VersionStatus.Draft && version.getBaseId() != null &&
        -                isHealingFlagOn(itemId, version.getBaseId(), user)
        -                    .orElse(isHealingFlagOn(itemId, version.getBaseId(), PUBLIC_USER)
        -                        .orElse(false))));
        -  }
        -
        -  private Optional getHealVersion(String itemId, Version version) {
        -    return version.getStatus() == VersionStatus.Certified
        -        ? createNewVersion(itemId, version.getId())
        -        : Optional.of(version);
        -  }
        -
        -  private Optional createNewVersion(String itemId, String versionId) {
        -    Version newVersion = new Version();
        -    newVersion.setBaseId(versionId);
        -    newVersion.setDescription("Version is created by healing process");
        -    try {
        -      return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major));
        -    } catch (Exception e) {
        -      return Optional.empty();
        +    private Optional getHealVersion(String itemId, Version version) {
        +        return version.getStatus() == VersionStatus.Certified ? createNewVersion(itemId, version.getId()) : Optional.of(version);
             }
        -  }
         
        -  private List doHeal(String itemId, Version version, Version origVersion,
        -                              List structureHealersToRun,
        -                              List dataHealersToRun, String user,
        -                              boolean force) {
        -    boolean publicFlagOn = isHealingFlagOn(itemId, origVersion.getId(), PUBLIC_USER)
        -        .orElse(origVersion.getBaseId() != null &&
        -            isHealingFlagOn(itemId, origVersion.getBaseId(), PUBLIC_USER).orElse(false));
        +    private Optional createNewVersion(String itemId, String versionId) {
        +        Version newVersion = new Version();
        +        newVersion.setBaseId(versionId);
        +        newVersion.setDescription("Version is created by healing process");
        +        try {
        +            return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major));
        +        } catch (Exception e) {
        +            return Optional.empty();
        +        }
        +    }
         
        -    List failureMessages =
        -        force || origVersion.getStatus() == VersionStatus.Certified || publicFlagOn
        -            ? healPublic(itemId, version, origVersion, structureHealersToRun, dataHealersToRun,
        -            user)
        -            : new LinkedList<>();
        +    private List doHeal(String itemId, Version version, Version origVersion, List structureHealersToRun,
        +                                List dataHealersToRun, String user, boolean force) {
        +        boolean publicFlagOn = isHealingFlagOn(itemId, origVersion.getId(), PUBLIC_USER)
        +            .orElse(origVersion.getBaseId() != null && isHealingFlagOn(itemId, origVersion.getBaseId(), PUBLIC_USER).orElse(false));
        +        List failureMessages =
        +            force || origVersion.getStatus() == VersionStatus.Certified || publicFlagOn ? healPublic(itemId, version, origVersion,
        +                structureHealersToRun, dataHealersToRun, user) : new LinkedList<>();
        +        failureMessages.addAll(healPrivate(itemId, version, origVersion, structureHealersToRun, dataHealersToRun, user));
        +        return failureMessages;
        +    }
         
        -    failureMessages.addAll(
        -        healPrivate(itemId, version, origVersion, structureHealersToRun, dataHealersToRun, user));
        +    private List healPrivate(String itemId, Version version, Version origVersion, List structureHealersToRun,
        +                                     List dataHealersToRun, String user) {
        +        List failureMessages;
        +        if (origVersion.getStatus() == VersionStatus.Certified) {
        +            failureMessages = executeHealers(itemId, version,
        +                Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()).collect(Collectors.toList()));
        +        } else {
        +            if (structureHealersToRun.isEmpty()) {
        +                failureMessages = executeHealers(itemId, version, dataHealersToRun);
        +            } else {
        +                versioningManager.forceSync(itemId, version);
        +                failureMessages = new LinkedList<>();
        +            }
        +        }
        +        markAsHealed(itemId, origVersion.getId(), user);
        +        return failureMessages;
        +    }
         
        -    return failureMessages;
        -  }
        +    private List healPublic(String itemId, Version version, Version origVersion, List structureHealersToRun,
        +                                    List dataHealersToRun, String user) {
        +        List failureMessages = origVersion.getStatus() == VersionStatus.Certified ? new LinkedList<>()
        +            : healPublic(itemId, version, Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()).collect(Collectors.toList()),
        +                user);
        +        markAsHealed(itemId, origVersion.getId(), PUBLIC_USER);
        +        return failureMessages;
        +    }
         
        -  private List healPrivate(String itemId, Version version, Version origVersion,
        -                                   List structureHealersToRun,
        -                                   List dataHealersToRun, String user) {
        -    List failureMessages;
        -    if (origVersion.getStatus() == VersionStatus.Certified) {
        -      failureMessages = executeHealers(itemId, version,
        -          Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream())
        -              .collect(Collectors.toList()));
        -    } else {
        -      if (structureHealersToRun.isEmpty()) {
        -        failureMessages = executeHealers(itemId, version, dataHealersToRun);
        -      } else {
        +    private List healPublic(String itemId, Version version, List healers, String user) {
        +        String tenant = SessionContextProviderFactory.getInstance().createInterface().get().getTenant();
        +        SessionContextProviderFactory.getInstance().createInterface().create(user + HEALING_USER_SUFFIX, tenant);
                 versioningManager.forceSync(itemId, version);
        -        failureMessages = new LinkedList<>();
        -      }
        +        List failureMessages = executeHealers(itemId, version, healers);
        +        Version publicVersion = versioningManager.get(itemId, version);
        +        if (Objects.nonNull(publicVersion.getState()) && publicVersion.getState().isDirty()) {
        +            versioningManager.publish(itemId, version, "Healing vsp");
        +        }
        +        SessionContextProviderFactory.getInstance().createInterface().create(user, tenant);
        +        return failureMessages;
             }
        -    markAsHealed(itemId, origVersion.getId(), user);
        -    return failureMessages;
        -  }
        -
        -  private List healPublic(String itemId, Version version, Version origVersion,
        -                                  List structureHealersToRun,
        -                                  List dataHealersToRun, String user) {
        -    List failureMessages = origVersion.getStatus() == VersionStatus.Certified
        -        ? new LinkedList<>()
        -        : healPublic(itemId, version,
        -            Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream())
        -                .collect(Collectors.toList()), user);
        -
        -    markAsHealed(itemId, origVersion.getId(), PUBLIC_USER);
        -    return failureMessages;
        -  }
        -
        -  private List healPublic(String itemId, Version version, List healers,
        -                                  String user) {
        -    String tenant = SessionContextProviderFactory.getInstance().createInterface().get().getTenant();
        -    SessionContextProviderFactory.getInstance().createInterface()
        -        .create(user + HEALING_USER_SUFFIX, tenant);
        -
        -    versioningManager.forceSync(itemId, version);
         
        -    List failureMessages = executeHealers(itemId, version, healers);
        -    Version publicVersion = versioningManager.get(itemId, version);
        -
        -    if (Objects.nonNull(publicVersion.getState()) && publicVersion.getState().isDirty()) {
        -      versioningManager.publish(itemId, version, "Healing vsp");
        +    private List executeHealers(String itemId, Version version, List healers) {
        +        List failureMessages = new LinkedList<>();
        +        for (Healer healer : healers) {
        +            try {
        +                healer.heal(itemId, version);
        +            } catch (Exception e) {
        +                failureMessages.add(String.format("Failure in healer %s: %s", healer.getClass().getName(), e.getMessage()));
        +            }
        +        }
        +        return failureMessages;
             }
         
        -    SessionContextProviderFactory.getInstance().createInterface().create(user, tenant);
        -    return failureMessages;
        -  }
        -
        -  private List executeHealers(String itemId, Version version, List healers) {
        -    List failureMessages = new LinkedList<>();
        -    for (Healer healer : healers) {
        -      try {
        -        healer.heal(itemId, version);
        -      } catch (Exception e) {
        -        failureMessages.add(
        -            String.format("Failure in healer %s: %s", healer.getClass().getName(), e.getMessage()));
        -      }
        +    private Optional isHealingFlagOn(String itemId, String version, String user) {
        +        return healingDao.getItemHealingFlag(user, itemId, version);
             }
         
        -    return failureMessages;
        -  }
        -
        -  private Optional isHealingFlagOn(String itemId, String version, String user) {
        -    return healingDao.getItemHealingFlag(user, itemId, version);
        -  }
        -
        -  private void markAsHealed(String itemId, String versionId, String user) {
        -    healingDao.setItemHealingFlag(false, user, itemId, versionId);
        -  }
        +    private void markAsHealed(String itemId, String versionId, String user) {
        +        healingDao.setItemHealingFlag(false, user, itemId, versionId);
        +    }
         
        -  private void handleFailures(List failureMessages) {
        -    if (!failureMessages.isEmpty()) {
        -      throw new CoreException(new ErrorCode.ErrorCodeBuilder()
        -          .withCategory(ErrorCategory.APPLICATION)
        -          .withMessage(CommonMethods.listToSeparatedString(failureMessages, '\n')).build());
        +    private void handleFailures(List failureMessages) {
        +        if (!failureMessages.isEmpty()) {
        +            throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION)
        +                .withMessage(CommonMethods.listToSeparatedString(failureMessages, '\n')).build());
        +        }
             }
        -  }
         
        -  private List getHealersToRun(Collection healersClassNames, String itemId,
        -                                       Version version, List failureMessages) {
        -    return healersClassNames == null
        -        ? Collections.emptyList()
        -        : healersClassNames.stream()
        -            .map(healerClassName -> getHealerInstance(healerClassName, failureMessages))
        -            .filter(Optional::isPresent)
        -            .map(Optional::get)
        -            .filter(healer -> healer.isHealingNeeded(itemId, version))
        -            .collect(Collectors.toList());
        -  }
        +    private List getHealersToRun(Collection healersClassNames, String itemId, Version version, List failureMessages) {
        +        return healersClassNames == null ? Collections.emptyList()
        +            : healersClassNames.stream().map(healerClassName -> getHealerInstance(healerClassName, failureMessages)).filter(Optional::isPresent)
        +                .map(Optional::get).filter(healer -> healer.isHealingNeeded(itemId, version)).collect(Collectors.toList());
        +    }
         
        -  private Optional getHealerInstance(String healerClassName, List failureMessages) {
        -    try {
        -      return Optional.of((Healer) Class.forName(healerClassName).getConstructor().newInstance());
        -    } catch (Exception e) {
        -      failureMessages
        -          .add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), healerClassName));
        -      return Optional.empty();
        +    private Optional getHealerInstance(String healerClassName, List failureMessages) {
        +        try {
        +            return Optional.of((Healer) Class.forName(healerClassName).getConstructor().newInstance());
        +        } catch (Exception e) {
        +            failureMessages.add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), healerClassName));
        +            return Optional.empty();
        +        }
             }
        -  }
         
        -  private Map> getItemHealers(ItemType itemType) {
        -    Map healingConfig = FileUtils
        -        .readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE,
        -            stream -> JsonUtil.json2Object(stream, Map.class));
        -    return (Map>) healingConfig
        -        .getOrDefault(itemType.name(), Collections.emptyMap());
        -  }
        +    private Map> getItemHealers(ItemType itemType) {
        +        Map healingConfig = FileUtils.readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
        +        return (Map>) healingConfig.getOrDefault(itemType.name(), Collections.emptyMap());
        +    }
         
        -  private String getUser() {
        -    return SessionContextProviderFactory.getInstance().createInterface().get().getUser()
        -        .getUserId();
        -  }
        +    private String getUser() {
        +        return SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java
        index 7767277444..2cfa874d28 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,11 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.utils;
         
         /**
          * Created by Talio on 11/29/2016.
          */
         public class HealingConfiguration {
        +
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java
        index e955c83b79..3a815e9867 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,11 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.utils;
         
         /**
          * Created by Talio on 11/29/2016.
          */
         public class HealingUtil {
        +
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java
        index 1e6299ce17..7dd86ddb5b 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java
        @@ -13,12 +13,13 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.healing.healers;
         
         import com.google.common.annotations.VisibleForTesting;
         import com.google.gson.JsonObject;
         import com.google.gson.JsonParser;
        +import java.util.Collection;
        +import java.util.Objects;
         import org.apache.commons.lang.StringUtils;
         import org.openecomp.sdc.healing.interfaces.Healer;
         import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao;
        @@ -26,14 +27,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory;
         import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.Collection;
        -import java.util.Objects;
        -
         public class ComponentDataHealer implements Healer {
         
             private static final String VFC_CODE = "vfcCode"; //earlier present in composition data
             private static final String NFC_FUNCTION = "nfcFunction";
        -    private  static final String NFC_NAMING_CODE = "nfcNamingCode";
        +    private static final String NFC_NAMING_CODE = "nfcNamingCode";
             private static final String GENERAL = "general";
             private final ComponentDao componentDao;
         
        @@ -46,12 +44,22 @@ public class ComponentDataHealer implements Healer {
                 this.componentDao = componentDao;
             }
         
        +    private static void moveAttribute(JsonObject compositionJsonObj, JsonObject questJsonObject, JsonObject general, String compositionAttrName,
        +                                      String questAttrName) {
        +        if (Objects.nonNull(compositionJsonObj.get(compositionAttrName))) {
        +            if (general == null) {
        +                general = new JsonObject();
        +            }
        +            general.addProperty(questAttrName, compositionJsonObj.get(compositionAttrName).getAsString());
        +            questJsonObject.add(GENERAL, general);
        +            compositionJsonObj.remove(compositionAttrName);
        +        }
        +    }
        +
             @Override
             public boolean isHealingNeeded(String itemId, Version version) {
        -        final Collection componentEntities =
        -                componentDao.listCompositionAndQuestionnaire(itemId, version);
        -        return Objects.nonNull(componentEntities) && !componentEntities.isEmpty() &&
        -                       componentEntities.stream().anyMatch(this::checkNfcParams);
        +        final Collection componentEntities = componentDao.listCompositionAndQuestionnaire(itemId, version);
        +        return Objects.nonNull(componentEntities) && !componentEntities.isEmpty() && componentEntities.stream().anyMatch(this::checkNfcParams);
             }
         
             private boolean checkNfcParams(ComponentEntity componentEntity) {
        @@ -66,8 +74,7 @@ public class ComponentDataHealer implements Healer {
         
             @Override
             public void heal(String itemId, Version version) throws Exception {
        -        final Collection componentEntities =
        -                componentDao.listCompositionAndQuestionnaire(itemId, version);
        +        final Collection componentEntities = componentDao.listCompositionAndQuestionnaire(itemId, version);
                 if (Objects.nonNull(componentEntities) && !componentEntities.isEmpty()) {
                     componentEntities.forEach(componentEntity -> {
                         final String compositionData = componentEntity.getCompositionData();
        @@ -76,32 +83,18 @@ public class ComponentDataHealer implements Healer {
                 }
             }
         
        -    private void updateComponentData(String itemId, Version version, ComponentEntity componentEntity,
        -                                            String questionnaireData, String compositionData) {
        +    private void updateComponentData(String itemId, Version version, ComponentEntity componentEntity, String questionnaireData,
        +                                     String compositionData) {
                 if (!StringUtils.isEmpty(compositionData)) {
                     JsonParser jsonParser = new JsonParser();
                     JsonObject json = (JsonObject) jsonParser.parse(compositionData);
                     JsonObject questionnaireJson = (JsonObject) jsonParser.parse(questionnaireData);
        -            moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), VFC_CODE,
        -                    NFC_NAMING_CODE);
        -            moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), NFC_FUNCTION,
        -                    NFC_FUNCTION);
        +            moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), VFC_CODE, NFC_NAMING_CODE);
        +            moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), NFC_FUNCTION, NFC_FUNCTION);
                     componentEntity.setCompositionData(json.toString());
                     componentDao.update(componentEntity);
                     componentEntity.setQuestionnaireData(questionnaireJson.toString());
        -            componentDao.updateQuestionnaireData(itemId,version,componentEntity.getId(), questionnaireJson.toString());
        -        }
        -    }
        -
        -    private static void moveAttribute(JsonObject compositionJsonObj, JsonObject questJsonObject,
        -                                      JsonObject general, String compositionAttrName, String questAttrName ) {
        -        if (Objects.nonNull(compositionJsonObj.get(compositionAttrName))) {
        -            if (general == null) {
        -                general = new JsonObject();
        -            }
        -            general.addProperty(questAttrName, compositionJsonObj.get(compositionAttrName).getAsString());
        -            questJsonObject.add(GENERAL, general);
        -            compositionJsonObj.remove(compositionAttrName);
        +            componentDao.updateQuestionnaireData(itemId, version, componentEntity.getId(), questionnaireJson.toString());
                 }
             }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java
        index 0416cc9479..e371463ef3 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java
        @@ -13,9 +13,11 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.healing.healers;
         
        +import java.util.Collection;
        +import java.util.Objects;
        +import java.util.Set;
         import org.openecomp.sdc.healing.interfaces.Healer;
         import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao;
         import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory;
        @@ -26,90 +28,71 @@ import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade;
         import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.Collection;
        -import java.util.Objects;
        -import java.util.Set;
        -
         public class ManufacturerReferenceNumberHealer implements Healer {
         
        -  private static final String MANUFACTURER_REFERENCE_NUMBER = "MRN";
        -  private final VendorLicenseFacade vendorLicenseFacade;
        -  private final FeatureGroupDao featureGroupDao;
        -
        -  public ManufacturerReferenceNumberHealer() {
        -    this(VendorLicenseFacadeFactory.getInstance().createInterface(), FeatureGroupDaoFactory
        -        .getInstance().createInterface());
        -  }
        -
        -  public ManufacturerReferenceNumberHealer(VendorLicenseFacade vendorLicenseFacade,
        -                                           FeatureGroupDao featureGroupDao) {
        -    this.vendorLicenseFacade = vendorLicenseFacade;
        -    this.featureGroupDao = featureGroupDao;
        -  }
        +    private static final String MANUFACTURER_REFERENCE_NUMBER = "MRN";
        +    private final VendorLicenseFacade vendorLicenseFacade;
        +    private final FeatureGroupDao featureGroupDao;
         
        -  @Override
        -  public boolean isHealingNeeded(String itemId, Version version) {
        -    return Objects.isNull(vendorLicenseFacade.listEntitlementPools
        -        (itemId, version).iterator().next().getManufacturerReferenceNumber()) ? true :
        -        false;
        -  }
        -
        -  @Override
        -  public void heal(String itemId, Version version) throws Exception {
        -
        -    healEntitlementPools(itemId, version);
        -    healLicenseKeyGroups(itemId, version);
        -    healFeatureGroups(itemId, version);
        -  }
        -
        -  private void healEntitlementPools(String itemId, Version version) {
        -    Collection entitlementPoolEntities = vendorLicenseFacade
        -        .listEntitlementPools(itemId, version);
        -
        -    for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) {
        -      Set referencingFeatureGroup = entitlementPoolEntity.getReferencingFeatureGroups();
        +    public ManufacturerReferenceNumberHealer() {
        +        this(VendorLicenseFacadeFactory.getInstance().createInterface(), FeatureGroupDaoFactory.getInstance().createInterface());
        +    }
         
        -      if (referencingFeatureGroup.size() == 1) {
        -        entitlementPoolEntity.setManufacturerReferenceNumber(getMRN(itemId, version,
        -            referencingFeatureGroup));
        -      } else {
        -        entitlementPoolEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER);
        -      }
        -      vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity);
        +    public ManufacturerReferenceNumberHealer(VendorLicenseFacade vendorLicenseFacade, FeatureGroupDao featureGroupDao) {
        +        this.vendorLicenseFacade = vendorLicenseFacade;
        +        this.featureGroupDao = featureGroupDao;
             }
        -  }
         
        -  private void healLicenseKeyGroups(String itemId, Version version) {
        -    Collection licenseKeyGroupEntities = vendorLicenseFacade
        -        .listLicenseKeyGroups(itemId, version);
        +    @Override
        +    public boolean isHealingNeeded(String itemId, Version version) {
        +        return Objects.isNull(vendorLicenseFacade.listEntitlementPools(itemId, version).iterator().next().getManufacturerReferenceNumber()) ? true
        +            : false;
        +    }
         
        -    for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) {
        -      Set referencingFeatureGroup = licenseKeyGroupEntity.getReferencingFeatureGroups();
        -      if (referencingFeatureGroup.size() == 1) {
        -        licenseKeyGroupEntity.setManufacturerReferenceNumber(getMRN(itemId, version,
        -            referencingFeatureGroup));
        -      } else {
        -        licenseKeyGroupEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER);
        -      }
        -      vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity);
        +    @Override
        +    public void heal(String itemId, Version version) throws Exception {
        +        healEntitlementPools(itemId, version);
        +        healLicenseKeyGroups(itemId, version);
        +        healFeatureGroups(itemId, version);
             }
        -  }
         
        -  private String getMRN(String itemId, Version
        -      version, Set referencingFeatureGroup) {
        -    FeatureGroupEntity featureGroupEntity = vendorLicenseFacade.getFeatureGroup(new
        -        FeatureGroupEntity(itemId, version, referencingFeatureGroup.iterator().next()));
        -    return featureGroupEntity.getManufacturerReferenceNumber();
        -  }
        +    private void healEntitlementPools(String itemId, Version version) {
        +        Collection entitlementPoolEntities = vendorLicenseFacade.listEntitlementPools(itemId, version);
        +        for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) {
        +            Set referencingFeatureGroup = entitlementPoolEntity.getReferencingFeatureGroups();
        +            if (referencingFeatureGroup.size() == 1) {
        +                entitlementPoolEntity.setManufacturerReferenceNumber(getMRN(itemId, version, referencingFeatureGroup));
        +            } else {
        +                entitlementPoolEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER);
        +            }
        +            vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity);
        +        }
        +    }
         
        -  private void healFeatureGroups(String itemId, Version version) {
        +    private void healLicenseKeyGroups(String itemId, Version version) {
        +        Collection licenseKeyGroupEntities = vendorLicenseFacade.listLicenseKeyGroups(itemId, version);
        +        for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) {
        +            Set referencingFeatureGroup = licenseKeyGroupEntity.getReferencingFeatureGroups();
        +            if (referencingFeatureGroup.size() == 1) {
        +                licenseKeyGroupEntity.setManufacturerReferenceNumber(getMRN(itemId, version, referencingFeatureGroup));
        +            } else {
        +                licenseKeyGroupEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER);
        +            }
        +            vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity);
        +        }
        +    }
         
        -    Collection featureGroupEntities = vendorLicenseFacade.listFeatureGroups
        -        (itemId, version);
        +    private String getMRN(String itemId, Version version, Set referencingFeatureGroup) {
        +        FeatureGroupEntity featureGroupEntity = vendorLicenseFacade
        +            .getFeatureGroup(new FeatureGroupEntity(itemId, version, referencingFeatureGroup.iterator().next()));
        +        return featureGroupEntity.getManufacturerReferenceNumber();
        +    }
         
        -    for (FeatureGroupEntity featureGroupEntity : featureGroupEntities) {
        -      featureGroupEntity.setManufacturerReferenceNumber(null);
        -      featureGroupDao.update(featureGroupEntity);
        +    private void healFeatureGroups(String itemId, Version version) {
        +        Collection featureGroupEntities = vendorLicenseFacade.listFeatureGroups(itemId, version);
        +        for (FeatureGroupEntity featureGroupEntity : featureGroupEntities) {
        +            featureGroupEntity.setManufacturerReferenceNumber(null);
        +            featureGroupDao.update(featureGroupEntity);
        +        }
             }
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java
        index 3b716da1ca..d4ce921133 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java
        @@ -16,9 +16,12 @@
          * Modifications copyright (c) 2019 Nokia
          * ================================================================================
          */
        -
         package org.openecomp.sdc.healing.healers;
         
        +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement;
        +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement;
        +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext;
        +
         import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element;
         import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo;
         import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement;
        @@ -27,6 +30,12 @@ import com.amdocs.zusammen.datatypes.SessionContext;
         import com.amdocs.zusammen.datatypes.item.Action;
         import com.amdocs.zusammen.datatypes.item.ElementContext;
         import com.amdocs.zusammen.utils.fileutils.FileUtils;
        +import java.io.ByteArrayInputStream;
        +import java.io.IOException;
        +import java.io.InputStream;
        +import java.nio.ByteBuffer;
        +import java.util.Collection;
        +import java.util.Objects;
         import org.apache.commons.io.IOUtils;
         import org.apache.commons.lang.ArrayUtils;
         import org.apache.commons.lang.StringUtils;
        @@ -51,49 +60,31 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.
         import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.io.ByteArrayInputStream;
        -import java.io.IOException;
        -import java.io.InputStream;
        -import java.nio.ByteBuffer;
        -import java.util.Collection;
        -import java.util.Objects;
        -
        -import static org.openecomp.core.zusammen.api.ZusammenUtil.*;
        -
         public class NetworkPackageHealer implements Healer {
         
             private static final byte[] EMPTY_DATA_BYTES = "{}".getBytes();
        -    private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR =
        -            "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidate";
        +    private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR = "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidate";
             private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR =
        -            "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidateContent"
        -                    + " under OrchestrationTemplateCandidate";
        -
        -    private static final String MISSING_VSP_MODEL_ERROR =
        -            "Vsp with invalid structure: does not contain element VspModel";
        +        "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidateContent" + " under OrchestrationTemplateCandidate";
        +    private static final String MISSING_VSP_MODEL_ERROR = "Vsp with invalid structure: does not contain element VspModel";
             private static final String MISSING_ORCHESTRATION_TEMPLATE_ERROR =
        -            "Vsp with invalid structure: does not contain element OrchestrationTemplate" + " under VspModel element";
        +        "Vsp with invalid structure: does not contain element OrchestrationTemplate" + " under VspModel element";
             private static final String MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR =
        -            "Vsp with invalid structure: does not contain element OrchestrationTemplateValidationData"
        -                    + " under OrchestrationTemplate element";
        -
        +        "Vsp with invalid structure: does not contain element OrchestrationTemplateValidationData" + " under OrchestrationTemplate element";
             private final VendorSoftwareProductInfoDao vspInfoDao;
             private final ZusammenAdaptor zusammenAdaptor;
             private final CandidateEntityBuilder candidateEntityBuilder;
         
             public NetworkPackageHealer() {
        -        this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(),
        -                ZusammenAdaptorFactory.getInstance().createInterface(),
        -                CandidateServiceFactory.getInstance().createInterface());
        +        this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), ZusammenAdaptorFactory.getInstance().createInterface(),
        +            CandidateServiceFactory.getInstance().createInterface());
             }
         
        -    private NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor,
        -            CandidateService candidateService) {
        +    private NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, CandidateService candidateService) {
                 this(vspInfoDao, zusammenAdaptor, new CandidateEntityBuilder(candidateService));
             }
         
        -    NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor,
        -            CandidateEntityBuilder candidateEntityBuilder) {
        +    NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, CandidateEntityBuilder candidateEntityBuilder) {
                 this.vspInfoDao = vspInfoDao;
                 this.zusammenAdaptor = zusammenAdaptor;
                 this.candidateEntityBuilder = candidateEntityBuilder;
        @@ -101,242 +92,170 @@ public class NetworkPackageHealer implements Healer {
         
             @Override
             public boolean isHealingNeeded(String itemId, Version version) {
        -        return OnboardingMethod.NetworkPackage.name()
        -                       .equals(vspInfoDao.get(new VspDetails(itemId, version)).getOnboardingMethod())
        -                       && isVspMissingAddedElements(itemId, version);
        +        return OnboardingMethod.NetworkPackage.name().equals(vspInfoDao.get(new VspDetails(itemId, version)).getOnboardingMethod())
        +            && isVspMissingAddedElements(itemId, version);
             }
         
             @Override
             public void heal(String itemId, Version version) throws Exception {
                 SessionContext context = createSessionContext();
                 ElementContext elementContext = new ElementContext(itemId, version.getId());
        -
                 Element candidateElement = getElement(context, elementContext, null, ElementType.OrchestrationTemplateCandidate,
        -                MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR);
        -
        -        Collection candidateSubs =
        -                zusammenAdaptor.listElementData(context, elementContext, candidateElement.getElementId());
        -
        -        Id candidateValidationElementId =
        -                creatIfAbsentCandidateValidationElementId(candidateSubs, context, elementContext, candidateElement);
        -
        +            MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR);
        +        Collection candidateSubs = zusammenAdaptor.listElementData(context, elementContext, candidateElement.getElementId());
        +        Id candidateValidationElementId = creatIfAbsentCandidateValidationElementId(candidateSubs, context, elementContext, candidateElement);
                 Element orchestrationTemplateElement = getOrchestrationTemplateElement(context, elementContext);
        -
        -        Collection orchestrationTemplateSubs =
        -                zusammenAdaptor.listElementData(context, elementContext, orchestrationTemplateElement.getElementId());
        -
        -        Id structureElementId = createIfAbsentStructureElementId(orchestrationTemplateSubs, context, elementContext,
        -                orchestrationTemplateElement);
        -
        -        Element orchestrationTemplateValidationElement =
        -                getOrchestrationTemplateValidationElement(orchestrationTemplateSubs);
        -
        -        OrchestrationTemplateEntity orchestrationTemplateEntity =
        -                getOrchestrationTemplateEntity(orchestrationTemplateElement, orchestrationTemplateValidationElement);
        -
        +        Collection orchestrationTemplateSubs = zusammenAdaptor
        +            .listElementData(context, elementContext, orchestrationTemplateElement.getElementId());
        +        Id structureElementId = createIfAbsentStructureElementId(orchestrationTemplateSubs, context, elementContext, orchestrationTemplateElement);
        +        Element orchestrationTemplateValidationElement = getOrchestrationTemplateValidationElement(orchestrationTemplateSubs);
        +        OrchestrationTemplateEntity orchestrationTemplateEntity = getOrchestrationTemplateEntity(orchestrationTemplateElement,
        +            orchestrationTemplateValidationElement);
                 if (StringUtils.isEmpty(orchestrationTemplateEntity.getFileSuffix())) {
                     return;
                 }
        -
                 Element candidateContentElement = getCandidateContentElement(candidateSubs);
        -
                 VspDetails vspDetails = vspInfoDao.get(new VspDetails(itemId, version));
                 if (isEqual(orchestrationTemplateEntity, getCandidateData(candidateElement, candidateContentElement))) {
        -
                     if (isProcessedEntityValid(orchestrationTemplateEntity)) {
        -                emptyStructureElementAndSub(context, elementContext, candidateElement.getElementId(),
        -                        ElementType.OrchestrationTemplateCandidate, candidateContentElement.getElementId(),
        -                        ElementType.OrchestrationTemplateCandidateContent);
        -
        -                populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId,
        -                        vspDetails, context, elementContext);
        +                emptyStructureElementAndSub(context, elementContext, candidateElement.getElementId(), ElementType.OrchestrationTemplateCandidate,
        +                    candidateContentElement.getElementId(), ElementType.OrchestrationTemplateCandidateContent);
        +                populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, vspDetails, context,
        +                    elementContext);
                     } else {
        -                emptyStructureElementAndSub(context, elementContext, orchestrationTemplateElement.getElementId(),
        -                        ElementType.OrchestrationTemplate, orchestrationTemplateValidationElement.getElementId(),
        -                        ElementType.OrchestrationTemplateValidationData);
        -
        +                emptyStructureElementAndSub(context, elementContext, orchestrationTemplateElement.getElementId(), ElementType.OrchestrationTemplate,
        +                    orchestrationTemplateValidationElement.getElementId(), ElementType.OrchestrationTemplateValidationData);
                         populateCandidateValidationData(context, elementContext, candidateValidationElementId,
        -                        orchestrationTemplateEntity.getValidationData());
        +                    orchestrationTemplateEntity.getValidationData());
                     }
                 } else {
        -            populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId,
        -                    vspDetails, context, elementContext);
        +            populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, vspDetails, context, elementContext);
                 }
             }
         
             private boolean isVspMissingAddedElements(String vspId, Version version) {
                 SessionContext context = createSessionContext();
                 ElementContext elementContext = new ElementContext(vspId, version.getId());
        -
        -        return zusammenAdaptor.listElementsByName(context, elementContext, null,
        -                ElementType.OrchestrationTemplateCandidate.name()).stream().noneMatch(
        -                candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name()
        -                                        .equals(candidateSub.getInfo().getName()));
        +        return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.OrchestrationTemplateCandidate.name()).stream()
        +            .noneMatch(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name().equals(candidateSub.getInfo().getName()));
             }
         
             private boolean isEqual(OrchestrationTemplateEntity orchestrationTemplateEntity,
        -            OrchestrationTemplateCandidateData orchestrationTemplateCandidateData) {
        -        return orchestrationTemplateEntity.getFileName().equals(orchestrationTemplateCandidateData.getFileName())
        -                       && orchestrationTemplateEntity.getFileSuffix()
        -                                  .equals(orchestrationTemplateCandidateData.getFileSuffix());
        +                            OrchestrationTemplateCandidateData orchestrationTemplateCandidateData) {
        +        return orchestrationTemplateEntity.getFileName().equals(orchestrationTemplateCandidateData.getFileName()) && orchestrationTemplateEntity
        +            .getFileSuffix().equals(orchestrationTemplateCandidateData.getFileSuffix());
             }
         
             private boolean isProcessedEntityValid(OrchestrationTemplateEntity orchestrationTemplateEntity) {
                 return !orchestrationTemplateEntity.getValidationData().contains(ErrorLevel.ERROR.name());
             }
         
        -    private void populateCandidateValidationData(SessionContext context, ElementContext elementContext,
        -            Id candidateValidationElementId, String validationData) {
        -        ZusammenElement candidateValidationElement =
        -                buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE);
        +    private void populateCandidateValidationData(SessionContext context, ElementContext elementContext, Id candidateValidationElementId,
        +                                                 String validationData) {
        +        ZusammenElement candidateValidationElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE);
                 candidateValidationElement.setElementId(candidateValidationElementId);
                 candidateValidationElement.setData(new ByteArrayInputStream(validationData.getBytes()));
        -
        -        zusammenAdaptor.saveElement(context, elementContext, candidateValidationElement,
        -                "Healed Orchestration Template Candidate Validation data");
        +        zusammenAdaptor.saveElement(context, elementContext, candidateValidationElement, "Healed Orchestration Template Candidate Validation data");
             }
         
        -    private void populateOrchestrationTemplateStructure(InputStream processedFile, Id structureElementId,
        -            VspDetails vspDetails, SessionContext context, ElementContext elementContext) throws Exception {
        +    private void populateOrchestrationTemplateStructure(InputStream processedFile, Id structureElementId, VspDetails vspDetails,
        +                                                        SessionContext context, ElementContext elementContext) throws Exception {
                 byte[] byteData = FileUtils.toByteArray(processedFile);
                 FileContentHandler contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteData);
        -        OrchestrationTemplateCandidateData orchestrationTemplateEntityData =
        -                candidateEntityBuilder
        -                        .buildCandidateEntityFromZip(vspDetails, byteData, contentMap, null);
        +        OrchestrationTemplateCandidateData orchestrationTemplateEntityData = candidateEntityBuilder
        +            .buildCandidateEntityFromZip(vspDetails, byteData, contentMap, null);
                 String fileDataStructure = orchestrationTemplateEntityData.getFilesDataStructure();
        -
        -        ZusammenElement orchestrationTemplateStructure =
        -                buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE);
        +        ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE);
                 orchestrationTemplateStructure.setElementId(structureElementId);
                 orchestrationTemplateStructure.setData(new ByteArrayInputStream(fileDataStructure.getBytes()));
        -
        -        zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateStructure,
        -                "Healed Orchestration Template Structure");
        +        zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateStructure, "Healed Orchestration Template Structure");
             }
         
             private Element getOrchestrationTemplateElement(SessionContext context, ElementContext elementContext) {
        -        ElementInfo vspModelElement =
        -                zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name())
        -                        .orElseThrow(() -> new CoreException(
        -                                new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_VSP_MODEL_ERROR).build()));
        -
        -        return getElement(context, elementContext, vspModelElement.getId(), ElementType.OrchestrationTemplate,
        -                MISSING_ORCHESTRATION_TEMPLATE_ERROR);
        +        ElementInfo vspModelElement = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name())
        +            .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_VSP_MODEL_ERROR).build()));
        +        return getElement(context, elementContext, vspModelElement.getId(), ElementType.OrchestrationTemplate, MISSING_ORCHESTRATION_TEMPLATE_ERROR);
             }
         
             private Element getOrchestrationTemplateValidationElement(Collection orchestrationTemplateSubs) {
        -        return orchestrationTemplateSubs.stream()
        -                       .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateValidationData.name()
        -                                                                   .equals(orchestrationTemplateSub.getInfo()
        -                                                                                   .getName())).findFirst().orElseThrow(
        -                        () -> new CoreException(new ErrorCode.ErrorCodeBuilder()
        -                                                        .withMessage(MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR)
        -                                                        .build()));
        -
        +        return orchestrationTemplateSubs.stream().filter(
        +            orchestrationTemplateSub -> ElementType.OrchestrationTemplateValidationData.name().equals(orchestrationTemplateSub.getInfo().getName()))
        +            .findFirst().orElseThrow(
        +                () -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR).build()));
             }
         
             private Element getCandidateContentElement(Collection candidateSubs) {
        -        return candidateSubs.stream().filter(candidateSub -> ElementType.OrchestrationTemplateCandidateContent.name()
        -                                                                     .equals(candidateSub.getInfo().getName()))
        -                       .findFirst().orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(
        -                        MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR).build()));
        +        return candidateSubs.stream()
        +            .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateContent.name().equals(candidateSub.getInfo().getName())).findFirst()
        +            .orElseThrow(() -> new CoreException(
        +                new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR).build()));
             }
         
        -    private Id createIfAbsentStructureElementId(Collection orchestrationTemplateSubs, SessionContext context,
        -            ElementContext elementContext, Element orchestrationTemplateElement) {
        -        return orchestrationTemplateSubs.stream()
        -                       .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateStructure.name()
        -                                                                   .equals(orchestrationTemplateSub.getInfo()
        -                                                                                   .getName())).findFirst()
        -                       .map(Element::getElementId).orElse(addStructureSubElement(context, elementContext,
        -                        ElementType.OrchestrationTemplateStructure, orchestrationTemplateElement.getElementId()));
        +    private Id createIfAbsentStructureElementId(Collection orchestrationTemplateSubs, SessionContext context, ElementContext elementContext,
        +                                                Element orchestrationTemplateElement) {
        +        return orchestrationTemplateSubs.stream().filter(
        +            orchestrationTemplateSub -> ElementType.OrchestrationTemplateStructure.name().equals(orchestrationTemplateSub.getInfo().getName()))
        +            .findFirst().map(Element::getElementId).orElse(addStructureSubElement(context, elementContext, ElementType.OrchestrationTemplateStructure,
        +                orchestrationTemplateElement.getElementId()));
             }
         
        -    private Id creatIfAbsentCandidateValidationElementId(Collection candidateSubs, SessionContext context,
        -            ElementContext elementContext, Element candidateElement) {
        +    private Id creatIfAbsentCandidateValidationElementId(Collection candidateSubs, SessionContext context, ElementContext elementContext,
        +                                                         Element candidateElement) {
                 return candidateSubs.stream()
        -                       .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name()
        -                                                       .equals(candidateSub.getInfo().getName())).findFirst()
        -                       .map(Element::getElementId).orElse(addStructureSubElement(context, elementContext,
        -                        ElementType.OrchestrationTemplateCandidateValidationData, candidateElement.getElementId()));
        +            .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name().equals(candidateSub.getInfo().getName()))
        +            .findFirst().map(Element::getElementId).orElse(
        +                addStructureSubElement(context, elementContext, ElementType.OrchestrationTemplateCandidateValidationData,
        +                    candidateElement.getElementId()));
             }
         
        -    private Element getElement(SessionContext context, ElementContext elementContext, Id parentElementId,
        -            ElementType elementType, String errorMessage) {
        +    private Element getElement(SessionContext context, ElementContext elementContext, Id parentElementId, ElementType elementType,
        +                               String errorMessage) {
                 return zusammenAdaptor.getElementByName(context, elementContext, parentElementId, elementType.name())
        -                       .orElseThrow(() -> new CoreException(
        -                               new ErrorCode.ErrorCodeBuilder().withMessage(errorMessage).build()));
        +            .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(errorMessage).build()));
             }
         
        -    private OrchestrationTemplateEntity getOrchestrationTemplateEntity(Element orchestrationTemplateElement,
        -            Element validationDataElement) {
        +    private OrchestrationTemplateEntity getOrchestrationTemplateEntity(Element orchestrationTemplateElement, Element validationDataElement) {
                 OrchestrationTemplateEntity orchestrationTemplateEntity = new OrchestrationTemplateEntity();
        -
                 if (isNotEmpty(orchestrationTemplateElement.getData())) {
        -            orchestrationTemplateEntity
        -                    .setContentData(ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData())));
        +            orchestrationTemplateEntity.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData())));
                 }
        -        orchestrationTemplateEntity
        -                .setFileSuffix(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
        -        orchestrationTemplateEntity
        -                .setFileName(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal()));
        +        orchestrationTemplateEntity.setFileSuffix(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
        +        orchestrationTemplateEntity.setFileName(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal()));
                 if (isNotEmpty(validationDataElement.getData())) {
        -            orchestrationTemplateEntity
        -                    .setValidationData(new String(FileUtils.toByteArray(validationDataElement.getData())));
        +            orchestrationTemplateEntity.setValidationData(new String(FileUtils.toByteArray(validationDataElement.getData())));
                 }
                 return orchestrationTemplateEntity;
             }
         
        -    private OrchestrationTemplateCandidateData getCandidateData(Element candidateElement,
        -            Element candidateContentElement) {
        +    private OrchestrationTemplateCandidateData getCandidateData(Element candidateElement, Element candidateContentElement) {
                 OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData();
                 candidateData.setFilesDataStructure(new String(FileUtils.toByteArray(candidateElement.getData())));
                 candidateData.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.getData())));
        -        candidateData
        -                .setFileSuffix(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
        +        candidateData.setFileSuffix(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal()));
                 candidateData.setFileName(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal()));
                 return candidateData;
             }
         
        -    private Id addStructureSubElement(SessionContext context, ElementContext elementContext, ElementType elementType,
        -            Id parentElementId) {
        +    private Id addStructureSubElement(SessionContext context, ElementContext elementContext, ElementType elementType, Id parentElementId) {
                 ZusammenElement newElement = buildStructuralElement(elementType, Action.CREATE);
        -
                 ZusammenElement parentElement = buildElement(parentElementId, Action.IGNORE);
                 parentElement.addSubElement(newElement);
        -
                 return zusammenAdaptor.saveElement(context, elementContext, parentElement,
        -                String.format("Add element %s under element id %s", elementType.name(), parentElementId))
        -                       .getSubElements().iterator().next().getElementId();
        +            String.format("Add element %s under element id %s", elementType.name(), parentElementId)).getSubElements().iterator().next()
        +            .getElementId();
             }
         
        -    private void emptyStructureElementAndSub(SessionContext context, ElementContext elementContext, Id elementId,
        -            ElementType elementType, Id subElementId, ElementType subElementType) {
        +    private void emptyStructureElementAndSub(SessionContext context, ElementContext elementContext, Id elementId, ElementType elementType,
        +                                             Id subElementId, ElementType subElementType) {
                 ZusammenElement subElement = buildStructuralElement(subElementType, Action.UPDATE);
                 subElement.setElementId(subElementId);
                 subElement.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES));
        -
                 ZusammenElement element = buildStructuralElement(elementType, Action.UPDATE);
                 element.setElementId(elementId);
                 element.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES));
                 element.addSubElement(subElement);
        -
                 zusammenAdaptor.saveElement(context, elementContext, element,
        -                String.format("Empty element %s and its sub element %s", elementType.name(), subElementType.name()));
        -    }
        -
        -    public enum InfoPropertyName {
        -        FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName");
        -
        -        private String val;
        -
        -        InfoPropertyName(String val) {
        -            this.val = val;
        -        }
        -
        -        private String getVal() {
        -            return val;
        -        }
        +            String.format("Empty element %s and its sub element %s", elementType.name(), subElementType.name()));
             }
         
             private boolean isNotEmpty(InputStream elementData) {
        @@ -351,4 +270,17 @@ public class NetworkPackageHealer implements Healer {
                 }
                 return !ArrayUtils.isEmpty(byteElementData);
             }
        +
        +    public enum InfoPropertyName {
        +        FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName");
        +        private String val;
        +
        +        InfoPropertyName(String val) {
        +            this.val = val;
        +        }
        +
        +        private String getVal() {
        +            return val;
        +        }
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java
        index 9fcc6e5b74..2d89661d26 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,13 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.healers;
         
        +import java.util.Collection;
        +import java.util.Collections;
        +import java.util.HashSet;
        +import java.util.Objects;
        +import java.util.Optional;
         import org.openecomp.sdc.common.errors.SdcRuntimeException;
         import org.openecomp.sdc.common.session.SessionContextProviderFactory;
         import org.openecomp.sdc.healing.interfaces.Healer;
        @@ -34,70 +38,57 @@ import org.openecomp.sdc.versioning.dao.ItemDaoFactory;
         import org.openecomp.sdc.versioning.dao.types.Version;
         import org.openecomp.sdc.versioning.types.Item;
         
        -import java.util.*;
        -
         /**
          * Created by ayalaben on 8/28/2017
          */
         public class OwnerHealer implements Healer {
        -  private static final String HEALING_USER_SUFFIX = "_healer";
        -  private static final ItemPermissionsDao permissionsDao =
        -      ItemPermissionsDaoFactory.getInstance().createInterface();
        -  private static final ItemDao itemDao = ItemDaoFactory.getInstance().createInterface();
        -
        -  private static final SubscribersDao subscribersDao = SubscribersDaoFactory.getInstance()
        -      .createInterface();
        -
        -  @Override
        -  public boolean isHealingNeeded(String itemId, Version version) {
        -    return permissionsDao.listItemPermissions(itemId).stream().noneMatch(this::isOwnerPermission) ||
        -        isOwnerMissingOnItem(itemId);
        -  }
        -
        -  public void heal(String itemId, Version version) {
        -    Collection itemPermissions = permissionsDao.listItemPermissions(itemId);
         
        -    if (itemPermissions.stream().noneMatch(this::isOwnerPermission)) {
        -      String currentUserId =
        -          SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId()
        -              .replace(HEALING_USER_SUFFIX, "");
        +    private static final String HEALING_USER_SUFFIX = "_healer";
        +    private static final ItemPermissionsDao permissionsDao = ItemPermissionsDaoFactory.getInstance().createInterface();
        +    private static final ItemDao itemDao = ItemDaoFactory.getInstance().createInterface();
        +    private static final SubscribersDao subscribersDao = SubscribersDaoFactory.getInstance().createInterface();
         
        -      permissionsDao.updateItemPermissions(itemId, PermissionTypes.Owner.name(),
        -          Collections.singleton(currentUserId), new HashSet<>());
        -
        -      updateItemOwner(itemId, currentUserId);
        -
        -      subscribersDao.subscribe(currentUserId, itemId);
        +    @Override
        +    public boolean isHealingNeeded(String itemId, Version version) {
        +        return permissionsDao.listItemPermissions(itemId).stream().noneMatch(this::isOwnerPermission) || isOwnerMissingOnItem(itemId);
        +    }
         
        -    } else if (isOwnerMissingOnItem(itemId)) {
        -      Optional ownerOpt =
        -          itemPermissions.stream().filter(this::isOwnerPermission).findFirst();
        -      if (ownerOpt.isPresent()) {
        -        updateItemOwner(itemId, ownerOpt.get().getUserId());
        -      } else {
        -        throw new SdcRuntimeException("Unexpected error in Owner Healer. Item id: " + itemId);
        -      }
        +    public void heal(String itemId, Version version) {
        +        Collection itemPermissions = permissionsDao.listItemPermissions(itemId);
        +        if (itemPermissions.stream().noneMatch(this::isOwnerPermission)) {
        +            String currentUserId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId()
        +                .replace(HEALING_USER_SUFFIX, "");
        +            permissionsDao.updateItemPermissions(itemId, PermissionTypes.Owner.name(), Collections.singleton(currentUserId), new HashSet<>());
        +            updateItemOwner(itemId, currentUserId);
        +            subscribersDao.subscribe(currentUserId, itemId);
        +        } else if (isOwnerMissingOnItem(itemId)) {
        +            Optional ownerOpt = itemPermissions.stream().filter(this::isOwnerPermission).findFirst();
        +            if (ownerOpt.isPresent()) {
        +                updateItemOwner(itemId, ownerOpt.get().getUserId());
        +            } else {
        +                throw new SdcRuntimeException("Unexpected error in Owner Healer. Item id: " + itemId);
        +            }
        +        }
             }
        -  }
         
        -  private void updateItemOwner(String itemId, String userId) {
        -    Item item = new Item();
        -    item.setId(itemId);
        -    Item retrievedItem = itemDao.get(item);
        -    if (Objects.nonNull(retrievedItem)) {
        -      retrievedItem.setOwner(userId);
        -      itemDao.update(retrievedItem);
        +    private void updateItemOwner(String itemId, String userId) {
        +        Item item = new Item();
        +        item.setId(itemId);
        +        Item retrievedItem = itemDao.get(item);
        +        if (Objects.nonNull(retrievedItem)) {
        +            retrievedItem.setOwner(userId);
        +            itemDao.update(retrievedItem);
        +        }
             }
        -  }
         
        -  private boolean isOwnerMissingOnItem(String itemId) {
        -    Item item = new Item();
        -    item.setId(itemId);
        -    Item retrievedItem = itemDao.get(item);
        -    return Objects.nonNull(retrievedItem) && Objects.isNull(retrievedItem.getOwner());
        -  }
        +    private boolean isOwnerMissingOnItem(String itemId) {
        +        Item item = new Item();
        +        item.setId(itemId);
        +        Item retrievedItem = itemDao.get(item);
        +        return Objects.nonNull(retrievedItem) && Objects.isNull(retrievedItem.getOwner());
        +    }
         
        -  private boolean isOwnerPermission(ItemPermissionsEntity permissionsEntity) {
        -    return permissionsEntity.getPermission().equals(PermissionTypes.Owner.name());
        -  }
        +    private boolean isOwnerPermission(ItemPermissionsEntity permissionsEntity) {
        +        return permissionsEntity.getPermission().equals(PermissionTypes.Owner.name());
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java
        index 1aed46163d..b65629002a 100644
        --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java
        +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healing.healers;
         
        +import java.io.IOException;
        +import java.util.Objects;
        +import java.util.Optional;
         import org.apache.commons.collections4.MapUtils;
         import org.openecomp.core.converter.ToscaConverter;
         import org.openecomp.core.converter.factory.ToscaConverterFactory;
        @@ -40,99 +42,73 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFacto
         import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.io.IOException;
        -import java.util.Objects;
        -import java.util.Optional;
        -
         public class ToscaServiceModelHealer implements Healer {
        -  private ServiceModelDao serviceModelDao;
        -  private OrchestrationTemplateDao orchestrationTemplateDao;
        -  private static final String VALIDATION_FAILURE_MESSAGE = "Product was updated. Please " +
        -      "update the uploaded Heat file according to these validation errors: \n";
        -
        -  public ToscaServiceModelHealer() {
        -    this.serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface();
        -    this.orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface();
        -  }
        -
        -  public ToscaServiceModelHealer(
        -      ServiceModelDao serviceModelDao,
        -      OrchestrationTemplateDao orchestrationTemplateDao) {
        -    this.serviceModelDao = serviceModelDao;
        -    this.orchestrationTemplateDao = orchestrationTemplateDao;
        -  }
        -
        -  @Override
        -  public boolean isHealingNeeded(String itemId, Version version) {
        -    OrchestrationTemplateEntity orchestrationTemplate =
        -        orchestrationTemplateDao.get(itemId, version);
        -    OnboardingTypesEnum onboardingTypes =
        -        OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix());
         
        -    return Objects.nonNull(onboardingTypes) &&
        -        Objects.nonNull(orchestrationTemplate.getContentData());
        -  }
        +    private static final String VALIDATION_FAILURE_MESSAGE =
        +        "Product was updated. Please " + "update the uploaded Heat file according to these validation errors: \n";
        +    private ServiceModelDao serviceModelDao;
        +    private OrchestrationTemplateDao orchestrationTemplateDao;
         
        -  @Override
        -  public void heal(String itemId, Version version) throws Exception {
        -    OrchestrationTemplateEntity orchestrationTemplateEntity =
        -        orchestrationTemplateDao.get(itemId, version);
        -    OnboardingTypesEnum type =
        -        OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplateEntity.getFileSuffix());
        -
        -    Optional healedServiceModel =
        -        healServiceModel(orchestrationTemplateEntity, type);
        -
        -    healedServiceModel.ifPresent(serviceModel -> serviceModelDao
        -        .overrideServiceModel(itemId, version, serviceModel));
        -  }
        -
        -  private Optional healServiceModel(
        -      OrchestrationTemplateEntity orchestrationTemplateEntity,
        -      OnboardingTypesEnum type) throws IOException {
        -    switch (type) {
        -      case ZIP:
        -        return Optional.of(healServiceModelFromZip(
        -            getFileContentHandlerForHealing(orchestrationTemplateEntity, type)));
        +    public ToscaServiceModelHealer() {
        +        this.serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface();
        +        this.orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface();
        +    }
         
        -      case CSAR:
        -        return Optional.of(healServiceModelFromCsar(
        -            getFileContentHandlerForHealing(orchestrationTemplateEntity, type)));
        +    public ToscaServiceModelHealer(ServiceModelDao serviceModelDao,
        +                                   OrchestrationTemplateDao orchestrationTemplateDao) {
        +        this.serviceModelDao = serviceModelDao;
        +        this.orchestrationTemplateDao = orchestrationTemplateDao;
        +    }
         
        -      default:
        -        return Optional.empty();
        +    @Override
        +    public boolean isHealingNeeded(String itemId, Version version) {
        +        OrchestrationTemplateEntity orchestrationTemplate = orchestrationTemplateDao.get(itemId, version);
        +        OnboardingTypesEnum onboardingTypes = OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix());
        +        return Objects.nonNull(onboardingTypes) && Objects.nonNull(orchestrationTemplate.getContentData());
             }
        -  }
         
        -  private FileContentHandler getFileContentHandlerForHealing(
        -      OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type)
        -      throws IOException {
        -    byte[] uploadedFileContent = orchestrationTemplateEntity.getContentData().array();
        -    return CommonUtil.validateAndUploadFileContent(type, uploadedFileContent);
        -  }
        +    @Override
        +    public void heal(String itemId, Version version) throws Exception {
        +        OrchestrationTemplateEntity orchestrationTemplateEntity = orchestrationTemplateDao.get(itemId, version);
        +        OnboardingTypesEnum type = OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplateEntity.getFileSuffix());
        +        Optional healedServiceModel = healServiceModel(orchestrationTemplateEntity, type);
        +        healedServiceModel.ifPresent(serviceModel -> serviceModelDao.overrideServiceModel(itemId, version, serviceModel));
        +    }
         
        -  private ToscaServiceModel healServiceModelFromZip(FileContentHandler contentMap) {
        -    TranslatorOutput translatorOutput =
        -        HeatToToscaUtil.loadAndTranslateTemplateData(contentMap);
        +    private Optional healServiceModel(OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type)
        +        throws IOException {
        +        switch (type) {
        +            case ZIP:
        +                return Optional.of(healServiceModelFromZip(getFileContentHandlerForHealing(orchestrationTemplateEntity, type)));
        +            case CSAR:
        +                return Optional.of(healServiceModelFromCsar(getFileContentHandlerForHealing(orchestrationTemplateEntity, type)));
        +            default:
        +                return Optional.empty();
        +        }
        +    }
         
        -    if (areThereValidationErrors(translatorOutput)) {
        -      String validationErrorsAsString = MessageContainerUtil.getErrorMessagesListAsString
        -          (MessageContainerUtil
        -              .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()));
        -      throw new RuntimeException(VALIDATION_FAILURE_MESSAGE + validationErrorsAsString);
        +    private FileContentHandler getFileContentHandlerForHealing(OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type)
        +        throws IOException {
        +        byte[] uploadedFileContent = orchestrationTemplateEntity.getContentData().array();
        +        return CommonUtil.validateAndUploadFileContent(type, uploadedFileContent);
             }
         
        -    return translatorOutput.getToscaServiceModel();
        -  }
        +    private ToscaServiceModel healServiceModelFromZip(FileContentHandler contentMap) {
        +        TranslatorOutput translatorOutput = HeatToToscaUtil.loadAndTranslateTemplateData(contentMap);
        +        if (areThereValidationErrors(translatorOutput)) {
        +            String validationErrorsAsString = MessageContainerUtil
        +                .getErrorMessagesListAsString(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()));
        +            throw new RuntimeException(VALIDATION_FAILURE_MESSAGE + validationErrorsAsString);
        +        }
        +        return translatorOutput.getToscaServiceModel();
        +    }
         
        -  private boolean areThereValidationErrors(TranslatorOutput translatorOutput) {
        -    return MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR,
        -        translatorOutput.getErrorMessages()));
        -  }
        +    private boolean areThereValidationErrors(TranslatorOutput translatorOutput) {
        +        return MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages()));
        +    }
         
        -  private ToscaServiceModel healServiceModelFromCsar(FileContentHandler contentMap)
        -      throws IOException {
        -    ToscaConverter toscaConverter = ToscaConverterFactory.getInstance().createInterface();
        -    return toscaConverter.convert(contentMap);
        -  }
        +    private ToscaServiceModel healServiceModelFromCsar(FileContentHandler contentMap) throws IOException {
        +        ToscaConverter toscaConverter = ToscaConverterFactory.getInstance().createInterface();
        +        return toscaConverter.convert(contentMap);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/DefinedHeatParameterTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/DefinedHeatParameterTypes.java
        index 4205f0bee3..2131dec35e 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/DefinedHeatParameterTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/DefinedHeatParameterTypes.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
         import java.util.HashMap;
        @@ -33,12 +32,7 @@ import org.onap.sdc.tosca.datatypes.model.ScalarUnitValidator;
         @AllArgsConstructor
         @Getter
         public enum DefinedHeatParameterTypes {
        -    NUMBER("number"),
        -    STRING("string"),
        -    COMMA_DELIMITED_LIST("comma_delimited_list"),
        -    JSON("json"),
        -    BOOLEAN("boolean");
        -
        +    NUMBER("number"), STRING("string"), COMMA_DELIMITED_LIST("comma_delimited_list"), JSON("json"), BOOLEAN("boolean");
             private static ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance();
             private static Map stringToDefinedType;
         
        @@ -64,49 +58,39 @@ public enum DefinedHeatParameterTypes {
              */
             public static boolean isValueIsFromGivenType(final Object value, final String parameterType) {
                 final DefinedHeatParameterTypes definedType = findByHeatResource(parameterType);
        -
                 if (Objects.nonNull(definedType)) {
                     switch (definedType) {
                         case NUMBER:
        -                    if (scalarUnitValidator.isValueScalarUnit(value, ToscaScalarUnitSize.class) ||
        -                        scalarUnitValidator.isValueScalarUnit(value, ToscaScalarUnitTime.class) ||
        -                        scalarUnitValidator.isValueScalarUnit(value, ToscaScalarUnitFrequency.class)) {
        +                    if (scalarUnitValidator.isValueScalarUnit(value, ToscaScalarUnitSize.class) || scalarUnitValidator
        +                        .isValueScalarUnit(value, ToscaScalarUnitTime.class) || scalarUnitValidator
        +                        .isValueScalarUnit(value, ToscaScalarUnitFrequency.class)) {
                                 return isValueString(value);
                             }
                             return NumberUtils.isNumber(String.valueOf(value));
        -
                         case BOOLEAN:
                             return HeatBoolean.isValueBoolean(value);
        -
                         case COMMA_DELIMITED_LIST:
                             return isValueCommaDelimitedList(value);
        -
                         case JSON:
                             return isValueJson(value);
        -
                         case STRING:
                             return isValueString(value);
                         default:
                     }
                 }
        -
                 return false;
             }
         
             public static boolean isNovaServerEnvValueIsFromRightType(final Object value) {
        -        return isValueIsFromGivenType(value, COMMA_DELIMITED_LIST.getType())
        -                || isValueIsFromGivenType(value, STRING.getType());
        +        return isValueIsFromGivenType(value, COMMA_DELIMITED_LIST.getType()) || isValueIsFromGivenType(value, STRING.getType());
             }
         
             private static boolean isValueCommaDelimitedList(final Object value) {
        -        return value instanceof List
        -                || String.valueOf(value).contains(",")
        -                || isValueIsFromGivenType(value, DefinedHeatParameterTypes.STRING.type);
        +        return value instanceof List || String.valueOf(value).contains(",") || isValueIsFromGivenType(value, DefinedHeatParameterTypes.STRING.type);
             }
         
             private static boolean isValueString(final Object value) {
        -        return value instanceof String
        -                || ClassUtils.isPrimitiveOrWrapper(value.getClass());
        +        return value instanceof String || ClassUtils.isPrimitiveOrWrapper(value.getClass());
             }
         
             private static boolean isValueJson(final Object value) {
        @@ -116,5 +100,4 @@ public enum DefinedHeatParameterTypes {
             public static boolean isEmptyValueInEnv(final Object value) {
                 return Objects.isNull(value);
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/HeatBoolean.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/HeatBoolean.java
        index 19fa2d5964..8b5d91c6e0 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/HeatBoolean.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/HeatBoolean.java
        @@ -13,12 +13,10 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
         import java.util.HashSet;
         import java.util.Set;
        -
         import org.openecomp.sdc.common.errors.CoreException;
         import org.openecomp.sdc.common.errors.ErrorCategory;
         import org.openecomp.sdc.common.errors.ErrorCode;
        @@ -28,17 +26,11 @@ import org.openecomp.sdc.logging.api.LoggerFactory;
         
         public class HeatBoolean {
         
        +    private static final Logger LOG = LoggerFactory.getLogger(HeatBoolean.class.getName());
             private static Set heatFalse;
             private static Set heatTrue;
        -    private static final Logger LOG = LoggerFactory.getLogger(HeatBoolean.class.getName());
        -
        -    private HeatBoolean() {
        -        //Utility classes, which are a collection of static members, are not meant to be instantiated
        -    }
         
             static {
        -
        -
                 heatFalse = new HashSet<>();
                 heatFalse.add("f");
                 heatFalse.add(false);
        @@ -47,7 +39,6 @@ public class HeatBoolean {
                 heatFalse.add("n");
                 heatFalse.add("no");
                 heatFalse.add(0);
        -
                 heatTrue = new HashSet<>();
                 heatTrue.add("t");
                 heatTrue.add(true);
        @@ -56,7 +47,10 @@ public class HeatBoolean {
                 heatTrue.add("y");
                 heatTrue.add("yes");
                 heatTrue.add(1);
        +    }
         
        +    private HeatBoolean() {
        +        //Utility classes, which are a collection of static members, are not meant to be instantiated
             }
         
             /**
        @@ -66,7 +60,6 @@ public class HeatBoolean {
              * @return the boolean
              */
             public static Boolean eval(Object value) {
        -
                 if (value instanceof String) {
                     value = ((String) value).toLowerCase();
                 }
        @@ -75,11 +68,9 @@ public class HeatBoolean {
                 } else if (heatTrue.contains(value)) {
                     return true;
                 } else {
        -            throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withId(ErrorCodes.INVALID_BOOLEAN)
        -                    .withCategory(ErrorCategory.APPLICATION)
        -                    .withMessage("Invalid boolean value [" + value + "].").build());
        +            throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withId(ErrorCodes.INVALID_BOOLEAN).withCategory(ErrorCategory.APPLICATION)
        +                .withMessage("Invalid boolean value [" + value + "].").build());
                 }
        -
             }
         
             /**
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitFrequency.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitFrequency.java
        index 8ec246555a..e61a9269f2 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitFrequency.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitFrequency.java
        @@ -16,14 +16,9 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
         /**
          * This enum is responsible for defining properties that have scalar values measured in units per second.
          */
        -public enum ToscaScalarUnitFrequency {
        -
        -    HZ, KHZ, MHZ, GHZ
        -
        -}
        +public enum ToscaScalarUnitFrequency {HZ, KHZ, MHZ, GHZ}
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitSize.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitSize.java
        index 12f6a176a3..6117ebdfc1 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitSize.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitSize.java
        @@ -16,14 +16,9 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
         /**
          * This enum is responsible for defining properties that have scalar values measured in size units.
          */
        -public enum ToscaScalarUnitSize {
        -
        -    B, KB, KIB, MB, MIB, GB, GIB, TB, TIB
        -
        -}
        +public enum ToscaScalarUnitSize {B, KB, KIB, MB, MIB, GB, GIB, TB, TIB}
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTime.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTime.java
        index 0a41a63ed1..081e06121e 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTime.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTime.java
        @@ -16,15 +16,9 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
        -
         /**
          * This enum is responsible for defining properties that have scalar values measured in size units.
          */
        -public enum ToscaScalarUnitTime {
        -
        -    D, H, M, S, MS, US, NS
        -
        -}
        +public enum ToscaScalarUnitTime {D, H, M, S, MS, US, NS}
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTypes.java
        index 05cc97c8dc..d92ef4fc2e 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/ToscaScalarUnitTypes.java
        @@ -16,7 +16,6 @@
          *  SPDX-License-Identifier: Apache-2.0
          *  ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes;
         
         import lombok.AllArgsConstructor;
        @@ -28,10 +27,6 @@ import lombok.Getter;
         @Getter
         @AllArgsConstructor
         public enum ToscaScalarUnitTypes {
        -
        -    SCALAR_UNIT_SIZE("scalar-unit.size"),
        -    SCALAR_UNIT_TIME("scalar-unit.time"),
        -    SCALAR_UNIT_FREQUENCY("scalar-unit.frequency");
        -
        +    SCALAR_UNIT_SIZE("scalar-unit.size"), SCALAR_UNIT_TIME("scalar-unit.time"), SCALAR_UNIT_FREQUENCY("scalar-unit.frequency");
             private String type;
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/FileData.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/FileData.java
        index 27b035b2ac..0e079414d2 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/FileData.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/FileData.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.manifest;
         
         import java.util.ArrayList;
        @@ -26,7 +25,6 @@ import java.util.HashSet;
         import java.util.List;
         import java.util.Set;
         import java.util.function.Predicate;
        -
         import lombok.AccessLevel;
         import lombok.AllArgsConstructor;
         import lombok.Data;
        @@ -37,9 +35,7 @@ import org.apache.commons.collections4.CollectionUtils;
         @Data
         public class FileData {
         
        -    protected static final Set heatFileTypes =
        -            new HashSet<>(Arrays.asList(Type.HEAT, Type.HEAT_NET, Type.HEAT_VOL));
        -
        +    protected static final Set heatFileTypes = new HashSet<>(Arrays.asList(Type.HEAT, Type.HEAT_NET, Type.HEAT_VOL));
             @Getter(AccessLevel.NONE)
             @Setter(AccessLevel.NONE)
             private Boolean isBase;
        @@ -79,6 +75,7 @@ public class FileData {
             @AllArgsConstructor
             @Getter
             public enum Type {
        +        // @formatter:off
                 HEAT("HEAT"),
                 HEAT_ENV("HEAT_ENV"),
                 HEAT_NET("HEAT_NET"),
        @@ -99,6 +96,7 @@ public class FileData {
                 OTHER("OTHER"),
                 PNF_SW_INFORMATION("PNF_SW_INFORMATION"),
                 PM_DICTIONARY("PM_DICTIONARY");
        +        // @formatter:on
         
                 private String displayName;
         
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestContent.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestContent.java
        index 107b060094..2976542bf0 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestContent.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestContent.java
        @@ -17,11 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.manifest;
         
         import java.util.List;
        -
         import lombok.Data;
         
         @Data
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestFile.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestFile.java
        index 6a62740bf5..0eeb2a6121 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestFile.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/manifest/ManifestFile.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.manifest;
         
         import lombok.Data;
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Constraint.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Constraint.java
        index 13b3fac170..81840e741b 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Constraint.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Constraint.java
        @@ -17,12 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
        -import java.util.ArrayList;
         import java.util.List;
        -
         import lombok.AccessLevel;
         import lombok.Data;
         import lombok.NoArgsConstructor;
        @@ -39,6 +36,6 @@ public class Constraint {
             private String pattern;
         
             public void setRange(Integer[] inRange) {
        -        this.range = new Integer[] {inRange[0], inRange[1]};
        +        this.range = new Integer[]{inRange[0], inRange[1]};
             }
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailResourceTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailResourceTypes.java
        index 7538f11593..28ba22a874 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailResourceTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailResourceTypes.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.HashMap;
        @@ -25,17 +24,18 @@ import java.util.Map;
         import java.util.Objects;
         
         public enum ContrailResourceTypes {
        +    // @formatter:off
             ATTACH_POLICY("OS::Contrail::AttachPolicy"),
             SERVICE_INSTANCE("OS::Contrail::ServiceInstance"),
             SERVICE_TEMPLATE("OS::Contrail::ServiceTemplate"),
             NETWORK_POLICY("OS::Contrail::NetworkPolicy"),
             VIRTUAL_NETWORK("OS::Contrail::VirtualNetwork");
        +    // @formatter:on
         
             private static Map stringToContrailResourceTypeMap;
         
             static {
                 stringToContrailResourceTypeMap = new HashMap<>();
        -
                 for (ContrailResourceTypes type : ContrailResourceTypes.values()) {
                     stringToContrailResourceTypeMap.put(type.contrailResourceType, type);
                 }
        @@ -54,9 +54,7 @@ public enum ContrailResourceTypes {
              * @return the contrail resource types
              */
             public static ContrailResourceTypes findByContrailV2Resource(String contrailV2Resource) {
        -        return contrailV2Resource == null ? null
        -                : stringToContrailResourceTypeMap.get(contrailV2Resource);
        -
        +        return contrailV2Resource == null ? null : stringToContrailResourceTypeMap.get(contrailV2Resource);
             }
         
             public static boolean isResourceTypeContrail(String resourceType) {
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailV2ResourceTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailV2ResourceTypes.java
        index 40253ad1be..cae1c7f521 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailV2ResourceTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ContrailV2ResourceTypes.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.HashMap;
        @@ -25,16 +24,17 @@ import java.util.Map;
         import java.util.Objects;
         
         public enum ContrailV2ResourceTypes {
        +    // @formatter:off
             NETWROK_IPAM("OS::ContrailV2::NetworkIpam"),
             VIRTUAL_NETWORK("OS::ContrailV2::VirtualNetwork"),
             NETWORK_POLICY("OS::ContrailV2::NetworkPolicy"),
             VIRTUAL_MACHINE_INTERFACE("OS::ContrailV2::VirtualMachineInterface");
        +    // @formatter:on
         
             private static Map stringToContrailV2ResourceTypeMap;
         
             static {
                 stringToContrailV2ResourceTypeMap = new HashMap<>();
        -
                 for (ContrailV2ResourceTypes type : ContrailV2ResourceTypes.values()) {
                     stringToContrailV2ResourceTypeMap.put(type.contrailV2ResourceType, type);
                 }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Environment.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Environment.java
        index db5121b014..1713e56381 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Environment.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Environment.java
        @@ -17,11 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.Map;
        -
         import lombok.Data;
         
         @Data
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplate.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplate.java
        index 3387c43840..c8dee98449 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplate.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatOrchestrationTemplate.java
        @@ -17,12 +17,10 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.List;
         import java.util.Map;
        -
         import lombok.Data;
         
         @Data
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatPseudoParameters.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatPseudoParameters.java
        index 73020bcbcf..b85ec3bb5b 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatPseudoParameters.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatPseudoParameters.java
        @@ -17,21 +17,21 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.ArrayList;
         import java.util.List;
        -
         import lombok.AllArgsConstructor;
         import lombok.Getter;
         
         @AllArgsConstructor
         @Getter
         public enum HeatPseudoParameters {
        +    // @formatter:off
             OS_STACK_NAME("OS::stack_name"),
             OS_STACK_ID("OS::stack_id"),
             OS_PROJECT_ID("OS::project_id");
        +    // @formatter:on
         
             private static final List pseudoParameterNames = new ArrayList<>();
             private final String pseudoParameter;
        @@ -42,8 +42,8 @@ public enum HeatPseudoParameters {
                 }
             }
         
        +
             public static List getPseudoParameterNames() {
                 return pseudoParameterNames;
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatResourcesTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatResourcesTypes.java
        index a9598eb67f..8e7456b679 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatResourcesTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/HeatResourcesTypes.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.ArrayList;
        @@ -27,6 +26,7 @@ import java.util.Map;
         import java.util.Objects;
         
         public enum HeatResourcesTypes {
        +    // @formatter:off
             NOVA_SERVER_RESOURCE_TYPE("OS::Nova::Server"),
             NOVA_SERVER_GROUP_RESOURCE_TYPE("OS::Nova::ServerGroup"),
             NEUTRON_PORT_RESOURCE_TYPE("OS::Neutron::Port"),
        @@ -48,13 +48,13 @@ public enum HeatResourcesTypes {
             CONTRAIL_SERVICE_INSTANCE("OS::Contrail::ServiceInstance"),
             CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE("OS::ContrailV2::NetworkPolicy"),
             RESOURCE_GROUP_RESOURCE_TYPE("OS::Heat::ResourceGroup");
        +    // @formatter:on
         
             private static Map stringToHeatResourceTypeMap;
             private String heatResource;
         
             static {
                 stringToHeatResourceTypeMap = new HashMap<>();
        -
                 for (HeatResourcesTypes type : HeatResourcesTypes.values()) {
                     stringToHeatResourceTypeMap.put(type.heatResource, type);
                 }
        @@ -81,10 +81,10 @@ public enum HeatResourcesTypes {
             public static boolean isResourceExpectedToBeExposed(String resourceType) {
                 //todo - check
                 return (resourceType.equals(NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource())
        -                || resourceType.equals(CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource())
        -                || resourceType.equals(NEUTRON_NET_RESOURCE_TYPE.getHeatResource())
        -                || resourceType.equals(CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())
        -                || resourceType.equals(NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource())
        +            || resourceType.equals(CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource())
        +            || resourceType.equals(NEUTRON_NET_RESOURCE_TYPE.getHeatResource())
        +            || resourceType.equals(CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())
        +            || resourceType.equals(NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource())
                 );
             }
         
        @@ -94,14 +94,11 @@ public enum HeatResourcesTypes {
              * @param types the types
              * @return the list for resource type
              */
        -    public static Map> getListForResourceType(
        -            HeatResourcesTypes... types) {
        +    public static Map> getListForResourceType(HeatResourcesTypes... types) {
                 Map> result = new HashMap<>();
        -
                 for (HeatResourcesTypes type : types) {
                     result.put(type, new ArrayList<>());
                 }
        -
                 return result;
             }
         
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Output.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Output.java
        index 343205d171..629f317a47 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Output.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Output.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import lombok.Data;
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Parameter.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Parameter.java
        index 81372aa68c..51df5df455 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Parameter.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Parameter.java
        @@ -17,12 +17,10 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.List;
         import java.util.Map;
        -
         import lombok.Data;
         
         @Data
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterGroup.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterGroup.java
        index 4595466436..d675cd2200 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterGroup.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterGroup.java
        @@ -17,11 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.List;
        -
         import lombok.Data;
         
         @Data
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterType.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterType.java
        index 3f6dc9f7ce..0a1bd4fa02 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterType.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ParameterType.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import lombok.AllArgsConstructor;
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PolicyTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PolicyTypes.java
        index 77a7cd4552..c8f7d96925 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PolicyTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PolicyTypes.java
        @@ -17,13 +17,11 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.HashMap;
         import java.util.Map;
         import java.util.Objects;
        -
         import lombok.AllArgsConstructor;
         import lombok.Getter;
         
        @@ -32,7 +30,6 @@ import lombok.Getter;
         public enum PolicyTypes {
             AFFINITY("affinity"),
             ANTI_AFFINITY("anti-affinity");
        -
             private static Map stringToPolicyTypesMap;
         
             static {
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PropertiesMapKeyTypes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PropertiesMapKeyTypes.java
        index 46673c2eaa..1f6493ae1d 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PropertiesMapKeyTypes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/PropertiesMapKeyTypes.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import lombok.AllArgsConstructor;
        @@ -26,10 +25,6 @@ import lombok.Getter;
         @Getter
         @AllArgsConstructor
         public enum PropertiesMapKeyTypes {
        -    IMAGE("image"),
        -    FLAVOR("flavor"),
        -    NETWORKS("networks"),
        -    RESOURCE_DEF("resource_def");
        -
        +    IMAGE("image"), FLAVOR("flavor"), NETWORKS("networks"), RESOURCE_DEF("resource_def");
             private String keyMap;
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Resource.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Resource.java
        index 4703f43632..a756d35c03 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Resource.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/Resource.java
        @@ -17,11 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.Map;
        -
         import lombok.Data;
         
         @Data
        @@ -36,13 +34,7 @@ public class Resource {
         
             @Override
             public String toString() {
        -        return "Resource{"
        -                + "type='" + type + '\''
        -                + ", properties=" + properties
        -                + ", metadata=" + metadata
        -                + ", depends_on=" + depends_on
        -                + ", update_policy='" + update_policy + '\''
        -                + ", deletion_policy='" + deletion_policy + '\''
        -                + '}';
        +        return "Resource{" + "type='" + type + '\'' + ", properties=" + properties + ", metadata=" + metadata + ", depends_on=" + depends_on
        +            + ", update_policy='" + update_policy + '\'' + ", deletion_policy='" + deletion_policy + '\'' + '}';
             }
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceReferenceFunctions.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceReferenceFunctions.java
        index 9c1feb2cc4..f86e53ba15 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceReferenceFunctions.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceReferenceFunctions.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import lombok.AllArgsConstructor;
        @@ -26,11 +25,6 @@ import lombok.Getter;
         @AllArgsConstructor
         @Getter
         public enum ResourceReferenceFunctions {
        -    GET_RESOURCE("get_resource"),
        -    GET_PARAM("get_param"),
        -    GET_ATTR("get_attr"),
        -    GET_FILE("get_file"),
        -    SCHEDULER_HINTS("scheduler_hints");
        -
        +    GET_RESOURCE("get_resource"), GET_PARAM("get_param"), GET_ATTR("get_attr"), GET_FILE("get_file"), SCHEDULER_HINTS("scheduler_hints");
             private String function;
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceTypeToMessageString.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceTypeToMessageString.java
        index c4a13588a1..574e510082 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceTypeToMessageString.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/model/ResourceTypeToMessageString.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.model;
         
         import java.util.HashMap;
        @@ -34,9 +33,9 @@ public enum ResourceTypeToMessageString {
                 resourcesTypesStringMap = new HashMap<>();
         
                 for (ResourceTypeToMessageString resourceTypeToMessageString : ResourceTypeToMessageString
        -                .values()) {
        +            .values()) {
                     resourcesTypesStringMap
        -                    .put(resourceTypeToMessageString.type, resourceTypeToMessageString.messageString);
        +                .put(resourceTypeToMessageString.type, resourceTypeToMessageString.messageString);
                 }
             }
         
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/Artifact.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/Artifact.java
        index 9d1fbe3cb3..ce8c15953d 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/Artifact.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/Artifact.java
        @@ -17,12 +17,10 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.structure;
         
         import java.util.ArrayList;
         import java.util.List;
        -
         import lombok.AccessLevel;
         import lombok.EqualsAndHashCode;
         import lombok.Getter;
        @@ -36,11 +34,9 @@ import org.openecomp.sdc.heat.datatypes.manifest.FileData;
         public class Artifact implements Comparable {
         
             private String fileName;
        -
             @Setter(AccessLevel.NONE)
             @EqualsAndHashCode.Exclude
             private FileData.Type type;
        -
             @EqualsAndHashCode.Exclude
             private List errors;
         
        @@ -58,7 +54,6 @@ public class Artifact implements Comparable {
                 if (this.errors == null || this.errors.isEmpty()) {
                     this.errors = new ArrayList<>();
                 }
        -
                 this.errors.add(error);
             }
         
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/HeatStructureTree.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/HeatStructureTree.java
        index 93eb7c649d..893f5f58d3 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/HeatStructureTree.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/HeatStructureTree.java
        @@ -19,7 +19,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.structure;
         
         import java.util.ArrayList;
        @@ -38,11 +37,9 @@ public class HeatStructureTree implements Comparable {
         
             private String fileName;
             private FileData.Type type;
        -
             @Getter(AccessLevel.NONE)
             @Setter(AccessLevel.NONE)
             private Boolean isBase;
        -
             private HeatStructureTree env;
             private List errors;
             private Set heat;
        @@ -63,14 +60,6 @@ public class HeatStructureTree implements Comparable {
                 this.fileName = fileName;
             }
         
        -    public Boolean getBase() {
        -        return isBase;
        -    }
        -
        -    public void setBase(Boolean isBase) {
        -        this.isBase = isBase;
        -    }
        -
             /**
              * Gets heat structure tree by name.
              *
        @@ -78,17 +67,23 @@ public class HeatStructureTree implements Comparable {
              * @param filename the filename
              * @return the heat structure tree by name
              */
        -    public static HeatStructureTree getHeatStructureTreeByName(Set filesSet,
        -        String filename) {
        +    public static HeatStructureTree getHeatStructureTreeByName(Set filesSet, String filename) {
                 for (HeatStructureTree heatStructureTree : filesSet) {
                     if (heatStructureTree.getFileName().equals(filename)) {
                         return heatStructureTree;
                     }
                 }
        -
                 return null;
             }
         
        +    public Boolean getBase() {
        +        return isBase;
        +    }
        +
        +    public void setBase(Boolean isBase) {
        +        this.isBase = isBase;
        +    }
        +
             /**
              * Add heat structure tree to nested heat list.
              *
        @@ -152,7 +147,6 @@ public class HeatStructureTree implements Comparable {
                 if (this.heat == null) {
                     this.heat = new TreeSet<>();
                 }
        -
                 this.heat.add(heat);
             }
         
        @@ -165,7 +159,6 @@ public class HeatStructureTree implements Comparable {
                 if (this.other == null) {
                     this.other = new TreeSet<>();
                 }
        -
                 this.other.add(other);
             }
         
        @@ -173,7 +166,6 @@ public class HeatStructureTree implements Comparable {
                 if (this.helm == null) {
                     this.helm = new TreeSet<>();
                 }
        -
                 this.helm.add(helm);
             }
         
        @@ -200,10 +192,8 @@ public class HeatStructureTree implements Comparable {
              * @param type             the type
              */
             public void removeFromVolumeOrNetwork(String fileNameToRemove, FileData.Type type) {
        -        Set volumeOrNetworkSet =
        -            type.equals(FileData.Type.HEAT_VOL) ? this.volume : this.network;
        +        Set volumeOrNetworkSet = type.equals(FileData.Type.HEAT_VOL) ? this.volume : this.network;
                 HeatStructureTree toRemove = getHeatStructureTreeByName(volumeOrNetworkSet, fileNameToRemove);
        -
                 volumeOrNetworkSet.remove(toRemove);
             }
         
        @@ -217,7 +207,6 @@ public class HeatStructureTree implements Comparable {
                 result1 = 31 * result1 + (artifacts != null ? artifacts.hashCode() : 0);
                 result1 = 31 * result1 + (nested != null ? nested.hashCode() : 0);
                 result1 = 31 * result1 + (errors != null ? errors.hashCode() : 0);
        -
                 return result1;
             }
         
        @@ -229,11 +218,8 @@ public class HeatStructureTree implements Comparable {
                 if (other == null || getClass() != other.getClass()) {
                     return false;
                 }
        -
                 HeatStructureTree heatStructureTree = (HeatStructureTree) other;
        -
        -        if (fileName != null ? !fileName.equals(heatStructureTree.fileName)
        -            : heatStructureTree.fileName != null) {
        +        if (fileName != null ? !fileName.equals(heatStructureTree.fileName) : heatStructureTree.fileName != null) {
                     return false;
                 }
                 if (env != null ? !env.equals(heatStructureTree.env) : heatStructureTree.env != null) {
        @@ -242,23 +228,18 @@ public class HeatStructureTree implements Comparable {
                 if (heat != null ? !heat.equals(heatStructureTree.heat) : heatStructureTree.heat != null) {
                     return false;
                 }
        -        if (volume != null ? !volume.equals(heatStructureTree.volume)
        -            : heatStructureTree.volume != null) {
        +        if (volume != null ? !volume.equals(heatStructureTree.volume) : heatStructureTree.volume != null) {
                     return false;
                 }
        -        if (network != null ? !network.equals(heatStructureTree.network)
        -            : heatStructureTree.network != null) {
        +        if (network != null ? !network.equals(heatStructureTree.network) : heatStructureTree.network != null) {
                     return false;
                 }
        -        if (artifacts != null ? !artifacts.equals(heatStructureTree.artifacts)
        -            : heatStructureTree.artifacts != null) {
        +        if (artifacts != null ? !artifacts.equals(heatStructureTree.artifacts) : heatStructureTree.artifacts != null) {
                     return false;
                 }
        -        if (nested != null ? !nested.equals(heatStructureTree.nested)
        -            : heatStructureTree.nested != null) {
        +        if (nested != null ? !nested.equals(heatStructureTree.nested) : heatStructureTree.nested != null) {
                     return false;
                 }
        -
                 return errors != null ? errors.equals(heatStructureTree.errors) : heatStructureTree.errors == null;
             }
         
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/ValidationStructureList.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/ValidationStructureList.java
        index 27b87b9045..d23f6e5af5 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/ValidationStructureList.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/datatypes/structure/ValidationStructureList.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.datatypes.structure;
         
         import lombok.AllArgsConstructor;
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/ErrorCodes.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/ErrorCodes.java
        index e239d225e8..8e7d398170 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/ErrorCodes.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/ErrorCodes.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.services;
         
        -
         public class ErrorCodes {
        -  public static final String INVALID_BOOLEAN = "INVALID_BOOLEAN";
        +
        +    public static final String INVALID_BOOLEAN = "INVALID_BOOLEAN";
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatConstants.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatConstants.java
        index 1e917ea4cd..7d4033e552 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatConstants.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatConstants.java
        @@ -13,14 +13,12 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.heat.services;
         
        -
         public class HeatConstants {
        +
             public static final String GET_ATTR_FROM_RESOURCE_GROUP_PREFIX = "resource.";
             public static final String RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE = "%index%";
        -
             public static final String INDEX_PROPERTY_NAME = "index_var";
             public static final String SERVICE_SCALING_PROPERTY_NAME = "service_scaling";
             public static final String INSTANCE_UUID_PROPERTY_NAME = "instance_uuid";
        @@ -32,13 +30,11 @@ public class HeatConstants {
             public static final String VIRTUAL_NETWORK_PROPERTY_NAME = "virtual_network";
             public static final String BLOCK_DEVICE_MAPPING = "block_device_mapping";
             public static final String BLOCK_DEVICE_MAPPING_V2 = "block_device_mapping_v2";
        -    public static final String VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME
        -            = "virtual_machine_interface_properties_sub_interface_vlan_tag";
        +    public static final String VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME = "virtual_machine_interface_properties_sub_interface_vlan_tag";
             public static final String VMI_PROPERTIES_PROPERTY_NAME = "virtual_machine_interface_properties";
             public static final String VMI_REFS_PROPERTY_NAME = "virtual_machine_interface_refs";
             public static final String VMI_MAC_ADDRESSES = "virtual_machine_interface_mac_addresses";
        -    public static final String VMI_MAC_ADDRESSES_MAC_ADDRESSES =
        -            "virtual_machine_interface_mac_addresses#virtual_machine_interface_mac_addresses_mac_address";
        +    public static final String VMI_MAC_ADDRESSES_MAC_ADDRESSES = "virtual_machine_interface_mac_addresses#virtual_machine_interface_mac_addresses_mac_address";
             public static final String VIRTUAL_NETWORK_REFS_PROPERTY_NAME = "virtual_network_refs";
             public static final String READ_ONLY_PROPERTY_NAME = "read_only";
             public static final String VOL_ID_PROPERTY_NAME = "volume_id";
        @@ -48,8 +44,7 @@ public class HeatConstants {
             public static final String ORDERED_INTERFACES_PROPERTY_NAME = "ordered_interfaces";
             public static final String SHARED_IP_LIST_PROPERTY_NAME = "shared_ip_list";
             public static final String STATIC_ROUTES_LIST_PROPERTY_NAME = "static_routes_list";
        -    public static final String SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME =
        -            "service_interface_type_list";
        +    public static final String SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME = "service_interface_type_list";
             public static final String PORT_SECURITY_ENABLED_PROPERTY_NAME = "port_security_enabled";
             public static final String SHARED_PROPERTY_NAME = "shared";
             public static final String ADMIN_STATE_UP_PROPERTY_NAME = "admin_state_up";
        @@ -70,5 +65,4 @@ public class HeatConstants {
             private HeatConstants() {
                 //Hide the implicit constructor
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatResourceUtil.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatResourceUtil.java
        index 4563e686e5..fa8845e382 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatResourceUtil.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatResourceUtil.java
        @@ -13,14 +13,12 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.heat.services;
         
         import java.util.Objects;
         import java.util.Optional;
         import java.util.regex.Matcher;
         import java.util.regex.Pattern;
        -
         import lombok.AllArgsConstructor;
         import lombok.Getter;
         import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
        @@ -30,36 +28,26 @@ public class HeatResourceUtil {
             private static final String UNDERSCORE = "_";
             private static final String WORDS_REGEX = "(\\w+)";
             private static final String PORT_RESOURCE_ID_REGEX_SUFFIX = "(_\\d+)*";
        -    private static final String PORT_RESOURCE_ID_REGEX_PREFIX =
        -            WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX;
        -    private static final String PORT_INT_RESOURCE_ID_REGEX_PREFIX = PORT_RESOURCE_ID_REGEX_PREFIX
        -            + UNDERSCORE + "int_" + WORDS_REGEX + UNDERSCORE;
        +    private static final String PORT_RESOURCE_ID_REGEX_PREFIX = WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX;
        +    private static final String PORT_INT_RESOURCE_ID_REGEX_PREFIX = PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "int_" + WORDS_REGEX + UNDERSCORE;
             private static final String SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX =
        -            PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "subint_" + WORDS_REGEX + UNDERSCORE;
        +        PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "subint_" + WORDS_REGEX + UNDERSCORE;
         
        -    public static Optional evaluateNetworkRoleFromResourceId(String resourceId,
        -                                                                     String resourceType) {
        +    public static Optional evaluateNetworkRoleFromResourceId(String resourceId, String resourceType) {
                 Optional portType = getPortType(resourceType);
                 if (portType.isPresent()) {
        -            String portResourceIdRegex =
        -                    PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + WORDS_REGEX + UNDERSCORE
        -                            + portType.get().getPortTypeName() + PORT_RESOURCE_ID_REGEX_SUFFIX;
        -            String portIntResourceIdRegex =
        -                    PORT_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
        -                            + PORT_RESOURCE_ID_REGEX_SUFFIX;
        -
        +            String portResourceIdRegex = PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + WORDS_REGEX + UNDERSCORE + portType.get().getPortTypeName()
        +                + PORT_RESOURCE_ID_REGEX_SUFFIX;
        +            String portIntResourceIdRegex = PORT_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName() + PORT_RESOURCE_ID_REGEX_SUFFIX;
                     String portNetworkRole = getNetworkRole(resourceId, portResourceIdRegex);
                     String portIntNetworkRole = getNetworkRole(resourceId, portIntResourceIdRegex);
        -
        -            return Optional.ofNullable(Objects.nonNull(portNetworkRole)
        -                    ? portNetworkRole : portIntNetworkRole);
        +            return Optional.ofNullable(Objects.nonNull(portNetworkRole) ? portNetworkRole : portIntNetworkRole);
                 }
                 return Optional.empty();
             }
         
             private static Optional getPortType(String resourceType) {
        -        if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()
        -                .equals(resourceType)) {
        +        if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource().equals(resourceType)) {
                     return Optional.of(PortType.VMI);
                 } else if (HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource().equals(resourceType)) {
                     return Optional.of(PortType.PORT);
        @@ -74,28 +62,16 @@ public class HeatResourceUtil {
              * @param resourceType the resource type
              * @return the optional
              */
        -    public static Optional extractNetworkRoleFromSubInterfaceId(String resourceId,
        -                                                                        String resourceType) {
        +    public static Optional extractNetworkRoleFromSubInterfaceId(String resourceId, String resourceType) {
                 Optional portType = getPortType(resourceType);
                 if (portType.isPresent()) {
                     String subInterfaceResourceIdRegex =
        -                    SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
        -                            + PORT_RESOURCE_ID_REGEX_SUFFIX;
        -
        +                SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName() + PORT_RESOURCE_ID_REGEX_SUFFIX;
                     return Optional.ofNullable(getNetworkRole(resourceId, subInterfaceResourceIdRegex));
                 }
                 return Optional.empty();
             }
         
        -    @AllArgsConstructor
        -    @Getter
        -    private enum PortType {
        -        PORT("port"),
        -        VMI("vmi");
        -
        -        private String portTypeName;
        -    }
        -
             private static String getNetworkRole(String portResourceId, String portIdRegex) {
                 Pattern pattern = Pattern.compile(portIdRegex);
                 Matcher matcher = pattern.matcher(portResourceId);
        @@ -109,4 +85,10 @@ public class HeatResourceUtil {
                 return null;
             }
         
        +    @AllArgsConstructor
        +    @Getter
        +    private enum PortType {
        +        PORT("port"), VMI("vmi");
        +        private String portTypeName;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatStructureUtil.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatStructureUtil.java
        index b73c7e8b8b..cc239751a8 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatStructureUtil.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/HeatStructureUtil.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.services;
         
         import java.util.HashSet;
        @@ -25,7 +24,6 @@ import java.util.List;
         import java.util.Map;
         import java.util.Objects;
         import java.util.Set;
        -
         import org.apache.commons.collections4.CollectionUtils;
         import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
         import org.openecomp.core.validation.types.GlobalValidationContext;
        @@ -51,63 +49,50 @@ public class HeatStructureUtil {
              * @param globalContext the global context
              * @return the referenced values by function name
              */
        -    public static Set getReferencedValuesByFunctionName(String filename, String functionName,
        -                                                                Object propertyValue,
        +    public static Set getReferencedValuesByFunctionName(String filename, String functionName, Object propertyValue,
                                                                         GlobalValidationContext globalContext) {
                 Set valuesNames = new HashSet<>();
                 if (propertyValue instanceof Map) {
                     Map currPropertyMap = (Map) propertyValue;
                     if (currPropertyMap.containsKey(functionName)) {
                         Object getFunctionValue = currPropertyMap.get(functionName);
        -                if (!(getFunctionValue instanceof String) && functionName.equals(
        -                        ResourceReferenceFunctions.GET_RESOURCE.getFunction())) {
        +                if (!(getFunctionValue instanceof String) && functionName.equals(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) {
                             globalContext.addMessage(filename, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
        -                            .getErrorWithParameters(globalContext.getMessageCode(),
        -                                    Messages.INVALID_GET_RESOURCE_SYNTAX.getErrorMessage(),
        -                                    getFunctionValue == null ? "null" : getFunctionValue.toString()));
        +                        .getErrorWithParameters(globalContext.getMessageCode(), Messages.INVALID_GET_RESOURCE_SYNTAX.getErrorMessage(),
        +                            getFunctionValue == null ? "null" : getFunctionValue.toString()));
                             return valuesNames;
                         }
                         if (getFunctionValue instanceof String) {
        -
                             if (functionName.equals(ResourceReferenceFunctions.GET_FILE.getFunction())) {
                                 getFunctionValue = ((String) getFunctionValue).replace("file:///", "");
                             }
        -
                             valuesNames.add((String) getFunctionValue);
                         } else if (getFunctionValue instanceof List) {
                             if (CollectionUtils.isNotEmpty((List) getFunctionValue)) {
                                 if (((List) getFunctionValue).get(0) instanceof String) {
                                     valuesNames.add(((String) ((List) getFunctionValue).get(0)).replace("file:///", ""));
                                 } else {
        -                            valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName,
        -                                    ((List) getFunctionValue).get(0), globalContext));
        +                            valuesNames
        +                                .addAll(getReferencedValuesByFunctionName(filename, functionName, ((List) getFunctionValue).get(0), globalContext));
                                 }
        -
                             }
                         } else {
        -                    valuesNames.addAll(
        -                            getReferencedValuesByFunctionName(filename, functionName, getFunctionValue,
        -                                    globalContext));
        +                    valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName, getFunctionValue, globalContext));
                         }
                     } else {
                         for (Map.Entry nestedPropertyMap : currPropertyMap.entrySet()) {
        -                    valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName,
        -                            nestedPropertyMap.getValue(), globalContext));
        +                    valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName, nestedPropertyMap.getValue(), globalContext));
                         }
                     }
                 } else if (propertyValue instanceof List) {
                     List propertyValueArray = (List) propertyValue;
                     for (Object propValue : propertyValueArray) {
        -                valuesNames.addAll(
        -                        getReferencedValuesByFunctionName(filename, functionName, propValue,
        -                                globalContext));
        +                valuesNames.addAll(getReferencedValuesByFunctionName(filename, functionName, propValue, globalContext));
                     }
                 }
        -
                 return valuesNames;
             }
         
        -
             /**
              * Is nested resource.
              *
        @@ -120,5 +105,4 @@ public class HeatStructureUtil {
                 }
                 return resourceType.endsWith(".yaml") || resourceType.endsWith(".yml");
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/manifest/ManifestUtil.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/manifest/ManifestUtil.java
        index 8c6daac71e..65afb4bab2 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/manifest/ManifestUtil.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/manifest/ManifestUtil.java
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.heat.services.manifest;
         
         import java.util.HashMap;
        @@ -25,14 +24,12 @@ import java.util.HashSet;
         import java.util.List;
         import java.util.Map;
         import java.util.Set;
        -
         import org.apache.commons.collections4.CollectionUtils;
         import org.openecomp.sdc.heat.datatypes.manifest.FileData;
         import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
         
         public class ManifestUtil {
         
        -
             /**
              * Gets file and its env.
              *
        @@ -45,7 +42,6 @@ public class ManifestUtil {
                 return fileEnvMap;
             }
         
        -
             /**
              * Scan file env map.
              *
        @@ -53,13 +49,10 @@ public class ManifestUtil {
              * @param fileDataList the file data list
              * @param fileEnvMap   the file env map
              */
        -    private static void scanFileEnvMap(FileData fileData, List fileDataList,
        -                                      Map fileEnvMap) {
        -
        +    private static void scanFileEnvMap(FileData fileData, List fileDataList, Map fileEnvMap) {
                 if (CollectionUtils.isEmpty(fileDataList)) {
                     return;
                 }
        -
                 for (FileData childFileData : fileDataList) {
                     FileData.Type childType = childFileData.getType();
                     if (fileData != null) {
        @@ -71,7 +64,6 @@ public class ManifestUtil {
                 }
             }
         
        -
             /**
              * Gets file type map.
              *
        @@ -84,15 +76,13 @@ public class ManifestUtil {
                 return fileTypeMap;
             }
         
        -    private static FileData.Type scanFileTypeMap(FileData fileData, List data,
        -                                                 Map fileTypeMap) {
        +    private static FileData.Type scanFileTypeMap(FileData fileData, List data, Map fileTypeMap) {
                 if (fileData != null) {
                     fileTypeMap.put(fileData.getFile(), fileData.getType());
                 }
                 if (data == null) {
                     return null;
                 }
        -
                 for (FileData chileFileData : data) {
                     FileData.Type type = scanFileTypeMap(chileFileData, chileFileData.getData(), fileTypeMap);
                     if (type != null) {
        @@ -102,7 +92,6 @@ public class ManifestUtil {
                 return null;
             }
         
        -
             /**
              * Gets artifacts.
              *
        @@ -112,7 +101,6 @@ public class ManifestUtil {
             public static Set getArtifacts(ManifestContent manifestContent) {
                 Set artifacts = new HashSet<>();
                 scanArtifacts(null, manifestContent.getData(), artifacts);
        -
                 return artifacts;
             }
         
        @@ -122,22 +110,18 @@ public class ManifestUtil {
                         artifacts.add(fileData.getFile());
                     }
                 }
        -
                 if (data == null) {
                     return;
                 }
        -
                 for (FileData chileFileData : data) {
                     scanArtifacts(chileFileData, chileFileData.getData(), artifacts);
                 }
             }
         
             private static boolean isArtifact(FileData fileData) {
        -        return FileData.Type.valueOf(fileData.getType().name()) != null
        -                && !fileData.getType().equals(FileData.Type.HEAT)
        -                && !fileData.getType().equals(FileData.Type.HEAT_ENV)
        -                && !fileData.getType().equals(FileData.Type.HEAT_NET)
        -                && !fileData.getType().equals(FileData.Type.HEAT_VOL);
        +        return FileData.Type.valueOf(fileData.getType().name()) != null && !fileData.getType().equals(FileData.Type.HEAT) && !fileData.getType()
        +            .equals(FileData.Type.HEAT_ENV) && !fileData.getType().equals(FileData.Type.HEAT_NET) && !fileData.getType()
        +            .equals(FileData.Type.HEAT_VOL);
             }
         
             /**
        @@ -158,11 +142,9 @@ public class ManifestUtil {
                         baseFiles.add(fileData.getFile());
                     }
                 }
        -
                 if (data == null) {
                     return;
                 }
        -
                 for (FileData chileFileData : data) {
                     scanBase(chileFileData, chileFileData.getData(), baseFiles);
                 }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManager.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManager.java
        index b441fc8660..2907b73ccb 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManager.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManager.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.heat.services.tree;
         
         import java.io.InputStream;
        @@ -23,7 +22,6 @@ import java.util.List;
         import java.util.Map;
         import java.util.Objects;
         import java.util.Set;
        -
         import org.onap.sdc.tosca.services.YamlUtil;
         import org.openecomp.core.utilities.file.FileContentHandler;
         import org.openecomp.core.utilities.file.FileUtils;
        @@ -39,12 +37,9 @@ import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -
         public class HeatTreeManager {
         
             private static final Logger LOGGER = LoggerFactory.getLogger(HeatTreeManager.class);
        -
        -
             private FileContentHandler heatContentMap = new FileContentHandler();
             private byte[] manifest;
             private HeatStructureTree tree = new HeatStructureTree();
        @@ -65,7 +60,6 @@ public class HeatTreeManager {
             public void addFile(String fileName, InputStream content) {
                 if (fileName.equals(SdcCommon.MANIFEST_NAME)) {
                     manifest = FileUtils.toByteArray(content);
        -
                 } else {
                     heatContentMap.addFile(fileName, content);
                 }
        @@ -79,25 +73,19 @@ public class HeatTreeManager {
                     LOGGER.error("Missing manifest file in the zip.");
                     return;
                 }
        -        ManifestContent manifestData =
        -                JsonUtil.json2Object(new String(manifest), ManifestContent.class);
        +        ManifestContent manifestData = JsonUtil.json2Object(new String(manifest), ManifestContent.class);
                 scanTree(null, manifestData.getData());
                 addNonNestedVolumeNetworkToTree(volumeFileToParent, nestedFiles.keySet(), true);
                 addNonNestedVolumeNetworkToTree(networkFileToParent, nestedFiles.keySet(), false);
                 handleOrphans();
        -
                 tree = fileTreeRef.get(SdcCommon.PARENT);
             }
         
             private void handleOrphans() {
                 tree = fileTreeRef.get(SdcCommon.PARENT);
                 candidateOrphanArtifacts.forEach((key, value) -> tree.addArtifactToArtifactList(value));
        -        nestedFiles
        -                .values().stream().filter(tree.getHeat()::contains)
        -                .forEach(tree.getHeat()::remove);
        -
        -        heatContentMap.getFileList().stream().filter(this::isNotInManifestFiles)
        -                .forEach(this::addTreeOther);
        +        nestedFiles.values().stream().filter(tree.getHeat()::contains).forEach(tree.getHeat()::remove);
        +        heatContentMap.getFileList().stream().filter(this::isNotInManifestFiles).forEach(this::addTreeOther);
             }
         
             private boolean isNotInManifestFiles(String fileName) {
        @@ -113,18 +101,12 @@ public class HeatTreeManager {
                 tree.getOther().add(other);
             }
         
        -
        -    private void handleHeatContentReference(HeatStructureTree fileHeatStructureTree,
        -                                            GlobalValidationContext globalContext) {
        -
        +    private void handleHeatContentReference(HeatStructureTree fileHeatStructureTree, GlobalValidationContext globalContext) {
                 String fileName = fileHeatStructureTree.getFileName();
                 try (InputStream fileContent = this.heatContentMap.getFileContentAsStream(fileName)) {
        -            HeatOrchestrationTemplate hot =
        -                    new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class);
        -
        +            HeatOrchestrationTemplate hot = new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class);
                     Set nestedSet = HeatTreeManagerUtil.getNestedFiles(hot);
                     addHeatNestedFiles(fileHeatStructureTree, nestedSet);
        -
                     Set artifactSet = HeatTreeManagerUtil.getArtifactFiles(fileName, hot, globalContext);
                     addHeatArtifactFiles(fileHeatStructureTree, artifactSet);
                 } catch (Exception exp) {
        @@ -132,14 +114,10 @@ public class HeatTreeManager {
                 }
             }
         
        -
        -    private void addHeatArtifactFiles(HeatStructureTree fileHeatStructureTree,
        -                                      Set artifactSet) {
        +    private void addHeatArtifactFiles(HeatStructureTree fileHeatStructureTree, Set artifactSet) {
                 Artifact artifact;
                 for (String artifactName : artifactSet) {
        -            FileData.Type type =
        -                    candidateOrphanArtifacts.get(artifactName) != null ? candidateOrphanArtifacts
        -                            .get(artifactName).getType() : null;
        +            FileData.Type type = candidateOrphanArtifacts.get(artifactName) != null ? candidateOrphanArtifacts.get(artifactName).getType() : null;
                     artifact = new Artifact(artifactName, type);
                     artifactRef.put(artifactName, artifact);
                     candidateOrphanArtifacts.remove(artifactName);
        @@ -147,7 +125,6 @@ public class HeatTreeManager {
                 }
             }
         
        -
             private void addHeatNestedFiles(HeatStructureTree fileHeatStructureTree, Set nestedSet) {
                 HeatStructureTree childHeatStructureTree;
                 for (String nestedName : nestedSet) {
        @@ -162,22 +139,16 @@ public class HeatTreeManager {
                 }
             }
         
        -
             /**
              * Add errors.
              *
              * @param validationErrors the validation errors
              */
             public void addErrors(Map> validationErrors) {
        -
        -        validationErrors.entrySet().stream()
        -                .filter(entry -> fileTreeRef.get(entry.getKey()) != null)
        -                .forEach(entry -> entry.getValue().forEach(fileTreeRef.get(entry.getKey())::addErrorToErrorsList));
        -
        -        validationErrors.entrySet().stream()
        -                .filter(entry -> artifactRef.get(entry.getKey()) != null)
        -                .forEach(entry -> artifactRef.get(entry.getKey()).setErrors(entry.getValue()));
        -
        +        validationErrors.entrySet().stream().filter(entry -> fileTreeRef.get(entry.getKey()) != null)
        +            .forEach(entry -> entry.getValue().forEach(fileTreeRef.get(entry.getKey())::addErrorToErrorsList));
        +        validationErrors.entrySet().stream().filter(entry -> artifactRef.get(entry.getKey()) != null)
        +            .forEach(entry -> artifactRef.get(entry.getKey()).setErrors(entry.getValue()));
             }
         
             /**
        @@ -200,12 +171,10 @@ public class HeatTreeManager {
                 } else {
                     parentHeatStructureTree = fileTreeRef.get(parent);
                 }
        -
                 for (FileData fileData : data) {
                     fileName = fileData.getFile();
                     manifestFiles.add(fileName);
                     type = fileData.getType();
        -
                     if (Objects.nonNull(type) && FileData.Type.HEAT.equals(type)) {
                         fileHeatStructureTree = fileTreeRef.get(fileName);
                         if (fileHeatStructureTree == null) {
        @@ -226,7 +195,6 @@ public class HeatTreeManager {
                         childHeatStructureTree.setBase(fileData.getBase());
                         childHeatStructureTree.setType(type);
                         fileTreeRef.put(childHeatStructureTree.getFileName(), childHeatStructureTree);
        -
                         if (type == null) {
                             parentHeatStructureTree.addOtherToOtherList(childHeatStructureTree);
                         } else if (FileData.Type.HEAT_NET.equals(type)) {
        @@ -235,7 +203,6 @@ public class HeatTreeManager {
                                 scanTree(fileName, fileData.getData());
                             }
                             handleHeatContentReference(childHeatStructureTree, null);
        -
                         } else if (FileData.Type.HEAT_VOL.equals(type)) {
                             volumeFileToParent.put(childHeatStructureTree, parentHeatStructureTree);
                             if (fileData.getData() != null) {
        @@ -253,8 +220,7 @@ public class HeatTreeManager {
                             }
                         } else if (FileData.Type.HELM.equals(type)) {
                             parentHeatStructureTree.addToHelmList(childHeatStructureTree);
        -                    }
        -                else {
        +                } else {
                             artifact = new Artifact(fileName, type);
                             if (!artifactRef.keySet().contains(fileName)) {
                                 artifactRef.put(fileName, artifact);
        @@ -265,10 +231,8 @@ public class HeatTreeManager {
                 }
             }
         
        -
        -    private void addNonNestedVolumeNetworkToTree(
        -            Map netVolToParent, Set nestedFileNames,
        -            boolean isVolume) {
        +    private void addNonNestedVolumeNetworkToTree(Map netVolToParent, Set nestedFileNames,
        +                                                 boolean isVolume) {
                 for (Map.Entry entry : netVolToParent.entrySet()) {
                     HeatStructureTree netOrVolNode = entry.getKey();
                     HeatStructureTree parent = entry.getValue();
        @@ -282,7 +246,6 @@ public class HeatTreeManager {
                 }
             }
         
        -
             public HeatStructureTree getTree() {
                 return tree;
             }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerUtil.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerUtil.java
        index 9970a4d74c..43bc3f80a9 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerUtil.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerUtil.java
        @@ -13,8 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
        -
         package org.openecomp.sdc.heat.services.tree;
         
         import java.util.Collection;
        @@ -23,7 +21,6 @@ import java.util.HashSet;
         import java.util.Map;
         import java.util.Objects;
         import java.util.Set;
        -
         import org.apache.commons.collections4.CollectionUtils;
         import org.apache.commons.collections4.MapUtils;
         import org.openecomp.core.utilities.file.FileContentHandler;
        @@ -42,7 +39,6 @@ public class HeatTreeManagerUtil {
             private static final String TYPE = "type";
         
             private HeatTreeManagerUtil() {
        -
             }
         
             /**
        @@ -52,11 +48,8 @@ public class HeatTreeManagerUtil {
              * @return the heat tree manager
              */
             public static HeatTreeManager initHeatTreeManager(FileContentHandler fileContentMap) {
        -
                 HeatTreeManager heatTreeManager = new HeatTreeManager();
        -        fileContentMap.getFileList().forEach(
        -                fileName -> heatTreeManager.addFile(fileName, fileContentMap.getFileContentAsStream(fileName)));
        -
        +        fileContentMap.getFileList().forEach(fileName -> heatTreeManager.addFile(fileName, fileContentMap.getFileContentAsStream(fileName)));
                 return heatTreeManager;
             }
         
        @@ -68,10 +61,8 @@ public class HeatTreeManagerUtil {
              */
             public static Set getNestedFiles(HeatOrchestrationTemplate hot) {
                 Set nestedFileList = new HashSet<>();
        -        hot.getResources().values().stream().filter(
        -                resource -> resource.getType().endsWith(".yaml") || resource.getType().endsWith(".yml"))
        -                .forEach(resource -> nestedFileList.add(resource.getType()));
        -
        +        hot.getResources().values().stream().filter(resource -> resource.getType().endsWith(".yaml") || resource.getType().endsWith(".yml"))
        +            .forEach(resource -> nestedFileList.add(resource.getType()));
                 Set resourceDefNestedFiles = getResourceDefNestedFiles(hot);
                 nestedFileList.addAll(resourceDefNestedFiles);
                 return nestedFileList;
        @@ -85,52 +76,36 @@ public class HeatTreeManagerUtil {
              * @param globalContext the global context
              * @return the artifact files name
              */
        -    public static Set getArtifactFiles(String filename, HeatOrchestrationTemplate hot,
        -                                               GlobalValidationContext globalContext) {
        +    public static Set getArtifactFiles(String filename, HeatOrchestrationTemplate hot, GlobalValidationContext globalContext) {
                 Set artifactSet = new HashSet<>();
        -        Collection resourcesValue =
        -                hot.getResources() == null ? null : hot.getResources().values();
        +        Collection resourcesValue = hot.getResources() == null ? null : hot.getResources().values();
                 if (CollectionUtils.isNotEmpty(resourcesValue)) {
                     for (Resource resource : resourcesValue) {
        -                Collection properties =
        -                        resource.getProperties() == null ? null : resource.getProperties().values();
        -
        -                artifactSet.addAll(getArtifactsFromPropertiesAndAddInArtifactSet(properties,
        -                        filename, globalContext));
        +                Collection properties = resource.getProperties() == null ? null : resource.getProperties().values();
        +                artifactSet.addAll(getArtifactsFromPropertiesAndAddInArtifactSet(properties, filename, globalContext));
                     }
                 }
                 return artifactSet;
             }
         
        -    private static Set getArtifactsFromPropertiesAndAddInArtifactSet(Collection properties,
        -                                                                             String filename,
        +    private static Set getArtifactsFromPropertiesAndAddInArtifactSet(Collection properties, String filename,
                                                                                      GlobalValidationContext globalContext) {
                 Set artifactSet = new HashSet<>();
                 if (CollectionUtils.isNotEmpty(properties)) {
        -
                     for (Object property : properties) {
        -                Set artifactNames =
        -                        HeatStructureUtil.getReferencedValuesByFunctionName(filename, "get_file", property,
        -                                globalContext);
        +                Set artifactNames = HeatStructureUtil.getReferencedValuesByFunctionName(filename, "get_file", property, globalContext);
                         artifactSet.addAll(artifactNames);
                     }
                 }
        -
                 return artifactSet;
             }
         
             private static Set getResourceDefNestedFiles(HeatOrchestrationTemplate hot) {
                 Set resourceDefNestedFiles = new HashSet<>();
        -        hot.getResources()
        -                .entrySet().stream().filter(entry -> entry.getValue().getType()
        -                .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()))
        -                .filter(entry ->
        -                        getResourceDef(entry.getValue()) != null
        -                                && HeatStructureUtil.isNestedResource(
        -                                getResourceDef(entry.getValue())
        -                                        .getType()))
        -                .forEach(entry -> resourceDefNestedFiles.add(
        -                        getResourceDef(entry.getValue()).getType()));
        +        hot.getResources().entrySet().stream()
        +            .filter(entry -> entry.getValue().getType().equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())).filter(
        +            entry -> getResourceDef(entry.getValue()) != null && HeatStructureUtil.isNestedResource(getResourceDef(entry.getValue()).getType()))
        +            .forEach(entry -> resourceDefNestedFiles.add(getResourceDef(entry.getValue()).getType()));
                 return resourceDefNestedFiles;
             }
         
        @@ -144,8 +119,7 @@ public class HeatTreeManagerUtil {
             public static Resource getResourceDef(Resource resource) {
                 Resource resourceDef = null;
                 Map resourceDefValueMap = resource.getProperties() == null ? new HashMap<>()
        -                : (Map) resource.getProperties().get(
        -                        PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
        +            : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
                 if (MapUtils.isNotEmpty(resourceDefValueMap)) {
                     Object resourceDefType = resourceDefValueMap.get(TYPE);
                     if (resourceDefType instanceof String && isResourceGroupTypeNested((String) resourceDefType)) {
        @@ -154,43 +128,33 @@ public class HeatTreeManagerUtil {
                         //noinspection unchecked
                         resourceDef.setProperties((Map) resourceDefValueMap.get("properties"));
                     }
        -
                 }
                 return resourceDef;
             }
         
             @SuppressWarnings("unchecked")
        -    public static void checkResourceGroupTypeValid(String filename, String resourceName,
        -                                                   Resource resource,
        -                                                   GlobalValidationContext globalContext) {
        +    public static void checkResourceGroupTypeValid(String filename, String resourceName, Resource resource, GlobalValidationContext globalContext) {
                 Map resourceDefValueMap = resource.getProperties() == null ? new HashMap<>()
        -                : (Map) resource.getProperties().get(
        -                        PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
        +            : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
                 if (MapUtils.isNotEmpty(resourceDefValueMap)) {
                     Object resourceDefType = resourceDefValueMap.get(TYPE);
                     if (Objects.nonNull(resourceDefType) && !(resourceDefType instanceof String)) {
                         globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
        -                        .getErrorWithParameters(
        -                                globalContext.getMessageCode(),
        -                                Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(),
        -                                resourceName, resourceDefType.toString()));
        +                    .getErrorWithParameters(globalContext.getMessageCode(), Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(), resourceName,
        +                        resourceDefType.toString()));
                     }
                 }
             }
         
             @SuppressWarnings("unchecked")
        -    public static void checkResourceTypeValid(String filename, String resourceName,
        -                                              Resource resource,
        -                                              GlobalValidationContext globalContext) {
        +    public static void checkResourceTypeValid(String filename, String resourceName, Resource resource, GlobalValidationContext globalContext) {
                 Map resourceDefValueMap = resource.getProperties() == null ? new HashMap<>()
        -                : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
        +            : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
                 if (MapUtils.isNotEmpty(resourceDefValueMap)) {
                     Object resourceDefType = resourceDefValueMap.get(TYPE);
                     if (Objects.isNull(resourceDefType)) {
                         globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
        -                        .getErrorWithParameters(
        -                                globalContext.getMessageCode(), Messages.INVALID_RESOURCE_TYPE.getErrorMessage(),
        -                                "null", resourceName));
        +                    .getErrorWithParameters(globalContext.getMessageCode(), Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", resourceName));
                     }
                 }
             }
        @@ -199,20 +163,17 @@ public class HeatTreeManagerUtil {
                 return HeatStructureUtil.isNestedResource(resourceDefType);
             }
         
        -    public static boolean checkIfResourceGroupTypeIsNested(String filename, String resourceName,
        -                                                           Resource resource,
        +    public static boolean checkIfResourceGroupTypeIsNested(String filename, String resourceName, Resource resource,
                                                                    GlobalValidationContext globalContext) {
                 //noinspection unchecked
                 Map resourceDefValueMap = resource.getProperties() == null ? new HashMap<>()
        -                : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
        +            : (Map) resource.getProperties().get(PropertiesMapKeyTypes.RESOURCE_DEF.getKeyMap());
                 if (MapUtils.isNotEmpty(resourceDefValueMap)) {
                     Object resourceDefType = resourceDefValueMap.get(TYPE);
                     if (resourceDefType instanceof String && isResourceGroupTypeNested((String) resourceDefType)) {
                         globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
        -                        .getErrorWithParameters(
        -                                globalContext.getMessageCode(),
        -                                Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(),
        -                                resourceName, resourceDefType.toString()));
        +                    .getErrorWithParameters(globalContext.getMessageCode(), Messages.INVALID_RESOURCE_GROUP_TYPE.getErrorMessage(), resourceName,
        +                        resourceDefType.toString()));
                         return true;
                     }
                 }
        diff --git a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/ToscaTreeManager.java b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/ToscaTreeManager.java
        index 944ab62f9f..6957cb4fd6 100644
        --- a/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/ToscaTreeManager.java
        +++ b/openecomp-be/lib/openecomp-heat-lib/src/main/java/org/openecomp/sdc/heat/services/tree/ToscaTreeManager.java
        @@ -12,8 +12,7 @@
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
        -**/
        -
        + **/
         package org.openecomp.sdc.heat.services.tree;
         
         import java.io.File;
        @@ -22,7 +21,6 @@ import java.util.List;
         import java.util.Map;
         import java.util.Objects;
         import java.util.regex.Pattern;
        -
         import org.openecomp.core.utilities.file.FileContentHandler;
         import org.openecomp.sdc.common.utils.SdcCommon;
         import org.openecomp.sdc.datatypes.error.ErrorMessage;
        @@ -37,7 +35,6 @@ public class ToscaTreeManager {
             private HeatStructureTree tree = new HeatStructureTree();
             private Map fileTreeRef = new HashMap<>();
         
        -
             /**
              * Add file.
              *
        @@ -60,14 +57,12 @@ public class ToscaTreeManager {
                 }
             }
         
        -    private void addFileToTree(String[] splitFilename, int startIndex, String fullFileName,
        -                               HeatStructureTree parent) {
        +    private void addFileToTree(String[] splitFilename, int startIndex, String fullFileName, HeatStructureTree parent) {
                 fileTreeRef.putIfAbsent(fullFileName, new HeatStructureTree());
                 HeatStructureTree heatStructureTree = fileTreeRef.get(fullFileName);
                 heatStructureTree.setFileName(splitFilename[startIndex]);
                 if (startIndex < splitFilename.length - 1) {
        -            addFileToTree(splitFilename, startIndex + 1,
        -                    getFullFileName(fullFileName, splitFilename[startIndex + 1]), heatStructureTree);
        +            addFileToTree(splitFilename, startIndex + 1, getFullFileName(fullFileName, splitFilename[startIndex + 1]), heatStructureTree);
                 }
                 parent.addHeatStructureTreeToNestedHeatList(heatStructureTree);
             }
        @@ -78,9 +73,8 @@ public class ToscaTreeManager {
              * @param validationErrors the validation errors
              */
             public void addErrors(Map> validationErrors) {
        -        validationErrors.entrySet().stream().filter(entry ->
        -                Objects.nonNull(fileTreeRef.get(entry.getKey()))).forEach(entry -> entry.getValue()
        -                .forEach(error -> fileTreeRef.get(entry.getKey()).addErrorToErrorsList(error)));
        +        validationErrors.entrySet().stream().filter(entry -> Objects.nonNull(fileTreeRef.get(entry.getKey())))
        +            .forEach(entry -> entry.getValue().forEach(error -> fileTreeRef.get(entry.getKey()).addErrorToErrorsList(error)));
             }
         
             private String getFullFileName(String parentFullName, String fileName) {
        @@ -91,7 +85,6 @@ public class ToscaTreeManager {
                 if (filename.contains("/")) {
                     return filename.split("/");
                 }
        -
                 return filename.split(Pattern.quote(File.separator));
             }
         
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java
        index b15ad10d7c..49d5ab4053 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java
        @@ -26,11 +26,9 @@ import java.util.Set;
          */
         public interface PermissionsRules {
         
        -  boolean isAllowed(String userId,String action);
        +    boolean isAllowed(String userId, String action);
         
        -  void executeAction(String itemId, String userId, String action);
        -
        -  void updatePermission(String itemId,String currentUserId, String permission,Set
        -      addedUsersIds, Set removedUsersIds);
        +    void executeAction(String itemId, String userId, String action);
         
        +    void updatePermission(String itemId, String currentUserId, String permission, Set addedUsersIds, Set removedUsersIds);
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java
        index a4afa2a5c0..b7efc852b6 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java
        @@ -25,11 +25,9 @@ import org.openecomp.core.factory.api.AbstractFactory;
         /**
          * Created by ayalaben on 6/26/2017
          */
        -public abstract class PermissionsRulesFactory extends
        -    AbstractComponentFactory {
        -
        -  public static PermissionsRulesFactory getInstance() {
        -    return AbstractFactory.getInstance(PermissionsRulesFactory.class);
        -  }
        +public abstract class PermissionsRulesFactory extends AbstractComponentFactory {
         
        +    public static PermissionsRulesFactory getInstance() {
        +        return AbstractFactory.getInstance(PermissionsRulesFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java
        index 72ae535b20..fe690df7bb 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java
        @@ -15,29 +15,27 @@
          */
         package org.openecomp.sdc.itempermissions;
         
        -import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
        -
         import java.util.Collection;
         import java.util.Optional;
         import java.util.Set;
        +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
         
         /**
          * Created by ayalaben on 6/22/2017
          */
         public interface PermissionsServices {
         
        -  Collection listItemPermissions(String itemId);
        +    Collection listItemPermissions(String itemId);
         
        -  Set listUserPermittedItems(String userId, String permission);
        +    Set listUserPermittedItems(String userId, String permission);
         
        -  void updateItemPermissions(String itemId, String permission, Set addedUsersIds,
        -                             Set removedUsersIds);
        +    void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds);
         
        -  boolean isAllowed(String itemId, String userId, String action);
        +    boolean isAllowed(String itemId, String userId, String action);
         
        -  void execute(String itemId, String userId, String action);
        +    void execute(String itemId, String userId, String action);
         
        -  Optional getUserItemPermission(String itemId, String userId);
        +    Optional getUserItemPermission(String itemId, String userId);
         
        -  void deleteItemPermissions(String itemId);
        +    void deleteItemPermissions(String itemId);
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java
        index 36ed52e440..4ccfee061a 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java
        @@ -25,11 +25,9 @@ import org.openecomp.core.factory.api.AbstractFactory;
         /**
          * Created by ayalaben on 6/22/2017.
          */
        -public abstract class PermissionsServicesFactory extends
        -    AbstractComponentFactory {
        -
        -  public static PermissionsServicesFactory getInstance() {
        -    return AbstractFactory.getInstance(PermissionsServicesFactory.class);
        -  }
        +public abstract class PermissionsServicesFactory extends AbstractComponentFactory {
         
        +    public static PermissionsServicesFactory getInstance() {
        +        return AbstractFactory.getInstance(PermissionsServicesFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java
        index ea2211df85..4bd2adf7e9 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java
        @@ -15,23 +15,21 @@
          */
         package org.openecomp.sdc.itempermissions.dao;
         
        -import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
        -
         import java.util.Collection;
         import java.util.Optional;
         import java.util.Set;
        +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
         
         /**
          * Created by ayalaben on 6/18/2017.
          */
         public interface ItemPermissionsDao {
         
        -  Collection listItemPermissions(String itemId);
        +    Collection listItemPermissions(String itemId);
         
        -  void updateItemPermissions(String itemId, String permission, Set addedUsersIds,
        -                             Set removedUsersIds);
        +    void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds);
         
        -  Optional getUserItemPermission(String itemId, String userId);
        +    Optional getUserItemPermission(String itemId, String userId);
         
        -  void deleteItemPermissions(String itemId);
        +    void deleteItemPermissions(String itemId);
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java
        index 9e46f9309f..d192b4e5c6 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java
        @@ -27,8 +27,7 @@ import org.openecomp.core.factory.api.AbstractFactory;
          */
         public abstract class ItemPermissionsDaoFactory extends AbstractComponentFactory {
         
        -  public static ItemPermissionsDaoFactory getInstance() {
        -    return AbstractFactory.getInstance(ItemPermissionsDaoFactory.class);
        -  }
        -
        +    public static ItemPermissionsDaoFactory getInstance() {
        +        return AbstractFactory.getInstance(ItemPermissionsDaoFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDao.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDao.java
        index 990fde9f84..56c81b0153 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDao.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDao.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao;
         
         import java.util.Set;
        @@ -22,8 +21,5 @@ public interface UserPermissionsDao {
         
             Set listUserPermittedItems(String userId, String permission);
         
        -    void updatePermissions(String itemId, String permission, Set addedUsersIds,
        -                           Set removedUsersIds);
        -
        +    void updatePermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds);
         }
        -
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDaoFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDaoFactory.java
        index 582fa23c0d..8ac89eba68 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/UserPermissionsDaoFactory.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java
        index 1b8a36d0d4..c616884fc9 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java
        @@ -24,19 +24,19 @@ package org.openecomp.sdc.itempermissions.errors;
          */
         public enum PermissionsErrorMessages {
         
        -  NO_PERMISSION_FOR_USER("The user is not permitted to edit this item"),
        -  USER_NOT_OWNER_SUBMIT("The user must be the owner to submit the item"),
        -  INVALID_PERMISSION_TYPE("Invalid permission type"),
        -  INVALID_ACTION_TYPE("Invalid action type");
        +    NO_PERMISSION_FOR_USER("The user is not permitted to edit this item"),
        +    USER_NOT_OWNER_SUBMIT("The user must be the owner to submit the item"),
        +    INVALID_PERMISSION_TYPE("Invalid permission type"),
        +    INVALID_ACTION_TYPE("Invalid action type");
         
        -  private String errorMessage;
        +    private String errorMessage;
         
        -  PermissionsErrorMessages(String errorMessage) {
        -    this.errorMessage = errorMessage;
        -  }
        +    PermissionsErrorMessages(String errorMessage) {
        +        this.errorMessage = errorMessage;
        +    }
         
        -  public String getErrorMessage() {
        -    return errorMessage;
        -  }
        +    public String getErrorMessage() {
        +        return errorMessage;
        +    }
         
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java
        index 638a7869d6..d092f5b52d 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java
        @@ -26,23 +26,22 @@ import org.openecomp.sdc.common.errors.ErrorCode;
          * Created by ayalaben on 6/28/2017
          */
         public class PermissionsErrorMessagesBuilder {
        -  public static final String PERMISSIONS_ERROR= "PERMISSIONS_ERROR";
        -  private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder();
         
        -  /**
        -   * Instantiates a new Submit uncompleted license model error builder.
        -   *
        -   * @param error
        -   */
        -  public PermissionsErrorMessagesBuilder(PermissionsErrorMessages error) {
        -    builder.withId(PERMISSIONS_ERROR);
        -    builder.withCategory(ErrorCategory.APPLICATION);
        -    builder.withMessage(error.getErrorMessage());
        -  }
        -
        -  public ErrorCode build() {
        -    return builder.build();
        -  }
        +    public static final String PERMISSIONS_ERROR = "PERMISSIONS_ERROR";
        +    private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder();
         
        +    /**
        +     * Instantiates a new Submit uncompleted license model error builder.
        +     *
        +     * @param error
        +     */
        +    public PermissionsErrorMessagesBuilder(PermissionsErrorMessages error) {
        +        builder.withId(PERMISSIONS_ERROR);
        +        builder.withCategory(ErrorCategory.APPLICATION);
        +        builder.withMessage(error.getErrorMessage());
        +    }
         
        +    public ErrorCode build() {
        +        return builder.build();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java
        index 88cd8de4c2..dcc7365aba 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java
        @@ -24,7 +24,8 @@ package org.openecomp.sdc.itempermissions.notifications;
          * @since July 10, 2017
          */
         public class NotificationConstants {
        -    public static final String PERMISSION_CHANGED= "PermissionChanged";
        +
        +    public static final String PERMISSION_CHANGED = "PermissionChanged";
             public static final String PERMISSION_ITEM = "permission";
             public static final String ITEM_ID_PROP = "itemId";
             public static final String ITEM_NAME_PROP = "itemName";
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java
        index 81ad393607..638cd853bb 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java
        @@ -30,21 +30,18 @@ import lombok.Setter;
         /**
          * Created by ayalaben on 6/18/2017.
          */
        -
         @Getter
         @Setter
         @NoArgsConstructor
         @Table(keyspace = "dox", name = "item_permissions")
         public class ItemPermissionsEntity {
         
        -  @PartitionKey
        -  @Column(name = "item_id")
        -  private String itemId;
        -
        -  @ClusteringColumn
        -  @Column(name = "user_id")
        -  private String userId;
        -
        -  @Column(name = "permission")
        -  private String permission;
        +    @PartitionKey
        +    @Column(name = "item_id")
        +    private String itemId;
        +    @ClusteringColumn
        +    @Column(name = "user_id")
        +    private String userId;
        +    @Column(name = "permission")
        +    private String permission;
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java
        index 6fd83c2233..89db18b30b 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java
        @@ -22,7 +22,6 @@ package org.openecomp.sdc.itempermissions.dao.impl;
         import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao;
         import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory;
         
        -
         /**
          * Created by ayalaben on 6/18/2017.
          */
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java
        index c9c4198081..34c4f39395 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java
        @@ -13,18 +13,15 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao.impl;
         
         import com.datastax.driver.core.ResultSet;
         import com.datastax.driver.mapping.Result;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        -
         import java.util.Collection;
         import java.util.Optional;
         import java.util.Set;
        -
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao;
        @@ -36,8 +33,7 @@ import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
         public class ItemPermissionsDaoImpl implements ItemPermissionsDao {
         
             private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        -    private static ItemPermissionsAccessor accessor =
        -            noSqlDb.getMappingManager().createAccessor(ItemPermissionsAccessor.class);
        +    private static ItemPermissionsAccessor accessor = noSqlDb.getMappingManager().createAccessor(ItemPermissionsAccessor.class);
         
             @Override
             public Collection listItemPermissions(String itemId) {
        @@ -45,22 +41,17 @@ public class ItemPermissionsDaoImpl implements ItemPermissionsDao {
             }
         
             @Override
        -    public void updateItemPermissions(String itemId, String permission, Set addedUsersIds,
        -                                      Set removedUsersIds) {
        +    public void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds) {
                 addedUsersIds.forEach(userId -> accessor.addPermission(itemId, userId, permission));
        -        removedUsersIds.stream()
        -                .filter(userId -> getUserItemPermission(itemId, userId)
        -                        .map(userPermissionOnItem -> userPermissionOnItem.equals(permission))
        -                        .orElse(false))
        -                .forEach(userId -> accessor.deletePermission(itemId, userId));
        +        removedUsersIds.stream().filter(
        +            userId -> getUserItemPermission(itemId, userId).map(userPermissionOnItem -> userPermissionOnItem.equals(permission)).orElse(false))
        +            .forEach(userId -> accessor.deletePermission(itemId, userId));
             }
         
             @Override
             public Optional getUserItemPermission(String itemId, String userId) {
                 ResultSet result = accessor.getUserItemPermission(itemId, userId);
        -        return result.getAvailableWithoutFetching() < 1
        -                ? Optional.empty()
        -                : Optional.of(result.one().getString(0));
        +        return result.getAvailableWithoutFetching() < 1 ? Optional.empty() : Optional.of(result.one().getString(0));
             }
         
             @Override
        @@ -68,7 +59,6 @@ public class ItemPermissionsDaoImpl implements ItemPermissionsDao {
                 accessor.deleteItemPermissions(itemId);
             }
         
        -
             @Accessor
             interface ItemPermissionsAccessor {
         
        @@ -86,6 +76,5 @@ public class ItemPermissionsDaoImpl implements ItemPermissionsDao {
         
                 @Query("delete from dox.item_permissions where item_id=?")
                 void deleteItemPermissions(String itemId);
        -
             }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java
        index d0e41d8c91..7e9d289731 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java
        @@ -13,13 +13,11 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao.impl;
         
         import java.util.Collection;
         import java.util.Optional;
         import java.util.Set;
        -
         import org.openecomp.sdc.common.session.SessionContextProviderFactory;
         import org.openecomp.sdc.itempermissions.PermissionsRules;
         import org.openecomp.sdc.itempermissions.PermissionsServices;
        @@ -27,29 +25,22 @@ import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao;
         import org.openecomp.sdc.itempermissions.dao.UserPermissionsDao;
         import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity;
         
        -
         /**
          * Created by ayalaben on 6/22/2017.
          */
         public class PermissionsServicesImpl implements PermissionsServices {
         
        +    private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions";
             private ItemPermissionsDao itemPermissionsDao;
        -
             private UserPermissionsDao userPermissionsDao;
        -
             private PermissionsRules permissionsRules;
         
        -    private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions";
        -
        -    public PermissionsServicesImpl(PermissionsRules permissionsRules,
        -                                   ItemPermissionsDao itemPermissionsDao,
        -                                   UserPermissionsDao userPermissionsDao) {
        +    public PermissionsServicesImpl(PermissionsRules permissionsRules, ItemPermissionsDao itemPermissionsDao, UserPermissionsDao userPermissionsDao) {
                 this.itemPermissionsDao = itemPermissionsDao;
                 this.permissionsRules = permissionsRules;
                 this.userPermissionsDao = userPermissionsDao;
             }
         
        -
             @Override
             public Collection listItemPermissions(String itemId) {
                 return itemPermissionsDao.listItemPermissions(itemId);
        @@ -61,30 +52,18 @@ public class PermissionsServicesImpl implements PermissionsServices {
             }
         
             @Override
        -    public void updateItemPermissions(String itemId, String permission, Set addedUsersIds,
        -                                      Set removedUsersIds) {
        -
        -        String currentUserId = SessionContextProviderFactory.getInstance()
        -                .createInterface().get().getUser().getUserId();
        -
        +    public void updateItemPermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds) {
        +        String currentUserId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId();
                 permissionsRules.executeAction(itemId, currentUserId, CHANGE_PERMISSIONS);
        -
        -        permissionsRules.updatePermission(itemId, currentUserId, permission, addedUsersIds,
        -                removedUsersIds);
        -
        -        itemPermissionsDao.updateItemPermissions(itemId, permission,
        -                addedUsersIds, removedUsersIds);
        -
        -        userPermissionsDao.updatePermissions(itemId, permission,
        -                addedUsersIds, removedUsersIds);
        -
        +        permissionsRules.updatePermission(itemId, currentUserId, permission, addedUsersIds, removedUsersIds);
        +        itemPermissionsDao.updateItemPermissions(itemId, permission, addedUsersIds, removedUsersIds);
        +        userPermissionsDao.updatePermissions(itemId, permission, addedUsersIds, removedUsersIds);
             }
         
             @Override
             public boolean isAllowed(String itemId, String userId, String action) {
        -        return itemPermissionsDao.getUserItemPermission(itemId, userId)
        -                .map(permission -> permissionsRules.isAllowed(permission, action))
        -                .orElse(false);
        +        return itemPermissionsDao.getUserItemPermission(itemId, userId).map(permission -> permissionsRules.isAllowed(permission, action))
        +            .orElse(false);
             }
         
             @Override
        @@ -101,5 +80,4 @@ public class PermissionsServicesImpl implements PermissionsServices {
             public void deleteItemPermissions(String itemId) {
                 itemPermissionsDao.deleteItemPermissions(itemId);
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java
        index d009f62270..b86d10ceb1 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java
        @@ -24,14 +24,13 @@ import org.openecomp.sdc.itempermissions.dao.UserPermissionsDaoFactory;
         /**
          * Created by ayalaben on 6/22/2017
          */
        -public class PrmissionsServicesFactoryImpl  extends PermissionsServicesFactory {
        +public class PrmissionsServicesFactoryImpl extends PermissionsServicesFactory {
         
        -  private static final PermissionsServices INSTANCE =
        -      new PermissionsServicesImpl(PermissionsRulesFactory.getInstance().createInterface(),
        -          ItemPermissionsDaoFactory.getInstance().createInterface(), UserPermissionsDaoFactory.getInstance().createInterface());
        +    private static final PermissionsServices INSTANCE = new PermissionsServicesImpl(PermissionsRulesFactory.getInstance().createInterface(),
        +        ItemPermissionsDaoFactory.getInstance().createInterface(), UserPermissionsDaoFactory.getInstance().createInterface());
         
        -  @Override
        -  public PermissionsServices createInterface() {
        -    return INSTANCE;
        -  }
        +    @Override
        +    public PermissionsServices createInterface() {
        +        return INSTANCE;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoFactoryImpl.java
        index 4c23743ea5..d60013db77 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoFactoryImpl.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao.impl;
         
         import org.openecomp.sdc.itempermissions.dao.UserPermissionsDao;
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoImpl.java
        index 8609f2f4a8..25645ab483 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/UserPermissionsDaoImpl.java
        @@ -13,17 +13,14 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.dao.impl;
         
         import com.datastax.driver.core.ResultSet;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        -
         import java.util.Collections;
         import java.util.HashSet;
         import java.util.Set;
        -
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         import org.openecomp.sdc.itempermissions.dao.UserPermissionsDao;
        @@ -31,9 +28,7 @@ import org.openecomp.sdc.itempermissions.dao.UserPermissionsDao;
         public class UserPermissionsDaoImpl implements UserPermissionsDao {
         
             private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        -    private static UserPermissionsAccessor accessor =
        -            noSqlDb.getMappingManager().createAccessor(UserPermissionsAccessor.class);
        -
        +    private static UserPermissionsAccessor accessor = noSqlDb.getMappingManager().createAccessor(UserPermissionsAccessor.class);
         
             @Override
             public Set listUserPermittedItems(String userId, String permission) {
        @@ -46,14 +41,10 @@ public class UserPermissionsDaoImpl implements UserPermissionsDao {
             }
         
             @Override
        -    public void updatePermissions(String itemId, String permission, Set addedUsersIds,
        -                                  Set removedUsersIds) {
        +    public void updatePermissions(String itemId, String permission, Set addedUsersIds, Set removedUsersIds) {
                 Set itemSet = Collections.singleton(itemId);
        -
        -        addedUsersIds.forEach(userId ->
        -                accessor.addItem(itemSet, userId, permission));
        -        removedUsersIds.forEach(userId ->
        -                accessor.removeItem(itemSet, userId, permission));
        +        addedUsersIds.forEach(userId -> accessor.addItem(itemSet, userId, permission));
        +        removedUsersIds.forEach(userId -> accessor.removeItem(itemSet, userId, permission));
             }
         
             @Accessor
        @@ -67,7 +58,5 @@ public class UserPermissionsDaoImpl implements UserPermissionsDao {
         
                 @Query("update dox.user_permission_items set item_list=item_list-? WHERE user_id = ? AND permission = ?")
                 void removeItem(Set items, String userId, String permission);
        -
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java
        index 1edfad3bbc..66b999951e 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java
        @@ -13,9 +13,9 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.itempermissions.servlet;
         
        +import com.fasterxml.jackson.databind.ObjectMapper;
         import java.io.IOException;
         import javax.servlet.Filter;
         import javax.servlet.FilterChain;
        @@ -27,8 +27,6 @@ import javax.servlet.http.HttpServletRequest;
         import javax.servlet.http.HttpServletResponse;
         import javax.ws.rs.HttpMethod;
         import javax.ws.rs.core.Response;
        -
        -import com.fasterxml.jackson.databind.ObjectMapper;
         import org.openecomp.sdc.common.errors.ErrorCode;
         import org.openecomp.sdc.common.errors.ErrorCodeAndMessage;
         import org.openecomp.sdc.common.errors.Messages;
        @@ -43,9 +41,9 @@ import org.openecomp.sdc.logging.api.LoggerFactory;
         public class PermissionsFilter implements Filter {
         
             private static final Logger LOGGER = LoggerFactory.getLogger(PermissionsFilter.class);
        -    private final PermissionsServices permissionsServices;
             private static final String IRRELEVANT_REQUEST = "Irrelevant_Request";
             private static final String EDIT_ITEM = "Edit_Item";
        +    private final PermissionsServices permissionsServices;
         
             public PermissionsFilter() {
                 this(PermissionsServicesFactory.getInstance().createInterface());
        @@ -62,10 +60,8 @@ public class PermissionsFilter implements Filter {
         
             @Override
             public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        -            throws IOException, ServletException {
        -
        -        if ((servletRequest instanceof HttpServletRequest)
        -                    && isRelevant((HttpServletRequest) servletRequest, servletResponse)) {
        +        throws IOException, ServletException {
        +        if ((servletRequest instanceof HttpServletRequest) && isRelevant((HttpServletRequest) servletRequest, servletResponse)) {
                     filterChain.doFilter(servletRequest, servletResponse);
                 }
             }
        @@ -73,19 +69,15 @@ public class PermissionsFilter implements Filter {
             private boolean isRelevant(HttpServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
                 String method = servletRequest.getMethod();
                 if (method.equals(HttpMethod.POST) || method.equals(HttpMethod.PUT) || method.equals(HttpMethod.DELETE)) {
        -
                     String userId = servletRequest.getHeader("USER_ID");
                     String itemId = parseItemIdFromPath(servletRequest.getPathInfo());
        -
                     if (!itemId.equals(IRRELEVANT_REQUEST) && !permissionsServices.isAllowed(itemId, userId, EDIT_ITEM)) {
                         ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_FORBIDDEN);
        -                servletResponse.getWriter().print(buildResponse(Response.Status.FORBIDDEN,
        -                        Messages.PERMISSIONS_ERROR.getErrorMessage(),
        -                        Messages.PERMISSIONS_ERROR.name()));
        +                servletResponse.getWriter()
        +                    .print(buildResponse(Response.Status.FORBIDDEN, Messages.PERMISSIONS_ERROR.getErrorMessage(), Messages.PERMISSIONS_ERROR.name()));
                         return false;
                     }
                 }
        -
                 return true;
             }
         
        @@ -104,9 +96,7 @@ public class PermissionsFilter implements Filter {
             }
         
             private String buildResponse(Response.Status status, String message, String id) {
        -        ErrorCode errorCode = new ErrorCode.ErrorCodeBuilder()
        -                                      .withId(id)
        -                                      .withMessage(message).build();
        +        ErrorCode errorCode = new ErrorCode.ErrorCodeBuilder().withId(id).withMessage(message).build();
                 return objectToJsonString(new ErrorCodeAndMessage(status, errorCode));
             }
         
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java
        index 0562078a6e..c7007a4644 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.itempermissions.impl;
         
         import org.openecomp.sdc.itempermissions.PermissionsRules;
        @@ -28,9 +27,8 @@ import org.openecomp.sdc.itempermissions.PermissionsRulesFactory;
          */
         public class PermissionsRulesFactoryImpl extends PermissionsRulesFactory {
         
        -   @Override
        -  public PermissionsRules createInterface() {
        -    return new PermissionsRulesImpl();
        -  }
        -
        +    @Override
        +    public PermissionsRules createInterface() {
        +        return new PermissionsRulesImpl();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java
        index 222ed000ae..2b039c7c93 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java
        @@ -15,6 +15,12 @@
          */
         package org.openecomp.sdc.itempermissions.impl;
         
        +import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_ACTION_TYPE;
        +import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_PERMISSION_TYPE;
        +
        +import java.util.Collections;
        +import java.util.HashSet;
        +import java.util.Set;
         import org.apache.commons.collections.CollectionUtils;
         import org.openecomp.sdc.common.errors.CoreException;
         import org.openecomp.sdc.itempermissions.PermissionsRules;
        @@ -24,22 +30,13 @@ import org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessagesBuilder;
         import org.openecomp.sdc.itempermissions.impl.types.PermissionActionTypes;
         import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes;
         
        -import java.util.Collections;
        -import java.util.HashSet;
        -import java.util.Set;
        -
        -import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_ACTION_TYPE;
        -import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_PERMISSION_TYPE;
        -
         /**
          * Created by ayalaben on 6/26/2017.
          */
         public class PermissionsRulesImpl implements PermissionsRules {
         
        -
             @Override
             public boolean isAllowed(String permission, String action) {
        -
                 if (permission == null) {
                     return false;
                 }
        @@ -48,35 +45,29 @@ public class PermissionsRulesImpl implements PermissionsRules {
                 } catch (IllegalArgumentException ex) {
                     throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_PERMISSION_TYPE).build());
                 }
        -
                 try {
                     switch (PermissionActionTypes.valueOf(action)) {
                         case Create_Item:
                             return true;
        -
                         case Edit_Item:
                         case Commit_Item:
                         case Delete_Item:
                         case Submit_Item:
        -                    if (permission.equals(PermissionTypes.Contributor.name()) || permission.equals
        -                            (PermissionTypes.Owner.name())) {
        +                    if (permission.equals(PermissionTypes.Contributor.name()) || permission.equals(PermissionTypes.Owner.name())) {
                                 return true;
                             }
                             break;
        -
                         case Change_Item_Permissions:
                             if (permission.equals(PermissionTypes.Owner.name())) {
                                 return true;
                             }
                             break;
        -
                         default:
                             return false;
                     }
                 } catch (IllegalArgumentException ex) {
                     throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_ACTION_TYPE).build());
                 }
        -
                 return false;
             }
         
        @@ -87,16 +78,12 @@ public class PermissionsRulesImpl implements PermissionsRules {
                         case Create_Item:
                             caseCreateItem(userId, itemId);
                             break;
        -
                         case Change_Item_Permissions:
                             break;
        -
                         case Edit_Item:
                             break;
        -
                         case Submit_Item:
                             break;
        -
                         default:
                     }
                 } catch (IllegalArgumentException ex) {
        @@ -104,46 +91,36 @@ public class PermissionsRulesImpl implements PermissionsRules {
                 }
             }
         
        -  @Override
        -  public void updatePermission(String itemId, String currentUserId, String permission, Set
        -      addedUsersIds, Set removedUsersIds) {
        -    try {
        -      PermissionTypes.valueOf(permission);
        -    } catch (IllegalArgumentException ex) {
        -      throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_PERMISSION_TYPE).build());
        +    @Override
        +    public void updatePermission(String itemId, String currentUserId, String permission, Set addedUsersIds, Set removedUsersIds) {
        +        try {
        +            PermissionTypes.valueOf(permission);
        +        } catch (IllegalArgumentException ex) {
        +            throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_PERMISSION_TYPE).build());
        +        }
        +        if (isOwnerAdded(permission, addedUsersIds)) {
        +            handleCurrentOwner(itemId, currentUserId);
        +        }
             }
         
        -    if (isOwnerAdded(permission, addedUsersIds)) {
        -      handleCurrentOwner(itemId, currentUserId);
        +    private boolean isOwnerAdded(String permission, Set addedUsersIds) {
        +        return permission.equals(PermissionTypes.Owner.name()) && CollectionUtils.isNotEmpty(addedUsersIds);
             }
        -  }
         
        -  private boolean isOwnerAdded(String permission, Set addedUsersIds) {
        -    return permission.equals(PermissionTypes.Owner.name()) &&
        -        CollectionUtils.isNotEmpty(addedUsersIds);
        -  }
        -
        -  private void handleCurrentOwner(String itemId, String currentUserId) {
        -    PermissionsServices permissionsServices =
        -        PermissionsServicesFactory.getInstance().createInterface();
        -    if (!permissionsServices.getUserItemPermission(itemId, currentUserId).isPresent()) {
        -      return; // no current owner - first owner addition
        +    private void handleCurrentOwner(String itemId, String currentUserId) {
        +        PermissionsServices permissionsServices = PermissionsServicesFactory.getInstance().createInterface();
        +        if (!permissionsServices.getUserItemPermission(itemId, currentUserId).isPresent()) {
        +            return; // no current owner - first owner addition
        +        }
        +        Set currentUserSet = Collections.singleton(currentUserId);
        +        permissionsServices.updateItemPermissions(itemId, PermissionTypes.Contributor.name(), currentUserSet, new HashSet<>());
        +        permissionsServices.updateItemPermissions(itemId, PermissionTypes.Owner.name(), new HashSet<>(), currentUserSet);
             }
         
        -    Set currentUserSet = Collections.singleton(currentUserId);
        -    permissionsServices
        -        .updateItemPermissions(itemId, PermissionTypes.Contributor.name(), currentUserSet,
        -            new HashSet<>());
        -    permissionsServices.updateItemPermissions(itemId, PermissionTypes.Owner.name(), new HashSet<>(),
        -        currentUserSet);
        -  }
        -
             private void caseCreateItem(String userId, String itemId) {
                 HashSet ownerId = new HashSet<>();
                 ownerId.add(userId);
                 PermissionsServicesFactory.getInstance().createInterface()
        -                .updateItemPermissions(itemId, PermissionTypes.Owner.name(), ownerId,
        -                        new HashSet<>());
        +            .updateItemPermissions(itemId, PermissionTypes.Owner.name(), ownerId, new HashSet<>());
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java
        index e0d03459a5..34c2128a5d 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.itempermissions.impl.types;
         
         /**
        diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java
        index 1e0acdfe99..67cd837652 100644
        --- a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java
        +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,13 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.itempermissions.impl.types;
         
         /**
          * Created by ayalaben on 6/26/2017.
          */
        -public enum PermissionTypes {
        -  Owner,
        -  Contributor
        -}
        +public enum PermissionTypes {Owner, Contributor}
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/ActionConstants.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/ActionConstants.java
        index 1823b752c8..d24deb75ef 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/ActionConstants.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/ActionConstants.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,91 +17,80 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action;
         
        -
         import org.onap.logging.ref.slf4j.ONAPLogConstants;
         
         public class ActionConstants {
         
        -  //
        -  public static final long MAX_ACTION_ARTIFACT_SIZE = 20 * 1024 * 1024L; //20 MB
        -  //REST layer constants
        -  public static final String X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM = "X-OPEN-ECOMP-InstanceID";
        -  public static final String X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM = "X-OPEN-ECOMP-RequestID";
        -  public static final String WWW_AUTHENTICATE_HEADER_PARAM = "WWW-Authenticate";
        -
        -  public static final String ACTION_REQUEST_PARAM_NAME = "name";
        -  public static final String ACTION_REQUEST_PARAM_END_POINT_URI = "endpointUri";
        -  public static final String SUPPORTED_MODELS_VERSION_ID = "versionId";
        -  public static final String SUPPORTED_COMPONENTS_ID = "Id";
        -  public static final String ACTION_REQUEST_PARAM_SUPPORTED_MODELS = SUPPORTED_MODELS_VERSION_ID
        -       + " in supportedModels";
        -  public static final String ACTION_REQUEST_PARAM_SUPPORTED_COMPONENTS =
        -      SUPPORTED_COMPONENTS_ID + " in supportedComponents";
        -
        -  public static final String REQUEST_EMPTY_BODY = "{}";
        -  public static final String REQUEST_TYPE_CREATE_ACTION = "REQUEST_CREATE_ACTION";
        -  public static final String REQUEST_TYPE_UPDATE_ACTION = "REQUEST_UPDATE_ACTION";
        -  public static final String REQUEST_TYPE_VERSION_ACTION = "REQUEST_VERSION_ACTION";
        -
        -  //DAO layer constants
        -  public static final String ACTION_VERSIONABLE_TYPE = "Action";
        -
        -  //Manager constants
        -  public static final String UNIQUE_ID = "actionUuId";
        -  public static final String VERSION = "version";
        -  public static final String INVARIANTUUID = "actionInvariantUuId";
        -  public static final String STATUS = "status";
        -  public static final String ARTIFACTS = "artifacts";
        -  public static final String TIMESTAMP = "timeStamp";
        -  public static final String UPDATED_BY = "updatedBy";
        -  public static final String ARTIFACT_NAME = "artifactName";
        -  public static final String ARTIFACT_FILE = "Artifact to be uploaded";
        -
        -  // Status
        -  public static final String UNDO_CHECKOUT_RESPONSE_TEXT =
        -      "Changes to the Action object successfully reverted back.";
        +    public static final long MAX_ACTION_ARTIFACT_SIZE = 20 * 1024 * 1024L; //20 MB
         
        -  //GET Request Filter Types
        -  public static final String FILTER_TYPE_VENDOR = "VENDOR";
        -  public static final String FILTER_TYPE_CATEGORY = "CATEGORY";
        -  public static final String FILTER_TYPE_NAME = "NAME";
        -  public static final String FILTER_TYPE_MODEL = "MODEL";
        -  public static final String FILTER_TYPE_OPEN_ECOMP_COMPONENT = "OPEN_ECOMP_COMPONENT";
        -  public static final String FILTER_TYPE_NONE = "NONE";
        +    //REST layer constants
        +    public static final String X_OPEN_ECOMP_INSTANCE_ID_HEADER_PARAM = "X-OPEN-ECOMP-InstanceID";
        +    public static final String X_OPEN_ECOMP_REQUEST_ID_HEADER_PARAM = "X-OPEN-ECOMP-RequestID";
        +    public static final String WWW_AUTHENTICATE_HEADER_PARAM = "WWW-Authenticate";
        +    public static final String ACTION_REQUEST_PARAM_NAME = "name";
        +    public static final String ACTION_REQUEST_PARAM_END_POINT_URI = "endpointUri";
        +    public static final String SUPPORTED_MODELS_VERSION_ID = "versionId";
        +    public static final String SUPPORTED_COMPONENTS_ID = "Id";
        +    public static final String ACTION_REQUEST_PARAM_SUPPORTED_MODELS = SUPPORTED_MODELS_VERSION_ID + " in supportedModels";
        +    public static final String ACTION_REQUEST_PARAM_SUPPORTED_COMPONENTS = SUPPORTED_COMPONENTS_ID + " in supportedComponents";
        +    public static final String REQUEST_EMPTY_BODY = "{}";
        +    public static final String REQUEST_TYPE_CREATE_ACTION = "REQUEST_CREATE_ACTION";
        +    public static final String REQUEST_TYPE_UPDATE_ACTION = "REQUEST_UPDATE_ACTION";
        +    public static final String REQUEST_TYPE_VERSION_ACTION = "REQUEST_VERSION_ACTION";
        +    //DAO layer constants
        +    public static final String ACTION_VERSIONABLE_TYPE = "Action";
        +    //Manager constants
        +    public static final String UNIQUE_ID = "actionUuId";
        +    public static final String VERSION = "version";
        +    public static final String INVARIANTUUID = "actionInvariantUuId";
        +    public static final String STATUS = "status";
        +    public static final String ARTIFACTS = "artifacts";
        +    public static final String TIMESTAMP = "timeStamp";
        +    public static final String UPDATED_BY = "updatedBy";
        +    public static final String ARTIFACT_NAME = "artifactName";
        +    public static final String ARTIFACT_FILE = "Artifact to be uploaded";
        +    // Status
        +    public static final String UNDO_CHECKOUT_RESPONSE_TEXT = "Changes to the Action object successfully reverted back.";
        +    //GET Request Filter Types
        +    public static final String FILTER_TYPE_VENDOR = "VENDOR";
        +    public static final String FILTER_TYPE_CATEGORY = "CATEGORY";
        +    public static final String FILTER_TYPE_NAME = "NAME";
        +    public static final String FILTER_TYPE_MODEL = "MODEL";
        +    public static final String FILTER_TYPE_OPEN_ECOMP_COMPONENT = "OPEN_ECOMP_COMPONENT";
        +    public static final String FILTER_TYPE_NONE = "NONE";
        +    public static final String ARTIFACT_METADATA_ATTR_UUID = "ARTIFACT_UUID";
        +    public static final String ARTIFACT_METADATA_ATTR_NAME = "ARTIFACT_NAME";
        +    public static final String REQUEST_ID = ONAPLogConstants.MDCs.REQUEST_ID;
        +    public static final String SERVICE_INSTANCE_ID = "serviceInstanceID";
        +    public static final String PARTNER_NAME = ONAPLogConstants.MDCs.PARTNER_NAME;
        +    public static final String SERVICE_NAME = ONAPLogConstants.MDCs.SERVICE_NAME;
        +    public static final String INSTANCE_UUID = ONAPLogConstants.MDCs.INSTANCE_UUID;
        +    public static final String REMOTE_HOST = "RemoteHost";
        +    public static final String CLIENT_IP = ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS;
        +    public static final String CATEGORY_LOG_LEVEL = "level";
        +    public static final String STATUS_CODE = ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE;
        +    public static final String RESPONSE_CODE = ONAPLogConstants.MDCs.RESPONSE_CODE;
        +    public static final String RESPONSE_DESCRIPTION = ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION;
        +    public static final String ELAPSED_TIME = "ElapsedTime";
        +    public static final String BEGIN_TIMESTAMP = ONAPLogConstants.MDCs.ENTRY_TIMESTAMP;
        +    public static final String TARGET_SERVICE_NAME = ONAPLogConstants.MDCs.TARGET_SERVICE_NAME;
        +    public static final String TARGET_ENTITY = ONAPLogConstants.MDCs.TARGET_ENTITY;
        +    public static final String TARGET_ENTITY_API = "API";
        +    public static final String TARGET_ENTITY_DB = "DB";
        +    public static final String END_TIMESTAMP = "EndTimestamp";
        +    public static final String ERROR_CATEGORY = "ErrorCategory";
        +    public static final String ERROR_CODE = "ErrorCode";
        +    public static final String ERROR_DESCRIPTION = "ErrorDescription";
        +    public static final String MDC_ASDC_INSTANCE_UUID = "ASDC";
        +    public static final String SERVICE_METRIC_BEGIN_TIMESTAMP = "SERVICE-METRIC-BEGIN-TIMESTAMP";
        +    public static final String LOCAL_ADDR = "localAddr"; //map ServerIPAddress from loggingfilter
         
        -  public static final String ARTIFACT_METADATA_ATTR_UUID = "ARTIFACT_UUID";
        -  public static final String ARTIFACT_METADATA_ATTR_NAME = "ARTIFACT_NAME";
        +    public static final String BE_FQDN = "beFqdn"; //map ServerFQDN from logging filter
         
        -  public static final String REQUEST_ID = ONAPLogConstants.MDCs.REQUEST_ID;
        -  public static final String SERVICE_INSTANCE_ID = "serviceInstanceID";
        -  public static final String PARTNER_NAME = ONAPLogConstants.MDCs.PARTNER_NAME;
        -  public static final String SERVICE_NAME = ONAPLogConstants.MDCs.SERVICE_NAME;
        -  public static final String INSTANCE_UUID = ONAPLogConstants.MDCs.INSTANCE_UUID;
        -  public static final String REMOTE_HOST = "RemoteHost";
        -  public static final String CLIENT_IP = ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS;
        -  public static final String CATEGORY_LOG_LEVEL = "level";
        -  public static final String STATUS_CODE = ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE;
        -  public static final String RESPONSE_CODE = ONAPLogConstants.MDCs.RESPONSE_CODE;
        -  public static final String RESPONSE_DESCRIPTION = ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION;
        -  public static final String ELAPSED_TIME = "ElapsedTime";
        -  public static final String BEGIN_TIMESTAMP = ONAPLogConstants.MDCs.ENTRY_TIMESTAMP;
        -  public static final String TARGET_SERVICE_NAME = ONAPLogConstants.MDCs.TARGET_SERVICE_NAME;
        -  public static final String TARGET_ENTITY = ONAPLogConstants.MDCs.TARGET_ENTITY;
        -  public static final String TARGET_ENTITY_API = "API";
        -  public static final String TARGET_ENTITY_DB = "DB";
        -  public static final String END_TIMESTAMP = "EndTimestamp";
        -  public static final String ERROR_CATEGORY = "ErrorCategory";
        -  public static final String ERROR_CODE = "ErrorCode";
        -  public static final String ERROR_DESCRIPTION = "ErrorDescription";
        -  public static final String MDC_ASDC_INSTANCE_UUID = "ASDC";
        -  public static final String SERVICE_METRIC_BEGIN_TIMESTAMP = "SERVICE-METRIC-BEGIN-TIMESTAMP";
        -  public static final String LOCAL_ADDR = "localAddr"; //map ServerIPAddress from loggingfilter
        -  public static final String BE_FQDN = "beFqdn"; //map ServerFQDN from logging filter
        +    public final class UniqueValues {
         
        -  public final class UniqueValues {
        -    public static final String ACTION_NAME = "Action name";
        -  }
        +        public static final String ACTION_NAME = "Action name";
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDao.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDao.java
        index 746a3b654d..f23014b422 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDao.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDao.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,19 +17,17 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao;
         
         import org.openecomp.core.dao.BaseDao;
         import org.openecomp.sdc.action.dao.types.ActionArtifactEntity;
         import org.openecomp.sdc.action.types.ActionArtifact;
         
        -
         public interface ActionArtifactDao extends BaseDao {
         
        -  public void uploadArtifact(ActionArtifact data);
        +    public void uploadArtifact(ActionArtifact data);
         
        -  public ActionArtifact downloadArtifact(int effectiveVersion, String artifactUuId);
        +    public ActionArtifact downloadArtifact(int effectiveVersion, String artifactUuId);
         
        -  public void updateArtifact(ActionArtifact data);
        +    public void updateArtifact(ActionArtifact data);
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDaoFactory.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDaoFactory.java
        index 51377a18f1..bab6577a05 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionArtifactDaoFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,16 +17,14 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         
        -
         public abstract class ActionArtifactDaoFactory extends AbstractComponentFactory {
         
        -  public static ActionArtifactDaoFactory getInstance() {
        -    return AbstractFactory.getInstance(ActionArtifactDaoFactory.class);
        -  }
        +    public static ActionArtifactDaoFactory getInstance() {
        +        return AbstractFactory.getInstance(ActionArtifactDaoFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDao.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDao.java
        index ed6dfcca52..de34bb3b93 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDao.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDao.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao;
         
        +import java.util.List;
         import org.openecomp.core.dao.BaseDao;
         import org.openecomp.sdc.action.dao.types.ActionEntity;
         import org.openecomp.sdc.action.errors.ActionException;
        @@ -27,25 +27,21 @@ import org.openecomp.sdc.action.types.Action;
         import org.openecomp.sdc.action.types.OpenEcompComponent;
         import org.openecomp.sdc.versioning.dao.VersionableDao;
         
        -import java.util.List;
        -
         public interface ActionDao extends VersionableDao, BaseDao {
         
        -  public Action createAction(Action actionDto) throws ActionException;
        -
        -  public Action updateAction(Action actionDto) throws ActionException;
        +    public Action createAction(Action actionDto) throws ActionException;
         
        -  public void deleteAction(String actionInvariantUuId) throws ActionException;
        +    public Action updateAction(Action actionDto) throws ActionException;
         
        -  public List getFilteredActions(String filterType, String filterId) throws ActionException;
        +    public void deleteAction(String actionInvariantUuId) throws ActionException;
         
        -  public Action getActionsByActionUuId(String uniqueId) throws ActionException;
        +    public List getFilteredActions(String filterType, String filterId) throws ActionException;
         
        -  public List getOpenEcompComponents() throws ActionException;
        +    public Action getActionsByActionUuId(String uniqueId) throws ActionException;
         
        -  public List getActionsByActionInvariantUuId(String actionInvariantUuId)
        -      throws ActionException;
        +    public List getOpenEcompComponents() throws ActionException;
         
        -  public Action getLockedAction(String actionInvariantUuId, String user) throws ActionException;
        +    public List getActionsByActionInvariantUuId(String actionInvariantUuId) throws ActionException;
         
        +    public Action getLockedAction(String actionInvariantUuId, String user) throws ActionException;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDaoFactory.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDaoFactory.java
        index d8b0c1889e..8b56809956 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/ActionDaoFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory;
         
         public abstract class ActionDaoFactory extends AbstractComponentFactory {
         
        -  public static ActionDaoFactory getInstance() {
        -    return AbstractFactory.getInstance(ActionDaoFactory.class);
        -  }
        +    public static ActionDaoFactory getInstance() {
        +        return AbstractFactory.getInstance(ActionDaoFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionArtifactEntity.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionArtifactEntity.java
        index bd6a978ed6..d020e57946 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionArtifactEntity.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionArtifactEntity.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,51 +17,47 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao.types;
         
         import com.datastax.driver.mapping.annotations.Column;
         import com.datastax.driver.mapping.annotations.PartitionKey;
         import com.datastax.driver.mapping.annotations.Table;
        +import java.nio.ByteBuffer;
         import lombok.Getter;
         import lombok.NoArgsConstructor;
         import lombok.Setter;
         import org.openecomp.sdc.action.types.ActionArtifact;
         
        -import java.nio.ByteBuffer;
        -
         @Getter
         @Setter
         @NoArgsConstructor
         @Table(keyspace = "dox", name = "action_artifact")
         public class ActionArtifactEntity {
         
        -  @PartitionKey
        -  @Column(name = "artifactuuid")
        -  private String artifactUuId;
        -
        -  @PartitionKey(value = 1)
        -  @Column(name = "effective_version")
        -  private int effectiveVersion;
        -
        -  @Column(name = "artifact")
        -  private ByteBuffer artifact;
        -
        -  public ActionArtifactEntity(String artifactUuId, int effectiveVersion) {
        -    this.artifactUuId = artifactUuId;
        -    this.effectiveVersion = effectiveVersion;
        -  }
        -
        -  /**
        -   * To dto action artifact.
        -   *
        -   * @return the action artifact
        -   */
        -  public ActionArtifact toDto() {
        -    ActionArtifact destination = new ActionArtifact();
        -    destination.setArtifactUuId(this.getArtifactUuId());
        -    destination.setEffectiveVersion(this.getEffectiveVersion());
        -    destination.setArtifact(this.getArtifact().array());
        -    return destination;
        -  }
        +    @PartitionKey
        +    @Column(name = "artifactuuid")
        +    private String artifactUuId;
        +    @PartitionKey(value = 1)
        +    @Column(name = "effective_version")
        +    private int effectiveVersion;
        +    @Column(name = "artifact")
        +    private ByteBuffer artifact;
        +
        +    public ActionArtifactEntity(String artifactUuId, int effectiveVersion) {
        +        this.artifactUuId = artifactUuId;
        +        this.effectiveVersion = effectiveVersion;
        +    }
        +
        +    /**
        +     * To dto action artifact.
        +     *
        +     * @return the action artifact
        +     */
        +    public ActionArtifact toDto() {
        +        ActionArtifact destination = new ActionArtifact();
        +        destination.setArtifactUuId(this.getArtifactUuId());
        +        destination.setEffectiveVersion(this.getEffectiveVersion());
        +        destination.setArtifact(this.getArtifact().array());
        +        return destination;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionEntity.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionEntity.java
        index d84d560557..566301343f 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionEntity.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/ActionEntity.java
        @@ -1,30 +1,27 @@
         /*
        -* Copyright © 2016-2018 European Support Limited
        -*
        -* Licensed under the Apache License, Version 2.0 (the "License");
        -* you may not use this file except in compliance with the License.
        -* You may obtain a copy of the License at
        -*
        -*      http://www.apache.org/licenses/LICENSE-2.0
        -*
        -* Unless required by applicable law or agreed to in writing, software
        -* distributed under the License is distributed on an "AS IS" BASIS,
        -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        -* See the License for the specific language governing permissions and
        -* limitations under the License.
        -*/
        -
        + * Copyright © 2016-2018 European Support Limited
        + *
        + * Licensed under the Apache License, Version 2.0 (the "License");
        + * you may not use this file except in compliance with the License.
        + * You may obtain a copy of the License at
        + *
        + *      http://www.apache.org/licenses/LICENSE-2.0
        + *
        + * Unless required by applicable law or agreed to in writing, software
        + * distributed under the License is distributed on an "AS IS" BASIS,
        + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        + * See the License for the specific language governing permissions and
        + * limitations under the License.
        + */
         package org.openecomp.sdc.action.dao.types;
         
         import com.datastax.driver.mapping.annotations.Column;
         import com.datastax.driver.mapping.annotations.Frozen;
         import com.datastax.driver.mapping.annotations.PartitionKey;
         import com.datastax.driver.mapping.annotations.Table;
        -
         import java.util.Date;
         import java.util.Set;
         import java.util.stream.Collectors;
        -
         import lombok.Getter;
         import lombok.NoArgsConstructor;
         import lombok.Setter;
        @@ -38,72 +35,71 @@ import org.openecomp.sdc.versioning.dao.types.Version;
         @Table(keyspace = "dox", name = "Action")
         public class ActionEntity {
         
        -  @Column(name = "actionUuId")
        -  private String actionUuId;
        -  @PartitionKey(value = 0)
        -  @Column(name = "actionInvariantUuId")
        -  private String actionInvariantUuId;
        -  @PartitionKey(value = 1)
        -  @Frozen
        -  @Column(name = "version")
        -  private Version version;
        -  @Column(name = "status")
        -  private String status;
        -  @Column(name = "name")
        -  private String name;
        -  @Column(name = "vendor_list")
        -  private Set vendorList;
        -  @Column(name = "category_list")
        -  private Set categoryList;
        -  @Column(name = "timestamp")
        -  private Date timestamp;
        -  @Column(name = "user")
        -  private String user;
        -  @Column(name = "supportedModels")
        -  private Set supportedModels;
        -  @Column(name = "supportedComponents")
        -  private Set supportedComponents;
        -  @Column(name = "data")
        -  private String data;
        -
        -  public ActionEntity(String actionInvariantUuId, Version version) {
        -    this.actionInvariantUuId = actionInvariantUuId;
        -    this.version = version;
        -  }
        +    @Column(name = "actionUuId")
        +    private String actionUuId;
        +    @PartitionKey(value = 0)
        +    @Column(name = "actionInvariantUuId")
        +    private String actionInvariantUuId;
        +    @PartitionKey(value = 1)
        +    @Frozen
        +    @Column(name = "version")
        +    private Version version;
        +    @Column(name = "status")
        +    private String status;
        +    @Column(name = "name")
        +    private String name;
        +    @Column(name = "vendor_list")
        +    private Set vendorList;
        +    @Column(name = "category_list")
        +    private Set categoryList;
        +    @Column(name = "timestamp")
        +    private Date timestamp;
        +    @Column(name = "user")
        +    private String user;
        +    @Column(name = "supportedModels")
        +    private Set supportedModels;
        +    @Column(name = "supportedComponents")
        +    private Set supportedComponents;
        +    @Column(name = "data")
        +    private String data;
         
        -  /**
        -   * Sets vendor list.
        -   *
        -   * @param vendorList the vendor list
        -   */
        -  public void setVendorList(Set vendorList) {
        -    this.vendorList = vendorList != null && !vendorList.isEmpty() ?
        -                              vendorList.stream().map(String::toLowerCase).collect(Collectors.toSet()) : vendorList;
        -  }
        +    public ActionEntity(String actionInvariantUuId, Version version) {
        +        this.actionInvariantUuId = actionInvariantUuId;
        +        this.version = version;
        +    }
         
        -  /**
        -   * Sets category list.
        -   *
        -   * @param categoryList the category list
        -   */
        -  public void setCategoryList(Set categoryList) {
        -    this.categoryList = categoryList != null && !categoryList.isEmpty() ?
        -                                categoryList.stream().map(String::toLowerCase).collect(Collectors.toSet()) :
        -                                categoryList;
        -  }
        +    /**
        +     * Sets vendor list.
        +     *
        +     * @param vendorList the vendor list
        +     */
        +    public void setVendorList(Set vendorList) {
        +        this.vendorList =
        +            vendorList != null && !vendorList.isEmpty() ? vendorList.stream().map(String::toLowerCase).collect(Collectors.toSet()) : vendorList;
        +    }
         
        -  /**
        -   * To dto action.
        -   *
        -   * @return the action
        -   */
        -  public Action toDto() {
        -    Action destination = JsonUtil.json2Object(this.getData(), Action.class);
        -    destination.setData(this.getData());
        -    destination.setTimestamp(this.getTimestamp());
        -    destination.setUser(this.getUser());
        -    destination.setData(this.getData());
        -    return destination;
        -  }
        +    /**
        +     * Sets category list.
        +     *
        +     * @param categoryList the category list
        +     */
        +    public void setCategoryList(Set categoryList) {
        +        this.categoryList =
        +            categoryList != null && !categoryList.isEmpty() ? categoryList.stream().map(String::toLowerCase).collect(Collectors.toSet())
        +                : categoryList;
        +    }
         
        +    /**
        +     * To dto action.
        +     *
        +     * @return the action
        +     */
        +    public Action toDto() {
        +        Action destination = JsonUtil.json2Object(this.getData(), Action.class);
        +        destination.setData(this.getData());
        +        destination.setTimestamp(this.getTimestamp());
        +        destination.setUser(this.getUser());
        +        destination.setData(this.getData());
        +        return destination;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/OpenEcompComponentEntity.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/OpenEcompComponentEntity.java
        index f8380a9785..8759e95f5d 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/OpenEcompComponentEntity.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/dao/types/OpenEcompComponentEntity.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao.types;
         
         import com.datastax.driver.mapping.annotations.Column;
        @@ -36,23 +35,21 @@ import org.openecomp.sdc.action.types.OpenEcompComponent;
         @Table(keyspace = "dox", name = "EcompComponent")
         public class OpenEcompComponentEntity {
         
        -  @PartitionKey
        -  @Column(name = "id")
        -  private String id;
        -
        -  @Column(name = "name")
        -  private String name;
        -
        +    @PartitionKey
        +    @Column(name = "id")
        +    private String id;
        +    @Column(name = "name")
        +    private String name;
         
        -  /**
        -   * To dto OPENECOMP component.
        -   *
        -   * @return the OPENECOMP component
        -   */
        -  public OpenEcompComponent toDto() {
        -    OpenEcompComponent destination = new OpenEcompComponent();
        -    destination.setId(this.getId());
        -    destination.setName(this.getName());
        -    return destination;
        -  }
        +    /**
        +     * To dto OPENECOMP component.
        +     *
        +     * @return the OPENECOMP component
        +     */
        +    public OpenEcompComponent toDto() {
        +        OpenEcompComponent destination = new OpenEcompComponent();
        +        destination.setId(this.getId());
        +        destination.setName(this.getName());
        +        return destination;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionErrorConstants.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionErrorConstants.java
        index 9eff8a7050..1acfe15dff 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionErrorConstants.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionErrorConstants.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.errors;
         
         /**
        @@ -25,116 +24,85 @@ package org.openecomp.sdc.action.errors;
          */
         public class ActionErrorConstants {
         
        -  //Error Codes
        -  public static final String ACTION_REQUEST_INVALID_GENERIC_CODE = "ACT0001";
        -  public static final String ACTION_AUTHENTICATION_ERR_CODE = "ACT1000";
        -  public static final String ACTION_AUTHORIZATION_ERR_CODE = "ACT1001";
        -  public static final String ACTION_INVALID_INSTANCE_ID_CODE = "ACT1002";
        -  public static final String ACTION_INVALID_REQUEST_ID_CODE = "ACT1003";
        -  public static final String ACTION_INVALID_PARAM_CODE = "ACT1004";
        -  //Operation  is not supported
        -  public static final String ACTION_INVALID_REQUEST_BODY_CODE = "ACT1005";
        -  //ACTION_REQUEST_BODY_EMPTY
        -  public static final String ACTION_UPDATE_NOT_ALLOWED_CODE_NAME = "ACT1007";
        -  public static final String ACTION_CHECKOUT_ON_LOCKED_ENTITY = "ACT1008";
        -  public static final String ACTION_ENTITY_UNIQUE_VALUE_ERROR = "ACT1009";
        -
        -  public static final String ACTION_INVALID_SEARCH_CRITERIA = "ACT1011";
        -  public static final String ACTION_MULT_SEARCH_CRITERIA = "ACT1012";
        -  public static final String ACTION_UPDATE_ON_UNLOCKED_ENTITY = "ACT1013";
        -  public static final String ACTION_UPDATE_INVALID_VERSION = "ACT1014";
        -  public static final String ACTION_UPDATE_NOT_ALLOWED_CODE = "ACT1015";
        -
        -  public static final String ACTION_CHECKIN_ON_UNLOCKED_ENTITY = "ACT1017";
        -  public static final String ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED = "ACT1018";
        -  public static final String ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED = "ACT1019";
        -  public static final String ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY = "ACT1020";
        -  public static final String ACTION_NOT_LOCKED_CODE = "ACT1021";
        -  public static final String ACTION_ARTIFACT_CHECKSUM_ERROR_CODE = "ACT1022";
        -  public static final String ACTION_ARTIFACT_TOO_BIG_ERROR_CODE = "ACT1023";
        -  public static final String ACTION_ARTIFACT_ALREADY_EXISTS_CODE = "ACT1025";
        -  public static final String ACTION_ARTIFACT_UPDATE_READ_ONLY = "ACT1026";
        -  public static final String ACTION_ARTIFACT_DELETE_READ_ONLY = "ACT1027";
        -  public static final String ACTION_ARTIFACT_INVALID_PROTECTION_CODE = "ACT1028";
        -  public static final String ACTION_ARTIFACT_INVALID_NAME_CODE = "ACT1029";
        -
        -  public static final String ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1041";
        -  public static final String ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1042";
        -  public static final String ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER = "ACT1043";
        -  public static final String ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1044";
        -  public static final String ACTION_ENTITY_NOT_EXIST_CODE = "ACT1045";
        -  public static final String ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE = "ACT1046";
        -  public static final String ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE = "ACT1047";
        -  public static final String ACTION_DELETE_ON_LOCKED_ENTITY_CODE = "ACT1048";
        -
        -  public static final String ACTION_INTERNAL_SERVER_ERR_CODE = "ACT1060";
        -  //Logging Query failure Response code
        -  public static final String ACTION_QUERY_FAILURE_CODE = "QUERY_FAILURE";
        -  public static final String ACTION_QUERY_FAILURE_MSG = "Query Failure";
        -
        -
        -  //Error Messages
        -  public static final String ACTION_REQUEST_BODY_EMPTY = "Request Body is missing";
        -  //"The API failed due to missing body";
        -  public static final String ACTION_REQUEST_MISSING_MANDATORY_PARAM =
        -      "Missing mandatory parameter(s) : ";
        -  public static final String ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID =
        -      "X-OPEN-ECOMP-InstanceID HTTP header missing or empty";
        -  public static final String ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID =
        -      "X-OPEN-ECOMP-RequestID HTTP header missing or empty";
        -  public static final String ACTION_REQUEST_CONTENT_TYPE_INVALID =
        -      "Content-Type HTTP header missing or empty";
        -  public static final String ACTION_REQUEST_AUTHORIZATION_HEADER_INVALID =
        -      "Authentication is required to use the API";
        -  public static final String ACTION_REQUEST_INVALID_NAME =
        -      "Invalid syntax for action name. No whitespaces allowed.";
        -  public static final String ACTION_REQUEST_FILTER_PARAM_INVALID =
        -      "Invalid Search filter criteria provided";
        -  public static final String ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED =
        -      "Multiple filter criteria are not supported";
        -  //"Operation supports filter by one property at a time";
        -  public static final String ACTION_ARTIFACT_ENTITY_NOT_EXIST = "Specified artifact is not found";
        -  public static final String ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR = "Checksum error";
        -  public static final String ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE =
        -      "Invalid artifact protection value";
        -
        -  public static final String ACTION_ARTIFACT_INVALID_NAME =
        -      "Artifact name cannot contain any of the following characters : #<>$+%!`&*'|{}?=/:@ including"
        -          + " whitespaces, double quotes and back-slash";
        -  public static final String ACTION_ARTIFACT_READ_FILE_ERROR = "Error Occurred while reading file";
        -  public static final String ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED =
        -      "Artifacts cannot be created/updated using this operation";
        -  public static final String ACTION_ARTIFACT_TOO_BIG_ERROR =
        -      "Operation is not allowed. Artifact size exceeds the maximum file size limit (20MB).";
        -
        -  //Business Validation Error messages
        -  public static final String ACTION_UPDATE_NOT_ALLOWED_FOR_NAME =
        -      "Action Name update is not allowed";
        -  public static final String ACTION_UPDATE_PARAM_INVALID =
        -      "Update not allowed for the parameter(s) : %s";
        -  public static final String ACTION_ENTITY_NOT_EXIST = "Specified Action is not found";
        -  public static final String ACTION_REQUESTED_VERSION_INVALID = "Invalid requested version : %s";
        -  public static final String ACTION_UNSUPPORTED_OPERATION = "Operation %s not supported";
        -  public static final String ACTION_ENTITY_UNIQUE_VALUE_MSG =
        -      "%s with the value '%s' already exists.";
        -  public static final String ACTION_ARTIFACT_ALREADY_EXISTS =
        -      "Artifact name already exists for Action with id %s. Please use another name.";
        -  public static final String ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG =
        -      "The request failed due to an internal ASDC problem. Open ECOMP Component should continue the "
        -          + "attempts, with corrected data if required, to create the resource.";
        -  public static final String ACTION_ARTIFACT_DELETE_READ_ONLY_MSG =
        -      "Cannot delete read only artifact.";
        -  public static final String ACTION_ARTIFACT_UPDATE_READ_ONLY_MSG =
        -      "Cannot update read only artifact.";
        -  public static final String ACTION_NOT_LOCKED_MSG =
        -      "Operation is not allowed. Action status should be Locked.";
        -  public static final String ACTION_ARTIFACT_UPDATE_NAME_INVALID =
        -      "Artifact name cannot be updated.";
        -  public static final String ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER =
        -      "Cannot delete artifact since it is locked by other user %s.";
        -  public static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG =
        -      "Can not undo checkout on versionable entity %s with id %s since it is not checked out.";
        -  public static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG =
        -      "Can not undo checkout on versionable entity %s with id %s since it is checked out by other "
        -          + "user: %s.";
        +    //Error Codes
        +    public static final String ACTION_REQUEST_INVALID_GENERIC_CODE = "ACT0001";
        +    public static final String ACTION_AUTHENTICATION_ERR_CODE = "ACT1000";
        +    public static final String ACTION_AUTHORIZATION_ERR_CODE = "ACT1001";
        +    public static final String ACTION_INVALID_INSTANCE_ID_CODE = "ACT1002";
        +    public static final String ACTION_INVALID_REQUEST_ID_CODE = "ACT1003";
        +    public static final String ACTION_INVALID_PARAM_CODE = "ACT1004";
        +    //Operation  is not supported
        +    public static final String ACTION_INVALID_REQUEST_BODY_CODE = "ACT1005";
        +    //ACTION_REQUEST_BODY_EMPTY
        +    public static final String ACTION_UPDATE_NOT_ALLOWED_CODE_NAME = "ACT1007";
        +    public static final String ACTION_CHECKOUT_ON_LOCKED_ENTITY = "ACT1008";
        +    public static final String ACTION_ENTITY_UNIQUE_VALUE_ERROR = "ACT1009";
        +    public static final String ACTION_INVALID_SEARCH_CRITERIA = "ACT1011";
        +    public static final String ACTION_MULT_SEARCH_CRITERIA = "ACT1012";
        +    public static final String ACTION_UPDATE_ON_UNLOCKED_ENTITY = "ACT1013";
        +    public static final String ACTION_UPDATE_INVALID_VERSION = "ACT1014";
        +    public static final String ACTION_UPDATE_NOT_ALLOWED_CODE = "ACT1015";
        +    public static final String ACTION_CHECKIN_ON_UNLOCKED_ENTITY = "ACT1017";
        +    public static final String ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED = "ACT1018";
        +    public static final String ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED = "ACT1019";
        +    public static final String ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY = "ACT1020";
        +    public static final String ACTION_NOT_LOCKED_CODE = "ACT1021";
        +    public static final String ACTION_ARTIFACT_CHECKSUM_ERROR_CODE = "ACT1022";
        +    public static final String ACTION_ARTIFACT_TOO_BIG_ERROR_CODE = "ACT1023";
        +    public static final String ACTION_ARTIFACT_ALREADY_EXISTS_CODE = "ACT1025";
        +    public static final String ACTION_ARTIFACT_UPDATE_READ_ONLY = "ACT1026";
        +    public static final String ACTION_ARTIFACT_DELETE_READ_ONLY = "ACT1027";
        +    public static final String ACTION_ARTIFACT_INVALID_PROTECTION_CODE = "ACT1028";
        +    public static final String ACTION_ARTIFACT_INVALID_NAME_CODE = "ACT1029";
        +    public static final String ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1041";
        +    public static final String ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1042";
        +    public static final String ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER = "ACT1043";
        +    public static final String ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER = "ACT1044";
        +    public static final String ACTION_ENTITY_NOT_EXIST_CODE = "ACT1045";
        +    public static final String ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE = "ACT1046";
        +    public static final String ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE = "ACT1047";
        +    public static final String ACTION_DELETE_ON_LOCKED_ENTITY_CODE = "ACT1048";
        +    public static final String ACTION_INTERNAL_SERVER_ERR_CODE = "ACT1060";
        +    //Logging Query failure Response code
        +    public static final String ACTION_QUERY_FAILURE_CODE = "QUERY_FAILURE";
        +    public static final String ACTION_QUERY_FAILURE_MSG = "Query Failure";
        +    //Error Messages
        +    public static final String ACTION_REQUEST_BODY_EMPTY = "Request Body is missing";
        +    //"The API failed due to missing body";
        +    public static final String ACTION_REQUEST_MISSING_MANDATORY_PARAM = "Missing mandatory parameter(s) : ";
        +    public static final String ACTION_REQUEST_OPEN_ECOMP_INSTANCE_ID_INVALID = "X-OPEN-ECOMP-InstanceID HTTP header missing or empty";
        +    public static final String ACTION_REQUEST_OPEN_ECOMP_REQUEST_ID_INVALID = "X-OPEN-ECOMP-RequestID HTTP header missing or empty";
        +    public static final String ACTION_REQUEST_CONTENT_TYPE_INVALID = "Content-Type HTTP header missing or empty";
        +    public static final String ACTION_REQUEST_AUTHORIZATION_HEADER_INVALID = "Authentication is required to use the API";
        +    public static final String ACTION_REQUEST_INVALID_NAME = "Invalid syntax for action name. No whitespaces allowed.";
        +    public static final String ACTION_REQUEST_FILTER_PARAM_INVALID = "Invalid Search filter criteria provided";
        +    public static final String ACTION_FILTER_MULTIPLE_QUERY_PARAM_NOT_SUPPORTED = "Multiple filter criteria are not supported";
        +    //"Operation supports filter by one property at a time";
        +    public static final String ACTION_ARTIFACT_ENTITY_NOT_EXIST = "Specified artifact is not found";
        +    public static final String ACTION_REQUEST_ARTIFACT_CHECKSUM_ERROR = "Checksum error";
        +    public static final String ACTION_REQUEST_ARTIFACT_INVALID_PROTECTION_VALUE = "Invalid artifact protection value";
        +    public static final String ACTION_ARTIFACT_INVALID_NAME =
        +        "Artifact name cannot contain any of the following characters : #<>$+%!`&*'|{}?=/:@ including" + " whitespaces, double quotes and back-slash";
        +    public static final String ACTION_ARTIFACT_READ_FILE_ERROR = "Error Occurred while reading file";
        +    public static final String ACTION_REQUEST_ARTIFACT_OPERATION_ALLOWED = "Artifacts cannot be created/updated using this operation";
        +    public static final String ACTION_ARTIFACT_TOO_BIG_ERROR = "Operation is not allowed. Artifact size exceeds the maximum file size limit (20MB).";
        +    //Business Validation Error messages
        +    public static final String ACTION_UPDATE_NOT_ALLOWED_FOR_NAME = "Action Name update is not allowed";
        +    public static final String ACTION_UPDATE_PARAM_INVALID = "Update not allowed for the parameter(s) : %s";
        +    public static final String ACTION_ENTITY_NOT_EXIST = "Specified Action is not found";
        +    public static final String ACTION_REQUESTED_VERSION_INVALID = "Invalid requested version : %s";
        +    public static final String ACTION_UNSUPPORTED_OPERATION = "Operation %s not supported";
        +    public static final String ACTION_ENTITY_UNIQUE_VALUE_MSG = "%s with the value '%s' already exists.";
        +    public static final String ACTION_ARTIFACT_ALREADY_EXISTS = "Artifact name already exists for Action with id %s. Please use another name.";
        +    public static final String ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG =
        +        "The request failed due to an internal ASDC problem. Open ECOMP Component should continue the "
        +            + "attempts, with corrected data if required, to create the resource.";
        +    public static final String ACTION_ARTIFACT_DELETE_READ_ONLY_MSG = "Cannot delete read only artifact.";
        +    public static final String ACTION_ARTIFACT_UPDATE_READ_ONLY_MSG = "Cannot update read only artifact.";
        +    public static final String ACTION_NOT_LOCKED_MSG = "Operation is not allowed. Action status should be Locked.";
        +    public static final String ACTION_ARTIFACT_UPDATE_NAME_INVALID = "Artifact name cannot be updated.";
        +    public static final String ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER = "Cannot delete artifact since it is locked by other user %s.";
        +    public static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG = "Can not undo checkout on versionable entity %s with id %s since it is not checked out.";
        +    public static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG =
        +        "Can not undo checkout on versionable entity %s with id %s since it is checked out by other " + "user: %s.";
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionException.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionException.java
        index 08db9e241a..e702737753 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionException.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionException.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.errors;
         
         import org.openecomp.sdc.action.util.ActionUtil;
        @@ -27,47 +26,46 @@ import org.openecomp.sdc.action.util.ActionUtil;
          */
         public class ActionException extends RuntimeException {
         
        -  private String errorCode;
        -  private String description;
        -  private int logResponseCode;
        -
        -  public ActionException() {
        +    private String errorCode;
        +    private String description;
        +    private int logResponseCode;
         
        -  }
        +    public ActionException() {
        +    }
         
        -  /**
        -   * Instantiates a new Action exception.
        -   *
        -   * @param errorCode   the error code
        -   * @param description the description
        -   */
        -  public ActionException(String errorCode, String description) {
        -    this.errorCode = errorCode;
        -    this.description = description;
        -    this.logResponseCode = ActionUtil.getLogResponseCode(this.errorCode);
        -  }
        +    /**
        +     * Instantiates a new Action exception.
        +     *
        +     * @param errorCode   the error code
        +     * @param description the description
        +     */
        +    public ActionException(String errorCode, String description) {
        +        this.errorCode = errorCode;
        +        this.description = description;
        +        this.logResponseCode = ActionUtil.getLogResponseCode(this.errorCode);
        +    }
         
        -  public String getErrorCode() {
        -    return errorCode;
        -  }
        +    public String getErrorCode() {
        +        return errorCode;
        +    }
         
        -  public void setErrorCode(String errorCode) {
        -    this.errorCode = errorCode;
        -  }
        +    public void setErrorCode(String errorCode) {
        +        this.errorCode = errorCode;
        +    }
         
        -  public String getDescription() {
        -    return description;
        -  }
        +    public String getDescription() {
        +        return description;
        +    }
         
        -  public void setDescription(String description) {
        -    this.description = description;
        -  }
        +    public void setDescription(String description) {
        +        this.description = description;
        +    }
         
        -  public int getLogResponseCode() {
        -    return logResponseCode;
        -  }
        +    public int getLogResponseCode() {
        +        return logResponseCode;
        +    }
         
        -  public void setLogResponseCode(int logResponseCode) {
        -    this.logResponseCode = logResponseCode;
        -  }
        +    public void setLogResponseCode(int logResponseCode) {
        +        this.logResponseCode = logResponseCode;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java
        index 09c8607b17..ec83fef0e1 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,101 +17,121 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.errors;
         
        +import static org.openecomp.sdc.action.ActionConstants.WWW_AUTHENTICATE_HEADER_PARAM;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_ALREADY_EXISTS_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_CHECKSUM_ERROR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DELETE_READ_ONLY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_INVALID_NAME_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_INVALID_PROTECTION_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_TOO_BIG_ERROR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_UPDATE_READ_ONLY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_AUTHENTICATION_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_AUTHORIZATION_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKIN_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKOUT_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_DELETE_ON_LOCKED_ENTITY_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_UNIQUE_VALUE_ERROR;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_INSTANCE_ID_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_PARAM_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_REQUEST_BODY_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_REQUEST_ID_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_SEARCH_CRITERIA;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_MULT_SEARCH_CRITERIA;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_AUTHORIZATION_HEADER_INVALID;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_INVALID_GENERIC_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_INVALID_VERSION;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_CODE_NAME;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_FOR_NAME;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_ON_UNLOCKED_ENTITY;
        +
         import javax.ws.rs.core.MediaType;
         import javax.ws.rs.core.Response;
         import javax.ws.rs.ext.ExceptionMapper;
         
        -import static org.openecomp.sdc.action.ActionConstants.WWW_AUTHENTICATE_HEADER_PARAM;
        -import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
        -
         /**
          * Mapper class to map Action Library exceptions to corresponding HTTP Response objects.
          */
         public class ActionExceptionMapper implements ExceptionMapper {
         
        -  @Override
        -  public Response toResponse(ActionException exception) {
        -    Response response;
        -    String errorCode = exception.getErrorCode();
        -    switch (errorCode) {
        -      case ACTION_REQUEST_INVALID_GENERIC_CODE:
        -      case ACTION_INVALID_INSTANCE_ID_CODE:
        -      case ACTION_INVALID_REQUEST_ID_CODE:
        -      case ACTION_INVALID_REQUEST_BODY_CODE:
        -      case ACTION_INVALID_PARAM_CODE:
        -      case ACTION_UPDATE_NOT_ALLOWED_FOR_NAME:
        -      case ACTION_CHECKOUT_ON_LOCKED_ENTITY:
        -      case ACTION_ENTITY_UNIQUE_VALUE_ERROR:
        -      case ACTION_INVALID_SEARCH_CRITERIA:
        -      case ACTION_MULT_SEARCH_CRITERIA:
        -      case ACTION_UPDATE_ON_UNLOCKED_ENTITY:
        -      case ACTION_UPDATE_INVALID_VERSION:
        -      case ACTION_UPDATE_NOT_ALLOWED_CODE:
        -      case ACTION_CHECKIN_ON_UNLOCKED_ENTITY:
        -      case ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED:
        -      case ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED:
        -      case ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY:
        -      case ACTION_UPDATE_NOT_ALLOWED_CODE_NAME:
        -      case ACTION_ARTIFACT_CHECKSUM_ERROR_CODE:
        -      case ACTION_ARTIFACT_ALREADY_EXISTS_CODE:
        -      case ACTION_ARTIFACT_INVALID_NAME_CODE:
        -      case ACTION_ARTIFACT_TOO_BIG_ERROR_CODE:
        -      case ACTION_ARTIFACT_INVALID_PROTECTION_CODE:
        -      case ACTION_ARTIFACT_DELETE_READ_ONLY:
        -      case ACTION_NOT_LOCKED_CODE:
        -        response = Response
        -            .status(Response.Status.BAD_REQUEST)
        -            .entity(new ActionExceptionResponse(errorCode,
        -                Response.Status.BAD_REQUEST.getReasonPhrase(), exception.getDescription()))
        -            .type(MediaType.APPLICATION_JSON)
        -            .build();
        -        break;
        -      case ACTION_AUTHENTICATION_ERR_CODE:
        -        response = Response
        -            .status(Response.Status.UNAUTHORIZED)
        -            .header(WWW_AUTHENTICATE_HEADER_PARAM, ACTION_REQUEST_AUTHORIZATION_HEADER_INVALID)
        -            .entity(new ActionExceptionResponse(errorCode,
        -                Response.Status.UNAUTHORIZED.getReasonPhrase(), exception.getDescription()))
        -            .type(MediaType.APPLICATION_JSON)
        -            .build();
        -        break;
        -      case ACTION_AUTHORIZATION_ERR_CODE:
        -      case ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER:
        -      case ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER:
        -      case ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER:
        -      case ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER:
        -      case ACTION_DELETE_ON_LOCKED_ENTITY_CODE:
        -      case ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE:
        -      case ACTION_ARTIFACT_UPDATE_READ_ONLY:
        -        response = Response
        -            .status(Response.Status.FORBIDDEN)
        -            .entity(
        -                new ActionExceptionResponse(errorCode, Response.Status.FORBIDDEN.getReasonPhrase(),
        -                    exception.getDescription())).type(MediaType.APPLICATION_JSON)
        -            .build();
        -        break;
        -      case ACTION_ENTITY_NOT_EXIST_CODE:
        -      case ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE:
        -        response = Response
        -            .status(Response.Status.NOT_FOUND)
        -            .entity(
        -                new ActionExceptionResponse(errorCode, Response.Status.NOT_FOUND.getReasonPhrase(),
        -                    exception.getDescription())).type(MediaType.APPLICATION_JSON)
        -            .build();
        -        break;
        -      case ACTION_INTERNAL_SERVER_ERR_CODE:
        -      default:
        -        response = Response
        -            .status(Response.Status.INTERNAL_SERVER_ERROR)
        -            .entity(new ActionExceptionResponse(errorCode,
        -                Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(),
        -                exception.getDescription()))
        -            .type(MediaType.APPLICATION_JSON)
        -            .build();
        +    @Override
        +    public Response toResponse(ActionException exception) {
        +        Response response;
        +        String errorCode = exception.getErrorCode();
        +        switch (errorCode) {
        +            case ACTION_REQUEST_INVALID_GENERIC_CODE:
        +            case ACTION_INVALID_INSTANCE_ID_CODE:
        +            case ACTION_INVALID_REQUEST_ID_CODE:
        +            case ACTION_INVALID_REQUEST_BODY_CODE:
        +            case ACTION_INVALID_PARAM_CODE:
        +            case ACTION_UPDATE_NOT_ALLOWED_FOR_NAME:
        +            case ACTION_CHECKOUT_ON_LOCKED_ENTITY:
        +            case ACTION_ENTITY_UNIQUE_VALUE_ERROR:
        +            case ACTION_INVALID_SEARCH_CRITERIA:
        +            case ACTION_MULT_SEARCH_CRITERIA:
        +            case ACTION_UPDATE_ON_UNLOCKED_ENTITY:
        +            case ACTION_UPDATE_INVALID_VERSION:
        +            case ACTION_UPDATE_NOT_ALLOWED_CODE:
        +            case ACTION_CHECKIN_ON_UNLOCKED_ENTITY:
        +            case ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED:
        +            case ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED:
        +            case ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY:
        +            case ACTION_UPDATE_NOT_ALLOWED_CODE_NAME:
        +            case ACTION_ARTIFACT_CHECKSUM_ERROR_CODE:
        +            case ACTION_ARTIFACT_ALREADY_EXISTS_CODE:
        +            case ACTION_ARTIFACT_INVALID_NAME_CODE:
        +            case ACTION_ARTIFACT_TOO_BIG_ERROR_CODE:
        +            case ACTION_ARTIFACT_INVALID_PROTECTION_CODE:
        +            case ACTION_ARTIFACT_DELETE_READ_ONLY:
        +            case ACTION_NOT_LOCKED_CODE:
        +                response = Response.status(Response.Status.BAD_REQUEST)
        +                    .entity(new ActionExceptionResponse(errorCode, Response.Status.BAD_REQUEST.getReasonPhrase(), exception.getDescription()))
        +                    .type(MediaType.APPLICATION_JSON).build();
        +                break;
        +            case ACTION_AUTHENTICATION_ERR_CODE:
        +                response = Response.status(Response.Status.UNAUTHORIZED)
        +                    .header(WWW_AUTHENTICATE_HEADER_PARAM, ACTION_REQUEST_AUTHORIZATION_HEADER_INVALID)
        +                    .entity(new ActionExceptionResponse(errorCode, Response.Status.UNAUTHORIZED.getReasonPhrase(), exception.getDescription()))
        +                    .type(MediaType.APPLICATION_JSON).build();
        +                break;
        +            case ACTION_AUTHORIZATION_ERR_CODE:
        +            case ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER:
        +            case ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER:
        +            case ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER:
        +            case ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER:
        +            case ACTION_DELETE_ON_LOCKED_ENTITY_CODE:
        +            case ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE:
        +            case ACTION_ARTIFACT_UPDATE_READ_ONLY:
        +                response = Response.status(Response.Status.FORBIDDEN)
        +                    .entity(new ActionExceptionResponse(errorCode, Response.Status.FORBIDDEN.getReasonPhrase(), exception.getDescription()))
        +                    .type(MediaType.APPLICATION_JSON).build();
        +                break;
        +            case ACTION_ENTITY_NOT_EXIST_CODE:
        +            case ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE:
        +                response = Response.status(Response.Status.NOT_FOUND)
        +                    .entity(new ActionExceptionResponse(errorCode, Response.Status.NOT_FOUND.getReasonPhrase(), exception.getDescription()))
        +                    .type(MediaType.APPLICATION_JSON).build();
        +                break;
        +            case ACTION_INTERNAL_SERVER_ERR_CODE:
        +            default:
        +                response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
        +                    new ActionExceptionResponse(errorCode, Response.Status.INTERNAL_SERVER_ERROR.getReasonPhrase(), exception.getDescription()))
        +                    .type(MediaType.APPLICATION_JSON).build();
        +        }
        +        return response;
             }
        -    return response;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionResponse.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionResponse.java
        index 51848464a7..1b9e811bbf 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionResponse.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionResponse.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,50 +17,48 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.errors;
         
         public class ActionExceptionResponse {
        -  private String code;
        -  private String description;
        -  private String message;
        -
        -  /**
        -   * Instantiates a new Action exception response.
        -   *
        -   * @param code        the code
        -   * @param description the description
        -   * @param message     the message
        -   */
        -  public ActionExceptionResponse(String code, String description, String message) {
        -    this.code = code;
        -    this.description = description;
        -    this.message = message;
        -  }
         
        -  public String getCode() {
        -    return code;
        -  }
        +    private String code;
        +    private String description;
        +    private String message;
         
        -  public void setCode(String code) {
        -    this.code = code;
        -  }
        +    /**
        +     * Instantiates a new Action exception response.
        +     *
        +     * @param code        the code
        +     * @param description the description
        +     * @param message     the message
        +     */
        +    public ActionExceptionResponse(String code, String description, String message) {
        +        this.code = code;
        +        this.description = description;
        +        this.message = message;
        +    }
         
        -  public String getDescription() {
        -    return description;
        -  }
        +    public String getCode() {
        +        return code;
        +    }
         
        -  public void setDescription(String description) {
        -    this.description = description;
        -  }
        +    public void setCode(String code) {
        +        this.code = code;
        +    }
         
        -  public String getMessage() {
        -    return message;
        -  }
        +    public String getDescription() {
        +        return description;
        +    }
         
        -  public void setMessage(String message) {
        -    this.message = message;
        -  }
        +    public void setDescription(String description) {
        +        this.description = description;
        +    }
         
        +    public String getMessage() {
        +        return message;
        +    }
         
        +    public void setMessage(String message) {
        +        this.message = message;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/logging/CategoryLogLevel.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/logging/CategoryLogLevel.java
        index d87bed310f..6aaec85693 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/logging/CategoryLogLevel.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/logging/CategoryLogLevel.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,13 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.logging;
         
        -public enum CategoryLogLevel {
        -  INFO,
        -  WARN,
        -  DEBUG,
        -  ERROR,
        -  FATAL
        -}
        +public enum CategoryLogLevel {INFO, WARN, DEBUG, ERROR, FATAL}
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/Action.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/Action.java
        index 672a27ae34..07dd03882d 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/Action.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/Action.java
        @@ -1,19 +1,18 @@
         /*
        -* Copyright © 2016-2018 European Support Limited
        -*
        -* Licensed under the Apache License, Version 2.0 (the "License");
        -* you may not use this file except in compliance with the License.
        -* You may obtain a copy of the License at
        -*
        -*      http://www.apache.org/licenses/LICENSE-2.0
        -*
        -* Unless required by applicable law or agreed to in writing, software
        -* distributed under the License is distributed on an "AS IS" BASIS,
        -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        -* See the License for the specific language governing permissions and
        -* limitations under the License.
        -*/
        -
        + * Copyright © 2016-2018 European Support Limited
        + *
        + * Licensed under the Apache License, Version 2.0 (the "License");
        + * you may not use this file except in compliance with the License.
        + * You may obtain a copy of the License at
        + *
        + *      http://www.apache.org/licenses/LICENSE-2.0
        + *
        + * Unless required by applicable law or agreed to in writing, software
        + * distributed under the License is distributed on an "AS IS" BASIS,
        + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        + * See the License for the specific language governing permissions and
        + * limitations under the License.
        + */
         package org.openecomp.sdc.action.types;
         
         import java.util.Date;
        @@ -22,252 +21,241 @@ import java.util.List;
         import java.util.Map;
         import java.util.Objects;
         import java.util.Set;
        -
         import org.openecomp.sdc.action.ActionConstants;
         import org.openecomp.sdc.action.dao.types.ActionEntity;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -
         public class Action implements Comparable {
        -  private String actionUuId;
        -  private String actionInvariantUuId;
        -  private String version;
        -  private ActionStatus status;
        -  private String name;
        -  private String displayName;
        -  private List vendorList;
        -  private List categoryList;
        -  private Date timestamp;
        -  private String user;
        -  private List> supportedModels;
        -  private List> supportedComponents;
        -  //private List> artifacts;
        -  private List artifacts;
        -  private String data;
        -
        -  public Action() {
        -  }
        -
        -  /**
        -   * Instantiates a new Action.
        -   *
        -   * @param action the action
        -   */
        -  public Action(Action action) {
        -    this.actionUuId = action.getActionUuId();
        -    this.actionInvariantUuId = action.getActionInvariantUuId();
        -    this.name = action.getName();
        -    this.setDisplayName(action.getDisplayName());
        -    this.setVendorList(action.getVendorList());
        -    this.setCategoryList(action.getCategoryList());
        -    this.setTimestamp(action.getTimestamp());
        -    this.setUser(action.getUser());
        -    this.version = action.getVersion();
        -    this.status = action.getStatus();
        -    this.data = action.getData();
        -    this.supportedComponents = action.getSupportedComponents();
        -    this.supportedModels = action.getSupportedModels();
        -    this.artifacts = action.getArtifacts();
        -  }
        -
        -  public String getActionUuId() {
        -    return actionUuId;
        -  }
        -
        -  public void setActionUuId(String actionUuId) {
        -    this.actionUuId = actionUuId;
        -  }
        -
        -  public String getActionInvariantUuId() {
        -    return actionInvariantUuId;
        -  }
        -
        -  public void setActionInvariantUuId(String actionInvariantUuId) {
        -    this.actionInvariantUuId = actionInvariantUuId;
        -  }
        -
        -  public String getVersion() {
        -    return version;
        -  }
        -
        -  public void setVersion(String version) {
        -    this.version = version;
        -  }
        -
        -  public ActionStatus getStatus() {
        -    return status;
        -  }
        -
        -  public void setStatus(ActionStatus status) {
        -    this.status = status;
        -  }
        -
        -  public String getName() {
        -    return name;
        -  }
        -
        -  public void setName(String name) {
        -    this.name = name;
        -  }
        -
        -  public String getDisplayName() {
        -    return displayName;
        -  }
        -
        -  public void setDisplayName(String displayName) {
        -    this.displayName = displayName;
        -  }
        -
        -  public List getVendorList() {
        -    return vendorList;
        -  }
        -
        -  public void setVendorList(List vendorList) {
        -    this.vendorList = vendorList;
        -  }
        -
        -  public List getCategoryList() {
        -    return categoryList;
        -  }
        -
        -  public void setCategoryList(List categoryList) {
        -    this.categoryList = categoryList;
        -  }
        -
        -  public Date getTimestamp() {
        -    return timestamp;
        -  }
        -
        -  public void setTimestamp(Date timestamp) {
        -    this.timestamp = timestamp;
        -  }
        -
        -  public String getUser() {
        -    return user;
        -  }
        -
        -  public void setUser(String user) {
        -    this.user = user;
        -  }
        -
        -  public List> getSupportedModels() {
        -    return supportedModels;
        -  }
        -
        -  public void setSupportedModels(List> supportedModels) {
        -    this.supportedModels = supportedModels;
        -  }
        -
        -  public List> getSupportedComponents() {
        -    return supportedComponents;
        -  }
        -
        -  public void setSupportedComponents(List> supportedComponents) {
        -    this.supportedComponents = supportedComponents;
        -  }
        -
        -
        -  public List getArtifacts() {
        -    return artifacts;
        -  }
        -
        -  public void setArtifacts(List artifacts) {
        -    this.artifacts = artifacts;
        -  }
        -
        -  public String getData() {
        -    return data;
        -  }
        -
        -  public void setData(String data) {
        -    this.data = data;
        -  }
        -
        -  /**
        -   * To entity action entity.
        -   *
        -   * @return the action entity
        -   */
        -  public ActionEntity toEntity() {
        -    ActionEntity destination = new ActionEntity();
        -
        -    destination
        -        .setActionUuId(this.getActionUuId() != null ? this.getActionUuId().toUpperCase() : null);
        -    destination.setActionInvariantUuId(
        -        this.getActionInvariantUuId() != null ? this.getActionInvariantUuId().toUpperCase() : null);
        -    destination.setName(this.getName() != null ? this.getName().toLowerCase() : null);
        -    if (Objects.nonNull(this.getVendorList())) {
        -      destination.setVendorList(new HashSet<>(this.getVendorList()));
        -    }
        -    if (Objects.nonNull(this.getCategoryList())) {
        -      destination.setCategoryList(new HashSet<>(this.getCategoryList()));
        -    }
        -    destination.setTimestamp(this.getTimestamp());
        -    destination.setUser(this.getUser());
        -    destination.setVersion(Version.valueOf(this.getVersion()));
        -    if (this.getStatus() != null) {
        -      destination.setStatus(this.getStatus().name());
        -    }
        -    destination.setSupportedComponents(getIdFromMap(this.getSupportedComponents(),
        -        ActionConstants.SUPPORTED_COMPONENTS_ID));
        -    destination.setSupportedModels(
        -        getIdFromMap(this.getSupportedModels(), ActionConstants.SUPPORTED_MODELS_VERSION_ID));
        -    destination.setData(this.getData());
        -    return destination;
        -  }
        -
        -  private Set getIdFromMap(List> map, String idName) {
        -    Set list = new HashSet<>();
        -    if (map != null && !map.isEmpty()) {
        -      for (Map entry : map) {
        -        if (entry.containsKey(idName)) {
        -          list.add(entry.get(idName) != null ? entry.get(idName).toLowerCase() : null);
        -        }
        -      }
        -      return list;
        +
        +    private String actionUuId;
        +    private String actionInvariantUuId;
        +    private String version;
        +    private ActionStatus status;
        +    private String name;
        +    private String displayName;
        +    private List vendorList;
        +    private List categoryList;
        +    private Date timestamp;
        +    private String user;
        +    private List> supportedModels;
        +    private List> supportedComponents;
        +    //private List> artifacts;
        +    private List artifacts;
        +    private String data;
        +
        +    public Action() {
        +    }
        +
        +    /**
        +     * Instantiates a new Action.
        +     *
        +     * @param action the action
        +     */
        +    public Action(Action action) {
        +        this.actionUuId = action.getActionUuId();
        +        this.actionInvariantUuId = action.getActionInvariantUuId();
        +        this.name = action.getName();
        +        this.setDisplayName(action.getDisplayName());
        +        this.setVendorList(action.getVendorList());
        +        this.setCategoryList(action.getCategoryList());
        +        this.setTimestamp(action.getTimestamp());
        +        this.setUser(action.getUser());
        +        this.version = action.getVersion();
        +        this.status = action.getStatus();
        +        this.data = action.getData();
        +        this.supportedComponents = action.getSupportedComponents();
        +        this.supportedModels = action.getSupportedModels();
        +        this.artifacts = action.getArtifacts();
        +    }
        +
        +    public String getActionUuId() {
        +        return actionUuId;
        +    }
        +
        +    public void setActionUuId(String actionUuId) {
        +        this.actionUuId = actionUuId;
        +    }
        +
        +    public String getActionInvariantUuId() {
        +        return actionInvariantUuId;
        +    }
        +
        +    public void setActionInvariantUuId(String actionInvariantUuId) {
        +        this.actionInvariantUuId = actionInvariantUuId;
        +    }
        +
        +    public String getVersion() {
        +        return version;
        +    }
        +
        +    public void setVersion(String version) {
        +        this.version = version;
        +    }
        +
        +    public ActionStatus getStatus() {
        +        return status;
        +    }
        +
        +    public void setStatus(ActionStatus status) {
        +        this.status = status;
        +    }
        +
        +    public String getName() {
        +        return name;
        +    }
        +
        +    public void setName(String name) {
        +        this.name = name;
             }
        -    return null;
        -  }
         
        -  @Override
        -  public int compareTo(Object object) {
        -    Action obj = (Action) object;
        -    Version thisVersion = Version.valueOf(this.version);
        -    Version objVersion = Version.valueOf(obj.getVersion());
        -    if (obj.getName().compareTo(this.getName()) == 0) {
        -      return compareVersions(objVersion, thisVersion);
        +    public String getDisplayName() {
        +        return displayName;
             }
        -    return obj.getName().compareTo(this.getName());
        -  }
         
        -  private int compareVersions(Version objVersion, Version thisVersion) {
        -    if (objVersion.getMajor() == thisVersion.getMajor()) {
        -      return Integer.compare(objVersion.getMinor(), thisVersion.getMinor());
        +    public void setDisplayName(String displayName) {
        +        this.displayName = displayName;
             }
        -    return Integer.compare(objVersion.getMajor(), thisVersion.getMajor());
        -  }
         
        -  @Override
        -  public boolean equals(Object o) {
        +    public List getVendorList() {
        +        return vendorList;
        +    }
         
        -    if (this == o) {
        -      return true;
        +    public void setVendorList(List vendorList) {
        +        this.vendorList = vendorList;
             }
        -    if (o == null || getClass() != o.getClass()) {
        -      return false;
        +
        +    public List getCategoryList() {
        +        return categoryList;
             }
         
        -    Action action = (Action) o;
        +    public void setCategoryList(List categoryList) {
        +        this.categoryList = categoryList;
        +    }
         
        -    if (!Objects.equals(version, action.version)) {
        -      return false;
        +    public Date getTimestamp() {
        +        return timestamp;
             }
         
        -    return Objects.equals(name, action.name);
        -  }
        +    public void setTimestamp(Date timestamp) {
        +        this.timestamp = timestamp;
        +    }
         
        -  @Override
        -  public int hashCode() {
        -    return com.google.common.base.Objects.hashCode(version, name);
        -  }
        +    public String getUser() {
        +        return user;
        +    }
        +
        +    public void setUser(String user) {
        +        this.user = user;
        +    }
        +
        +    public List> getSupportedModels() {
        +        return supportedModels;
        +    }
        +
        +    public void setSupportedModels(List> supportedModels) {
        +        this.supportedModels = supportedModels;
        +    }
        +
        +    public List> getSupportedComponents() {
        +        return supportedComponents;
        +    }
        +
        +    public void setSupportedComponents(List> supportedComponents) {
        +        this.supportedComponents = supportedComponents;
        +    }
        +
        +    public List getArtifacts() {
        +        return artifacts;
        +    }
        +
        +    public void setArtifacts(List artifacts) {
        +        this.artifacts = artifacts;
        +    }
        +
        +    public String getData() {
        +        return data;
        +    }
        +
        +    public void setData(String data) {
        +        this.data = data;
        +    }
        +
        +    /**
        +     * To entity action entity.
        +     *
        +     * @return the action entity
        +     */
        +    public ActionEntity toEntity() {
        +        ActionEntity destination = new ActionEntity();
        +        destination.setActionUuId(this.getActionUuId() != null ? this.getActionUuId().toUpperCase() : null);
        +        destination.setActionInvariantUuId(this.getActionInvariantUuId() != null ? this.getActionInvariantUuId().toUpperCase() : null);
        +        destination.setName(this.getName() != null ? this.getName().toLowerCase() : null);
        +        if (Objects.nonNull(this.getVendorList())) {
        +            destination.setVendorList(new HashSet<>(this.getVendorList()));
        +        }
        +        if (Objects.nonNull(this.getCategoryList())) {
        +            destination.setCategoryList(new HashSet<>(this.getCategoryList()));
        +        }
        +        destination.setTimestamp(this.getTimestamp());
        +        destination.setUser(this.getUser());
        +        destination.setVersion(Version.valueOf(this.getVersion()));
        +        if (this.getStatus() != null) {
        +            destination.setStatus(this.getStatus().name());
        +        }
        +        destination.setSupportedComponents(getIdFromMap(this.getSupportedComponents(), ActionConstants.SUPPORTED_COMPONENTS_ID));
        +        destination.setSupportedModels(getIdFromMap(this.getSupportedModels(), ActionConstants.SUPPORTED_MODELS_VERSION_ID));
        +        destination.setData(this.getData());
        +        return destination;
        +    }
        +
        +    private Set getIdFromMap(List> map, String idName) {
        +        Set list = new HashSet<>();
        +        if (map != null && !map.isEmpty()) {
        +            for (Map entry : map) {
        +                if (entry.containsKey(idName)) {
        +                    list.add(entry.get(idName) != null ? entry.get(idName).toLowerCase() : null);
        +                }
        +            }
        +            return list;
        +        }
        +        return null;
        +    }
        +
        +    @Override
        +    public int compareTo(Object object) {
        +        Action obj = (Action) object;
        +        Version thisVersion = Version.valueOf(this.version);
        +        Version objVersion = Version.valueOf(obj.getVersion());
        +        if (obj.getName().compareTo(this.getName()) == 0) {
        +            return compareVersions(objVersion, thisVersion);
        +        }
        +        return obj.getName().compareTo(this.getName());
        +    }
        +
        +    private int compareVersions(Version objVersion, Version thisVersion) {
        +        if (objVersion.getMajor() == thisVersion.getMajor()) {
        +            return Integer.compare(objVersion.getMinor(), thisVersion.getMinor());
        +        }
        +        return Integer.compare(objVersion.getMajor(), thisVersion.getMajor());
        +    }
        +
        +    @Override
        +    public boolean equals(Object o) {
        +        if (this == o) {
        +            return true;
        +        }
        +        if (o == null || getClass() != o.getClass()) {
        +            return false;
        +        }
        +        Action action = (Action) o;
        +        if (!Objects.equals(version, action.version)) {
        +            return false;
        +        }
        +        return Objects.equals(name, action.name);
        +    }
        +
        +    @Override
        +    public int hashCode() {
        +        return com.google.common.base.Objects.hashCode(version, name);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifact.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifact.java
        index ff4d908ed2..85aee57018 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifact.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifact.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,127 +17,123 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
         import com.fasterxml.jackson.annotation.JsonIgnore;
         import com.google.common.base.Objects;
        -import org.openecomp.sdc.action.dao.types.ActionArtifactEntity;
        -
         import java.nio.ByteBuffer;
         import java.util.Date;
        +import org.openecomp.sdc.action.dao.types.ActionArtifactEntity;
         
         public class ActionArtifact {
        -  private String artifactUuId;
        -
        -  @JsonIgnore
        -  private Integer effectiveVersion;
        -
        -  private String artifactName;
        -  private String artifactLabel;
        -  private String artifactCategory;
        -  private String artifactDescription;
        -  private String artifactProtection;
        -  private Date timestamp;
        -  private byte[] artifact;
        -
        -  public String getArtifactUuId() {
        -    return artifactUuId;
        -  }
        -
        -  public void setArtifactUuId(String artifactUuId) {
        -    this.artifactUuId = artifactUuId;
        -  }
        -
        -  public Integer getEffectiveVersion() {
        -    return effectiveVersion;
        -  }
        -
        -  public void setEffectiveVersion(Integer effectiveVersion) {
        -    this.effectiveVersion = effectiveVersion;
        -  }
        -
        -  public String getArtifactName() {
        -    return artifactName;
        -  }
        -
        -  public void setArtifactName(String artifactName) {
        -    this.artifactName = artifactName;
        -  }
        -
        -  public String getArtifactLabel() {
        -    return artifactLabel;
        -  }
        -
        -  public void setArtifactLabel(String artifactLabel) {
        -    this.artifactLabel = artifactLabel;
        -  }
        -
        -  public String getArtifactCategory() {
        -    return artifactCategory;
        -  }
        -
        -  public void setArtifactCategory(String artifactCategory) {
        -    this.artifactCategory = artifactCategory;
        -  }
        -
        -  public String getArtifactDescription() {
        -    return artifactDescription;
        -  }
        -
        -  public void setArtifactDescription(String artifactDescription) {
        -    this.artifactDescription = artifactDescription;
        -  }
        -
        -  public String getArtifactProtection() {
        -    return artifactProtection;
        -  }
        -
        -  public void setArtifactProtection(String artifactProtection) {
        -    this.artifactProtection = artifactProtection;
        -  }
        -
        -  public Date getTimestamp() {
        -    return timestamp;
        -  }
        -
        -  public void setTimestamp(Date timestamp) {
        -    this.timestamp = timestamp;
        -  }
        -
        -  public byte[] getArtifact() {
        -    return artifact;
        -  }
        -
        -  public void setArtifact(byte[] artifact) {
        -    this.artifact = artifact;
        -  }
        -
        -  /**
        -   * To entity action artifact entity.
        -   *
        -   * @return the action artifact entity
        -   */
        -  public ActionArtifactEntity toEntity() {
        -    ActionArtifactEntity destination = new ActionArtifactEntity();
        -    destination.setArtifactUuId(this.getArtifactUuId());
        -    destination.setEffectiveVersion(this.getEffectiveVersion());
        -    destination.setArtifact(ByteBuffer.wrap(this.getArtifact()));
        -
        -    return destination;
        -  }
        -
        -  @Override
        -  public boolean equals(Object obj) {
        -    if (obj instanceof ActionArtifact) {
        -      ActionArtifact temp = (ActionArtifact) obj;
        -      return Objects.equal(artifactUuId, temp.getArtifactUuId());
        -    }
        -    return false;
        -  }
        -
        -  @Override
        -  public int hashCode() {
        -    return Objects.hashCode(artifactUuId);
        -  }
        +
        +    private String artifactUuId;
        +    @JsonIgnore
        +    private Integer effectiveVersion;
        +    private String artifactName;
        +    private String artifactLabel;
        +    private String artifactCategory;
        +    private String artifactDescription;
        +    private String artifactProtection;
        +    private Date timestamp;
        +    private byte[] artifact;
        +
        +    public String getArtifactUuId() {
        +        return artifactUuId;
        +    }
        +
        +    public void setArtifactUuId(String artifactUuId) {
        +        this.artifactUuId = artifactUuId;
        +    }
        +
        +    public Integer getEffectiveVersion() {
        +        return effectiveVersion;
        +    }
        +
        +    public void setEffectiveVersion(Integer effectiveVersion) {
        +        this.effectiveVersion = effectiveVersion;
        +    }
        +
        +    public String getArtifactName() {
        +        return artifactName;
        +    }
        +
        +    public void setArtifactName(String artifactName) {
        +        this.artifactName = artifactName;
        +    }
        +
        +    public String getArtifactLabel() {
        +        return artifactLabel;
        +    }
        +
        +    public void setArtifactLabel(String artifactLabel) {
        +        this.artifactLabel = artifactLabel;
        +    }
        +
        +    public String getArtifactCategory() {
        +        return artifactCategory;
        +    }
        +
        +    public void setArtifactCategory(String artifactCategory) {
        +        this.artifactCategory = artifactCategory;
        +    }
        +
        +    public String getArtifactDescription() {
        +        return artifactDescription;
        +    }
        +
        +    public void setArtifactDescription(String artifactDescription) {
        +        this.artifactDescription = artifactDescription;
        +    }
        +
        +    public String getArtifactProtection() {
        +        return artifactProtection;
        +    }
        +
        +    public void setArtifactProtection(String artifactProtection) {
        +        this.artifactProtection = artifactProtection;
        +    }
        +
        +    public Date getTimestamp() {
        +        return timestamp;
        +    }
        +
        +    public void setTimestamp(Date timestamp) {
        +        this.timestamp = timestamp;
        +    }
        +
        +    public byte[] getArtifact() {
        +        return artifact;
        +    }
        +
        +    public void setArtifact(byte[] artifact) {
        +        this.artifact = artifact;
        +    }
        +
        +    /**
        +     * To entity action artifact entity.
        +     *
        +     * @return the action artifact entity
        +     */
        +    public ActionArtifactEntity toEntity() {
        +        ActionArtifactEntity destination = new ActionArtifactEntity();
        +        destination.setArtifactUuId(this.getArtifactUuId());
        +        destination.setEffectiveVersion(this.getEffectiveVersion());
        +        destination.setArtifact(ByteBuffer.wrap(this.getArtifact()));
        +        return destination;
        +    }
        +
        +    @Override
        +    public boolean equals(Object obj) {
        +        if (obj instanceof ActionArtifact) {
        +            ActionArtifact temp = (ActionArtifact) obj;
        +            return Objects.equal(artifactUuId, temp.getArtifactUuId());
        +        }
        +        return false;
        +    }
        +
        +    @Override
        +    public int hashCode() {
        +        return Objects.hashCode(artifactUuId);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifactProtection.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifactProtection.java
        index 636f24d781..cf57052114 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifactProtection.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionArtifactProtection.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
        -public enum ActionArtifactProtection {
        -  readOnly,
        -  readWrite
        -}
        +public enum ActionArtifactProtection {readOnly, readWrite}
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionLogResponseCode.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionLogResponseCode.java
        index c3de8aa4dc..5eacf18265 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionLogResponseCode.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionLogResponseCode.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,74 +17,74 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
         import java.util.HashMap;
         import java.util.Map;
         
         public enum ActionLogResponseCode {
        +  // @formatter:off
        +    MISSING_AUTHORIZATION(100),
        +    FORBIDDEN(101),
        +    UPDATE_ON_LOCKED_ENTITY(102),
        +    CHECKIN_ON_LOCKED_ENTITY_OTHER_USER(103),
        +    CHECKOUT_ON_LOCKED_ENTITY(104),
        +    UNDO_CHECKOUT_ON_LOCKED_ENTITY(105),
        +    DELETE_ARTIFACT_ON_LOCKED_ENTITY(106),
        +    DELETE_ON_LOCKED_ENTITY_OTHER_USER(107),
        +    INTERNAL_SERVER_ERROR(201),
        +    MISSING_MANDATORY_PARAMS(300),
        +    MISSING_INSTANCE_ID_HEADER(301),
        +    MISSING_REQUEST_ID_HEADER(302),
        +    MISSING_REQUEST_BODY(303),
        +    INVALID_SEARCH_FILTER_CRITERIA(304),
        +    INVALID_REQUESTED_VERSION(305),
        +    CHECKSUM_ERROR(306),
        +    ARTIFACT_TOO_BIG(307),
        +    ACTION_NOT_FOUND(308),
        +    ARTIFACT_NOT_FOUND(309),
        +    METHOD_NOT_ALLOWED(310),
        +    INVALID_REQUEST_PARAM(311),
        +    ARTIFACT_PROTECTION_INVALID(312),
        +    ACTION_NAME_UPDATE_NOT_ALLOWED(501),
        +    //METHOD_NOT_ALLOWED(502),
        +    ACTION_NAME_ALREADY_EXISTS(503),
        +    MULTIPLE_FILTER_CRITERIA_NOT_SUPPORTED(504),
        +    UPDATE_ON_UNLOCKED_ENTITY(505),
        +    UPDATE_NOT_ALLOWED(506),
        +    //METHOD_NOT_ALLOWED(507),
        +    CHECKIN_ON_UNLOCKED_ENTITY(508),
        +    SUBMIT_ON_FINAL_ENTITY(509),
        +    SUBMIT_ON_LOCKED_ENTITY_OTHER_USER(510),
        +    UNDO_CHECKOUT_ON_UNLOCKED_ENTITY(511),
        +    ACTION_NOT_LOCKED(512),
        +    ARTIFACT_ALREADY_EXISTS(513),
        +    ARTIFACT_UPDATE_READ_ONLY(514),
        +    ARTIFACT_DELETE_READ_ONLY(515),
        +    ARTIFACT_NAME_INVALID(516),
        +    ARTIFACT_CREATE_UPDATE_NOT_ALLOWED(518),
        +    QUERY_FAILURE(519);
        +  // @formatter:on
         
        -  MISSING_AUTHORIZATION(100),
        -  FORBIDDEN(101),
        -  UPDATE_ON_LOCKED_ENTITY(102),
        -  CHECKIN_ON_LOCKED_ENTITY_OTHER_USER(103),
        -  CHECKOUT_ON_LOCKED_ENTITY(104),
        -  UNDO_CHECKOUT_ON_LOCKED_ENTITY(105),
        -  DELETE_ARTIFACT_ON_LOCKED_ENTITY(106),
        -  DELETE_ON_LOCKED_ENTITY_OTHER_USER(107),
        -  INTERNAL_SERVER_ERROR(201),
        -  MISSING_MANDATORY_PARAMS(300),
        -  MISSING_INSTANCE_ID_HEADER(301),
        -  MISSING_REQUEST_ID_HEADER(302),
        -  MISSING_REQUEST_BODY(303),
        -  INVALID_SEARCH_FILTER_CRITERIA(304),
        -  INVALID_REQUESTED_VERSION(305),
        -  CHECKSUM_ERROR(306),
        -  ARTIFACT_TOO_BIG(307),
        -  ACTION_NOT_FOUND(308),
        -  ARTIFACT_NOT_FOUND(309),
        -  METHOD_NOT_ALLOWED(310),
        -  INVALID_REQUEST_PARAM(311),
        -  ARTIFACT_PROTECTION_INVALID(312),
        -  ACTION_NAME_UPDATE_NOT_ALLOWED(501),
        -  //METHOD_NOT_ALLOWED(502),
        -  ACTION_NAME_ALREADY_EXISTS(503),
        -  MULTIPLE_FILTER_CRITERIA_NOT_SUPPORTED(504),
        -  UPDATE_ON_UNLOCKED_ENTITY(505),
        -  UPDATE_NOT_ALLOWED(506),
        -  //METHOD_NOT_ALLOWED(507),
        -  CHECKIN_ON_UNLOCKED_ENTITY(508),
        -  SUBMIT_ON_FINAL_ENTITY(509),
        -  SUBMIT_ON_LOCKED_ENTITY_OTHER_USER(510),
        -  UNDO_CHECKOUT_ON_UNLOCKED_ENTITY(511),
        -  ACTION_NOT_LOCKED(512),
        -  ARTIFACT_ALREADY_EXISTS(513),
        -  ARTIFACT_UPDATE_READ_ONLY(514),
        -  ARTIFACT_DELETE_READ_ONLY(515),
        -  ARTIFACT_NAME_INVALID(516),
        -  ARTIFACT_CREATE_UPDATE_NOT_ALLOWED(518),
        -  QUERY_FAILURE(519);
        -
        -  private static Map mapValueToEnum = new HashMap<>();
        +    private static Map mapValueToEnum = new HashMap<>();
         
        -  static {
        -    for (ActionLogResponseCode responseCode : ActionLogResponseCode.values()) {
        -      mapValueToEnum.put(responseCode.value, responseCode);
        +    static {
        +        for (ActionLogResponseCode responseCode : ActionLogResponseCode.values()) {
        +            mapValueToEnum.put(responseCode.value, responseCode);
        +        }
             }
        -  }
         
        -  private int value;
        +    private int value;
         
        -  ActionLogResponseCode(int value) {
        -    this.value = value;
        -  }
        +    ActionLogResponseCode(int value) {
        +        this.value = value;
        +    }
         
        -  public static ActionLogResponseCode parseValue(int value) {
        -    return mapValueToEnum.get(value);
        -  }
        +    public static ActionLogResponseCode parseValue(int value) {
        +        return mapValueToEnum.get(value);
        +    }
         
        -  public int getValue() {
        -    return value;
        -  }
        +    public int getValue() {
        +        return value;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionRequest.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionRequest.java
        index 6ba70b08ee..f438060150 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionRequest.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionRequest.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
         public enum ActionRequest {
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionStatus.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionStatus.java
        index af3516e1eb..651fd19568 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionStatus.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionStatus.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,12 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
        -public enum ActionStatus {
        -  Locked,
        -  Available,
        -  Final,
        -  Deleted
        -}
        +public enum ActionStatus {Locked, Available, Final, Deleted}
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionSubOperation.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionSubOperation.java
        index 3298be7179..1520c6f3a1 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionSubOperation.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/ActionSubOperation.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,43 +17,44 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
         public enum ActionSubOperation {
        -  //Versioning operations
        -  CREATE_ACTION_VERSION,
        -  CREATE_ACTION_UNIQUE_VALUE,
        -  GET_ACTION_VERSION,
        -  //Action DAO operations
        -  CREATE_ACTION_ENTITY,
        -  GET_ACTIONENTITY_BY_ACTIONINVID,
        -  GET_ACTIONENTITY_BY_ACTIONUUID,
        -  GET_ACTIONENTITY_BY_VENDOR,
        -  GET_ACTIONENTITY_BY_CATEGORY,
        -  GET_ACTIONENTITY_BY_MODEL,
        -  GET_ACTIONENTITY_BY_COMPONENT,
        -  GET_ACTIONENTITY_BY_VERSION,
        -  GET_ALL_ACTIONS,
        -  GET_ACTIONINVID_BY_NAME,
        +    // @formatter:off
        +    //Versioning operations
        +    CREATE_ACTION_VERSION,
        +    CREATE_ACTION_UNIQUE_VALUE,
        +    GET_ACTION_VERSION,
        +    //Action DAO operations
        +    CREATE_ACTION_ENTITY,
        +    GET_ACTIONENTITY_BY_ACTIONINVID,
        +    GET_ACTIONENTITY_BY_ACTIONUUID,
        +    GET_ACTIONENTITY_BY_VENDOR,
        +    GET_ACTIONENTITY_BY_CATEGORY,
        +    GET_ACTIONENTITY_BY_MODEL,
        +    GET_ACTIONENTITY_BY_COMPONENT,
        +    GET_ACTIONENTITY_BY_VERSION,
        +    GET_ALL_ACTIONS,
        +    GET_ACTIONINVID_BY_NAME,
             GET_OPEN_ECOMP_COMPONENTS_ENTITY,
        -  GET_VERSIONINFO_FOR_ALL_ACTIONS,
        -  GET_NAME_BY_ACTIONINVID,
        -  CHECKOUT_ACTION,
        -  UNDO_CHECKOUT_ACTION,
        -  CHECKIN_ACTION,
        -  SUBMIT_ACTION,
        -  UPDATE_ACTION,
        -  UPDATE_ACTION_STATUS,
        -  DELETE_UNIQUEVALUE,
        -  DELETE_ACTIONVERSION,
        -  DELETE_ARTIFACT,
        -  DELETE_ACTION,
        -  //Validations
        -  VALIDATE_ACTION_UNIQUE_NAME,
        -  //Artifacts
        -  GET_ARTIFACT_BY_ARTIFACTUUID,
        -  CREATE_ACTION_ARTIFACT,
        -  UPDATE_ACTION_ARTIFACT,
        -  DELETE_ACTION_ARTIFACT,
        +    GET_VERSIONINFO_FOR_ALL_ACTIONS,
        +    GET_NAME_BY_ACTIONINVID,
        +    CHECKOUT_ACTION,
        +    UNDO_CHECKOUT_ACTION,
        +    CHECKIN_ACTION,
        +    SUBMIT_ACTION,
        +    UPDATE_ACTION,
        +    UPDATE_ACTION_STATUS,
        +    DELETE_UNIQUEVALUE,
        +    DELETE_ACTIONVERSION,
        +    DELETE_ARTIFACT,
        +    DELETE_ACTION,
        +    //Validations
        +    VALIDATE_ACTION_UNIQUE_NAME,
        +    //Artifacts
        +    GET_ARTIFACT_BY_ARTIFACTUUID,
        +    CREATE_ACTION_ARTIFACT,
        +    UPDATE_ACTION_ARTIFACT,
        +    DELETE_ACTION_ARTIFACT,
        +    // @formatter:on
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/OpenEcompComponent.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/OpenEcompComponent.java
        index bf3f0c54f9..1858833d82 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/OpenEcompComponent.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/types/OpenEcompComponent.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,88 +17,87 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.types;
         
         import org.openecomp.sdc.action.dao.types.OpenEcompComponentEntity;
         
         public class OpenEcompComponent {
         
        -  private String id;
        -  private String name;
        -
        -  public OpenEcompComponent() {
        -    //Default constructor
        -  }
        -
        -  public OpenEcompComponent(String name, String id) {
        -    this.name = name;
        -    this.id = id;
        -  }
        -
        -  public String getId() {
        -    return id;
        -  }
        +    private String id;
        +    private String name;
         
        -  public void setId(String id) {
        -    this.id = id;
        -  }
        -
        -  public String getName() {
        -    return name;
        -  }
        +    public OpenEcompComponent() {
        +        //Default constructor
        +    }
         
        -  public void setName(String name) {
        -    this.name = name;
        -  }
        +    public OpenEcompComponent(String name, String id) {
        +        this.name = name;
        +        this.id = id;
        +    }
         
        -  /**
        -   * To entity OPENECOMP component entity.
        -   *
        -   * @return the OPENECOMP component entity
        -   */
        -  public OpenEcompComponentEntity toEntity() {
        -    OpenEcompComponentEntity destination = new OpenEcompComponentEntity();
        -    destination.setId(this.getId());
        -    destination.setName(this.getName());
        -    return destination;
        -  }
        +    public String getId() {
        +        return id;
        +    }
         
        -  @Override
        -  public int hashCode() {
        -    final int prime = 31;
        -    int result = 1;
        -    result = prime * result + ((id == null) ? 0 : id.hashCode());
        -    result = prime * result + ((name == null) ? 0 : name.hashCode());
        -    return result;
        -  }
        +    public void setId(String id) {
        +        this.id = id;
        +    }
         
        -  @Override
        -  public boolean equals(Object object) {
        -    if (this == object) {
        -      return true;
        +    public String getName() {
        +        return name;
             }
        -    if (object == null) {
        -      return false;
        +
        +    public void setName(String name) {
        +        this.name = name;
             }
        -    if (this.getClass() != object.getClass()) {
        -      return false;
        +
        +    /**
        +     * To entity OPENECOMP component entity.
        +     *
        +     * @return the OPENECOMP component entity
        +     */
        +    public OpenEcompComponentEntity toEntity() {
        +        OpenEcompComponentEntity destination = new OpenEcompComponentEntity();
        +        destination.setId(this.getId());
        +        destination.setName(this.getName());
        +        return destination;
             }
        -    OpenEcompComponent obj = (OpenEcompComponent) object;
        -    if (id == null) {
        -      if (obj.id != null) {
        -        return false;
        -      }
        -    } else if (!id.equals(obj.id)) {
        -      return false;
        +
        +    @Override
        +    public int hashCode() {
        +        final int prime = 31;
        +        int result = 1;
        +        result = prime * result + ((id == null) ? 0 : id.hashCode());
        +        result = prime * result + ((name == null) ? 0 : name.hashCode());
        +        return result;
             }
        -    if (name == null) {
        -      if (obj.name != null) {
        -        return false;
        -      }
        -    } else if (!name.equals(obj.name)) {
        -      return false;
        +
        +    @Override
        +    public boolean equals(Object object) {
        +        if (this == object) {
        +            return true;
        +        }
        +        if (object == null) {
        +            return false;
        +        }
        +        if (this.getClass() != object.getClass()) {
        +            return false;
        +        }
        +        OpenEcompComponent obj = (OpenEcompComponent) object;
        +        if (id == null) {
        +            if (obj.id != null) {
        +                return false;
        +            }
        +        } else if (!id.equals(obj.id)) {
        +            return false;
        +        }
        +        if (name == null) {
        +            if (obj.name != null) {
        +                return false;
        +            }
        +        } else if (!name.equals(obj.name)) {
        +            return false;
        +        }
        +        return true;
             }
        -    return true;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java
        index 28195b334f..4e0c5658fa 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java
        @@ -17,24 +17,106 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.util;
         
        -import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
        -import org.openecomp.sdc.action.logging.CategoryLogLevel;
        -import org.openecomp.sdc.action.types.ActionLogResponseCode;
        -import org.openecomp.sdc.action.types.ActionSubOperation;
        -import org.slf4j.MDC;
        +import static org.openecomp.sdc.action.ActionConstants.BEGIN_TIMESTAMP;
        +import static org.openecomp.sdc.action.ActionConstants.ELAPSED_TIME;
        +import static org.openecomp.sdc.action.ActionConstants.END_TIMESTAMP;
        +import static org.openecomp.sdc.action.ActionConstants.ERROR_CATEGORY;
        +import static org.openecomp.sdc.action.ActionConstants.ERROR_CODE;
        +import static org.openecomp.sdc.action.ActionConstants.ERROR_DESCRIPTION;
        +import static org.openecomp.sdc.action.ActionConstants.RESPONSE_CODE;
        +import static org.openecomp.sdc.action.ActionConstants.RESPONSE_DESCRIPTION;
        +import static org.openecomp.sdc.action.ActionConstants.SERVICE_METRIC_BEGIN_TIMESTAMP;
        +import static org.openecomp.sdc.action.ActionConstants.STATUS_CODE;
        +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY;
        +import static org.openecomp.sdc.action.ActionConstants.TARGET_SERVICE_NAME;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_ALREADY_EXISTS_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_CHECKSUM_ERROR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DELETE_READ_ONLY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_ENTITY_NOT_EXIST_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_INVALID_NAME_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_INVALID_PROTECTION_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_TOO_BIG_ERROR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_UPDATE_READ_ONLY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_AUTHENTICATION_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_AUTHORIZATION_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKIN_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKOUT_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_CHECKOUT_ON_LOCKED_ENTITY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_DELETE_ON_LOCKED_ENTITY_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_UNIQUE_VALUE_ERROR;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_INSTANCE_ID_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_PARAM_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_REQUEST_BODY_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_REQUEST_ID_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INVALID_SEARCH_CRITERIA;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_MULT_SEARCH_CRITERIA;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_REQUEST_INVALID_GENERIC_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_SUBMIT_LOCKED_ENTITY_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UNDO_CHECKOUT_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_INVALID_VERSION;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_CODE_NAME;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ACTION_NAME_ALREADY_EXISTS;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ACTION_NAME_UPDATE_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ACTION_NOT_FOUND;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ACTION_NOT_LOCKED;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_ALREADY_EXISTS;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_DELETE_READ_ONLY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_NAME_INVALID;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_NOT_FOUND;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_PROTECTION_INVALID;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_TOO_BIG;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.ARTIFACT_UPDATE_READ_ONLY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.CHECKIN_ON_LOCKED_ENTITY_OTHER_USER;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.CHECKIN_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.CHECKOUT_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.CHECKSUM_ERROR;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.DELETE_ARTIFACT_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.DELETE_ON_LOCKED_ENTITY_OTHER_USER;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.INTERNAL_SERVER_ERROR;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.INVALID_REQUESTED_VERSION;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.INVALID_REQUEST_PARAM;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.INVALID_SEARCH_FILTER_CRITERIA;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.MISSING_AUTHORIZATION;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.MISSING_INSTANCE_ID_HEADER;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.MISSING_REQUEST_BODY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.MISSING_REQUEST_ID_HEADER;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.MULTIPLE_FILTER_CRITERIA_NOT_SUPPORTED;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.QUERY_FAILURE;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.SUBMIT_ON_FINAL_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.SUBMIT_ON_LOCKED_ENTITY_OTHER_USER;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.UNDO_CHECKOUT_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_NOT_ALLOWED;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_ON_LOCKED_ENTITY;
        +import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_ON_UNLOCKED_ENTITY;
         
         import java.text.DateFormat;
         import java.text.SimpleDateFormat;
         import java.time.ZoneOffset;
        -import java.util.*;
        +import java.util.Date;
        +import java.util.EnumMap;
        +import java.util.HashMap;
        +import java.util.Map;
        +import java.util.TimeZone;
         import java.util.function.LongSupplier;
        -
        -import static org.openecomp.sdc.action.ActionConstants.*;
        -import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
        -import static org.openecomp.sdc.action.types.ActionLogResponseCode.*;
        +import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
        +import org.openecomp.sdc.action.logging.CategoryLogLevel;
        +import org.openecomp.sdc.action.types.ActionLogResponseCode;
        +import org.openecomp.sdc.action.types.ActionSubOperation;
        +import org.slf4j.MDC;
         
         public class ActionUtil {
         
        @@ -44,6 +126,9 @@ public class ActionUtil {
             private static final Map errorCodeMap = initErrorCodeMap();
             private static final EnumMap errorTypeMap = initErrorTypeMap();
         
        +    private ActionUtil() {
        +    }
        +
             private static Map initErrorCodeMap() {
                 Map map = new HashMap<>();
                 map.put(ACTION_REQUEST_INVALID_GENERIC_CODE, INVALID_REQUEST_PARAM);
        @@ -94,9 +179,6 @@ public class ActionUtil {
                 return map;
             }
         
        -    private ActionUtil() {
        -    }
        -
             /**
              * Get Current Timestamp in UTC format.
              *
        @@ -140,7 +222,6 @@ public class ActionUtil {
                 if (subOperation != null) {
                     MDC.put(TARGET_SERVICE_NAME, subOperation.name());
                 }
        -
                 MDC.put(TARGET_ENTITY, targetEntity);
             }
         
        @@ -157,8 +238,7 @@ public class ActionUtil {
                 actionLogPostProcessor(statusCode, null, isServiceMetricLog);
             }
         
        -    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
        -                                              boolean isServiceMetricLog) {
        +    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode, boolean isServiceMetricLog) {
                 actionLogPostProcessor(statusCode, responseCode, null, isServiceMetricLog);
             }
         
        @@ -170,8 +250,7 @@ public class ActionUtil {
              * @param responseDescription the response description
              * @param isServiceMetricLog  the is service metric log
              */
        -    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
        -                                              String responseDescription,
        +    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode, String responseDescription,
                                                       boolean isServiceMetricLog) {
                 actionLogPostProcessor(statusCode, responseCode, responseDescription, isServiceMetricLog, System::currentTimeMillis);
             }
        @@ -184,9 +263,7 @@ public class ActionUtil {
              * @param responseDescription the response description
              * @param isServiceMetricLog  the is service metric log
              */
        -    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode,
        -                                              String responseDescription,
        -                                              boolean isServiceMetricLog,
        +    public static void actionLogPostProcessor(ResponseStatus statusCode, String responseCode, String responseDescription, boolean isServiceMetricLog,
                                                       LongSupplier getCurrentTime) {
                 MDC.put(STATUS_CODE, statusCode.name());
                 if (responseCode != null) {
        @@ -213,8 +290,7 @@ public class ActionUtil {
              * @param errorCode        Action Library exception code
              * @param errorDescription Description of the error
              */
        -    public static void actionErrorLogProcessor(CategoryLogLevel errorCategory, String errorCode,
        -                                               String errorDescription) {
        +    public static void actionErrorLogProcessor(CategoryLogLevel errorCategory, String errorCode, String errorDescription) {
                 MDC.put(ERROR_CATEGORY, errorCategory.name());
                 if (errorCode != null) {
                     MDC.put(ERROR_CODE, getLogResponseCode(errorCode) + (errorTypeMap.getOrDefault(errorCategory, "")));
        @@ -223,8 +299,7 @@ public class ActionUtil {
             }
         
             /**
        -     * Method to convert Action Library exception codes to OPENECOMP Audit codes in {@link
        -     * ActionLogResponseCode} e.g: ACT1060 --> 201
        +     * Method to convert Action Library exception codes to OPENECOMP Audit codes in {@link ActionLogResponseCode} e.g: ACT1060 --> 201
              *
              * @param errorCode Action library exception code
              * @return Audit log code corresponding to the Action Library exception
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDao.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDao.java
        index 86ae7510a6..c99c0ce039 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDao.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDao.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healthcheck.dao;
         
        +import java.util.List;
         import org.openecomp.core.dao.BaseDao;
         import org.openecomp.sdc.action.dao.types.ActionEntity;
         import org.openecomp.sdc.action.errors.ActionException;
        @@ -27,25 +27,21 @@ import org.openecomp.sdc.action.types.Action;
         import org.openecomp.sdc.action.types.OpenEcompComponent;
         import org.openecomp.sdc.versioning.dao.VersionableDao;
         
        -import java.util.List;
        -
         public interface ActionDao extends VersionableDao, BaseDao {
         
        -  public Action createAction(Action actionDto) throws ActionException;
        -
        -  public Action updateAction(Action actionDto) throws ActionException;
        +    public Action createAction(Action actionDto) throws ActionException;
         
        -  public void deleteAction(String actionInvariantUuId) throws ActionException;
        +    public Action updateAction(Action actionDto) throws ActionException;
         
        -  public List getFilteredActions(String filterType, String filterId) throws ActionException;
        +    public void deleteAction(String actionInvariantUuId) throws ActionException;
         
        -  public Action getActionsByActionUuId(String uniqueId) throws ActionException;
        +    public List getFilteredActions(String filterType, String filterId) throws ActionException;
         
        -  public List getEcompComponents() throws ActionException;
        +    public Action getActionsByActionUuId(String uniqueId) throws ActionException;
         
        -  public List getActionsByActionInvariantUuId(String actionInvariantUuId)
        -      throws ActionException;
        +    public List getEcompComponents() throws ActionException;
         
        -  public Action getLockedAction(String actionInvariantUuId, String user) throws ActionException;
        +    public List getActionsByActionInvariantUuId(String actionInvariantUuId) throws ActionException;
         
        +    public Action getLockedAction(String actionInvariantUuId, String user) throws ActionException;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDaoFactory.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDaoFactory.java
        index 0ecf04d843..683350b75a 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/healthcheck/dao/ActionDaoFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.healthcheck.dao;
         
         import org.openecomp.core.factory.api.AbstractComponentFactory;
        @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory;
         
         public abstract class ActionDaoFactory extends AbstractComponentFactory {
         
        -  public static ActionDaoFactory getInstance() {
        -    return AbstractFactory.getInstance(ActionDaoFactory.class);
        -  }
        +    public static ActionDaoFactory getInstance() {
        +        return AbstractFactory.getInstance(ActionDaoFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoFactoryImpl.java
        index 5c308e7f64..a37745bbae 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,18 +17,17 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao.impl;
         
         import org.openecomp.sdc.action.dao.ActionArtifactDao;
         import org.openecomp.sdc.action.dao.ActionArtifactDaoFactory;
         
        -
         public class ActionArtifactDaoFactoryImpl extends ActionArtifactDaoFactory {
        -  private static ActionArtifactDao instance = new ActionArtifactDaoImpl();
         
        -  @Override
        -  public ActionArtifactDao createInterface() {
        -    return instance;
        -  }
        +    private static ActionArtifactDao instance = new ActionArtifactDaoImpl();
        +
        +    @Override
        +    public ActionArtifactDao createInterface() {
        +        return instance;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java
        index f9e0b00ff8..f8c2482fe9 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,14 +17,23 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao.impl;
         
        +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE;
        +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR;
        +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE;
        +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG;
        +
         import com.datastax.driver.core.exceptions.NoHostAvailableException;
         import com.datastax.driver.mapping.Mapper;
         import com.datastax.driver.mapping.Result;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        +import java.util.Collection;
        +import java.util.List;
         import org.openecomp.core.dao.impl.CassandraBaseDao;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
        @@ -38,111 +47,92 @@ import org.openecomp.sdc.action.util.ActionUtil;
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -import java.util.Collection;
        -import java.util.List;
        -
        -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE;
        -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR;
        -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB;
        -import static org.openecomp.sdc.action.errors.ActionErrorConstants.*;
        -
        -
        -public class ActionArtifactDaoImpl extends CassandraBaseDao
        -    implements ActionArtifactDao {
        -  private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        -  private static Mapper mapper =
        -      noSqlDb.getMappingManager().mapper(ActionArtifactEntity.class);
        -  private static ActionArtifactAccessor accessor =
        -      noSqlDb.getMappingManager().createAccessor(ActionArtifactAccessor.class);
        -  private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
        +public class ActionArtifactDaoImpl extends CassandraBaseDao implements ActionArtifactDao {
         
        -  @Override
        -  protected Mapper getMapper() {
        -    return mapper;
        -  }
        +    private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        +    private static Mapper mapper = noSqlDb.getMappingManager().mapper(ActionArtifactEntity.class);
        +    private static ActionArtifactAccessor accessor = noSqlDb.getMappingManager().createAccessor(ActionArtifactAccessor.class);
        +    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
         
        -  @Override
        -  protected Object[] getKeys(ActionArtifactEntity entity) {
        -    return new Object[]{entity.getArtifactUuId(), entity.getEffectiveVersion()};
        -  }
        +    @Override
        +    protected Mapper getMapper() {
        +        return mapper;
        +    }
         
        -  @Override
        -  public Collection list(ActionArtifactEntity entity) {
        -    return null;
        -  }
        +    @Override
        +    protected Object[] getKeys(ActionArtifactEntity entity) {
        +        return new Object[]{entity.getArtifactUuId(), entity.getEffectiveVersion()};
        +    }
         
        +    @Override
        +    public Collection list(ActionArtifactEntity entity) {
        +        return null;
        +    }
         
        -  @Override
        -  public void uploadArtifact(ActionArtifact data) {
        -    log.debug(" entering uploadArtifact with artifactName= " + data.getArtifactName());
        -    try {
        -      ActionUtil.actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_ARTIFACT, TARGET_ENTITY_DB);
        -      this.create(data.toEntity());
        -      ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        -      log.metrics("");
        -    } catch (NoHostAvailableException noHostAvailableException) {
        -      logGenericException(noHostAvailableException);
        -      throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE,
        -          ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +    @Override
        +    public void uploadArtifact(ActionArtifact data) {
        +        log.debug(" entering uploadArtifact with artifactName= " + data.getArtifactName());
        +        try {
        +            ActionUtil.actionLogPreProcessor(ActionSubOperation.CREATE_ACTION_ARTIFACT, TARGET_ENTITY_DB);
        +            this.create(data.toEntity());
        +            ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        +            log.metrics("");
        +        } catch (NoHostAvailableException noHostAvailableException) {
        +            logGenericException(noHostAvailableException);
        +            throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +        }
        +        log.debug(" exit uploadArtifact with artifactName= " + data.getArtifactName());
             }
        -    log.debug(" exit uploadArtifact with artifactName= " + data.getArtifactName());
        -  }
         
        -  @Override
        -  public ActionArtifact downloadArtifact(int effectiveVersion, String artifactUuId) {
        -    log.debug(" entering downloadArtifact with artifactUUID= " + artifactUuId);
        -    ActionArtifact actionArtifact = null;
        -    try {
        -      ActionUtil
        -          .actionLogPreProcessor(ActionSubOperation.GET_ARTIFACT_BY_ARTIFACTUUID, TARGET_ENTITY_DB);
        -      Result result = null;
        -      result = accessor.getArtifactByUuId(effectiveVersion, artifactUuId);
        -      ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        -      log.metrics("");
        -      List artifactEntities = result.all();
        -      if (artifactEntities != null && !artifactEntities.isEmpty()) {
        -        ActionArtifactEntity artifactEntity = artifactEntities.get(0);
        -        actionArtifact = artifactEntity.toDto();
        -      }
        -    } catch (NoHostAvailableException noHostAvailableException) {
        -      logGenericException(noHostAvailableException);
        -      throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE,
        -          ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +    @Override
        +    public ActionArtifact downloadArtifact(int effectiveVersion, String artifactUuId) {
        +        log.debug(" entering downloadArtifact with artifactUUID= " + artifactUuId);
        +        ActionArtifact actionArtifact = null;
        +        try {
        +            ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ARTIFACT_BY_ARTIFACTUUID, TARGET_ENTITY_DB);
        +            Result result = null;
        +            result = accessor.getArtifactByUuId(effectiveVersion, artifactUuId);
        +            ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        +            log.metrics("");
        +            List artifactEntities = result.all();
        +            if (artifactEntities != null && !artifactEntities.isEmpty()) {
        +                ActionArtifactEntity artifactEntity = artifactEntities.get(0);
        +                actionArtifact = artifactEntity.toDto();
        +            }
        +        } catch (NoHostAvailableException noHostAvailableException) {
        +            logGenericException(noHostAvailableException);
        +            throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +        }
        +        log.debug(" exit downloadArtifact with artifactUUID= " + artifactUuId);
        +        return actionArtifact;
             }
        -    log.debug(" exit downloadArtifact with artifactUUID= " + artifactUuId);
        -    return actionArtifact;
        -  }
         
        -  @Override
        -  public void updateArtifact(ActionArtifact data) {
        -    log.debug(" entering updateArtifact with artifactName= " + data.getArtifactName());
        -    try {
        -      ActionUtil.actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION_ARTIFACT, TARGET_ENTITY_DB);
        -      this.update(data.toEntity());
        -      ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        -      log.metrics("");
        -    } catch (NoHostAvailableException noHostAvailableException) {
        -      logGenericException(noHostAvailableException);
        -      throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE,
        -          ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +    @Override
        +    public void updateArtifact(ActionArtifact data) {
        +        log.debug(" entering updateArtifact with artifactName= " + data.getArtifactName());
        +        try {
        +            ActionUtil.actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION_ARTIFACT, TARGET_ENTITY_DB);
        +            this.update(data.toEntity());
        +            ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
        +            log.metrics("");
        +        } catch (NoHostAvailableException noHostAvailableException) {
        +            logGenericException(noHostAvailableException);
        +            throw new ActionException(ACTION_INTERNAL_SERVER_ERR_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG);
        +        }
        +        log.debug(" exit updateArtifact with artifactName= " + data.getArtifactName());
             }
        -    log.debug(" exit updateArtifact with artifactName= " + data.getArtifactName());
        -  }
         
        -  private void logGenericException(Exception exception) {
        -    ActionUtil.actionLogPostProcessor(ERROR, ACTION_QUERY_FAILURE_CODE,
        -        ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, false);
        -    log.metrics("");
        -    ActionUtil.actionErrorLogProcessor(CategoryLogLevel.FATAL, ACTION_QUERY_FAILURE_CODE,
        -        ACTION_QUERY_FAILURE_MSG);
        -    log.error(exception.getMessage());
        -  }
        +    private void logGenericException(Exception exception) {
        +        ActionUtil.actionLogPostProcessor(ERROR, ACTION_QUERY_FAILURE_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, false);
        +        log.metrics("");
        +        ActionUtil.actionErrorLogProcessor(CategoryLogLevel.FATAL, ACTION_QUERY_FAILURE_CODE, ACTION_QUERY_FAILURE_MSG);
        +        log.error(exception.getMessage());
        +    }
         
        -  @Accessor
        -  interface ActionArtifactAccessor {
        +    @Accessor
        +    interface ActionArtifactAccessor {
         
        -    @Query(
        -        "SELECT * FROM action_artifact WHERE effective_version <= ? and artifactuuid = ? limit 1")
        -    Result getArtifactByUuId(int effectiveVersion, String artifactUuId);
        -  }
        +        @Query("SELECT * FROM action_artifact WHERE effective_version <= ? and artifactuuid = ? limit 1")
        +        Result getArtifactByUuId(int effectiveVersion, String artifactUuId);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoFactoryImpl.java
        index 72279d41fd..285e54fde7 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,18 +17,17 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.action.dao.impl;
         
         import org.openecomp.sdc.action.dao.ActionDao;
         import org.openecomp.sdc.action.dao.ActionDaoFactory;
         
        -
         public class ActionDaoFactoryImpl extends ActionDaoFactory {
        -  private static ActionDao instance = new ActionDaoImpl();
         
        -  @Override
        -  public ActionDao createInterface() {
        -    return instance;
        -  }
        +    private static ActionDao instance = new ActionDaoImpl();
        +
        +    @Override
        +    public ActionDao createInterface() {
        +        return instance;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java
        index f22fa08ee3..cdd2d5a02e 100644
        --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.action.dao.impl;
         
         import static com.datastax.driver.core.querybuilder.QueryBuilder.eq;
        @@ -51,7 +50,6 @@ import com.datastax.driver.mapping.Mapper;
         import com.datastax.driver.mapping.Result;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        -
         import java.util.ArrayList;
         import java.util.Collection;
         import java.util.HashSet;
        @@ -60,7 +58,6 @@ import java.util.List;
         import java.util.Map;
         import java.util.Set;
         import java.util.stream.Collectors;
        -
         import org.openecomp.core.dao.impl.CassandraBaseDao;
         import org.openecomp.core.nosqldb.api.NoSqlDb;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
        @@ -90,37 +87,22 @@ import org.openecomp.sdc.versioning.types.VersionableEntityMetadata;
         import org.slf4j.MDC;
         
         public class ActionDaoImpl extends CassandraBaseDao implements ActionDao {
        +
             private static final String FOR_VERSIONS = " for versions ";
             private static final String VERSION = "version";
             private static final String ACTION = "Action";
        -    private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance()
        -            .createInterface();
        -    private static Mapper mapper = noSqlDb.getMappingManager()
        -            .mapper(ActionEntity.class);
        -    private static ActionAccessor accessor = noSqlDb.getMappingManager()
        -            .createAccessor(ActionAccessor.class);
        -    private static VersionInfoDao versionInfoDao = VersionInfoDaoFactory.getInstance()
        -            .createInterface();
        -    private static VersionInfoDeletedDao versionInfoDeletedDao = VersionInfoDeletedDaoFactory.getInstance()
        -            .createInterface();
        -
        -    private final Logger log = LoggerFactory.getLogger(this.getClass()
        -            .getName());
        +    private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface();
        +    private static Mapper mapper = noSqlDb.getMappingManager().mapper(ActionEntity.class);
        +    private static ActionAccessor accessor = noSqlDb.getMappingManager().createAccessor(ActionAccessor.class);
        +    private static VersionInfoDao versionInfoDao = VersionInfoDaoFactory.getInstance().createInterface();
        +    private static VersionInfoDeletedDao versionInfoDeletedDao = VersionInfoDeletedDaoFactory.getInstance().createInterface();
        +    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
         
             @Override
             public void registerVersioning(String versionableEntityType) {
        -        ActionVersioningManagerFactory.getInstance()
        -                .createInterface()
        -                .register(versionableEntityType, new VersionableEntityMetadata(mapper.getTableMetadata()
        -                        .getName(),
        -                        mapper.getTableMetadata()
        -                                .getPartitionKey()
        -                                .get(0)
        -                                .getName(),
        -                        mapper.getTableMetadata()
        -                                .getPartitionKey()
        -                                .get(1)
        -                                .getName()));
        +        ActionVersioningManagerFactory.getInstance().createInterface().register(versionableEntityType,
        +            new VersionableEntityMetadata(mapper.getTableMetadata().getName(), mapper.getTableMetadata().getPartitionKey().get(0).getName(),
        +                mapper.getTableMetadata().getPartitionKey().get(1).getName()));
             }
         
             @Override
        @@ -159,24 +141,18 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                     log.debug("entering deleteAction with actionInvariantUuId = " + actionInvariantUuId);
                     ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
                     VersionInfoDeletedEntity activeVersionEntity = versionInfoDeletedDao
        -                    .get(new VersionInfoDeletedEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
        +                .get(new VersionInfoDeletedEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
                     ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                     log.metrics("");
        -
                     Version activeVersion = activeVersionEntity.getActiveVersion();
        -            Statement getNameFromInvUuId = QueryBuilder.select()
        -                    .column("name")
        -                    .from("dox", ACTION)
        -                    .where(eq("actioninvariantuuid", actionInvariantUuId))
        -                    .and(in(VERSION, activeVersion));
        +            Statement getNameFromInvUuId = QueryBuilder.select().column("name").from("dox", ACTION)
        +                .where(eq("actioninvariantuuid", actionInvariantUuId)).and(in(VERSION, activeVersion));
                     ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_NAME_BY_ACTIONINVID, TARGET_ENTITY_DB);
                     ResultSet results = getSession().execute(getNameFromInvUuId);
                     ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                     log.metrics("");
        -
                     if (!results.isExhausted()) {
        -                String name = results.one()
        -                        .getString("name");
        +                String name = results.one().getString("name");
                         List versions = getVersionsByName(name);
                         updateActionStatusForDelete(actionInvariantUuId, versions);
                     }
        @@ -194,60 +170,56 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                 log.debug(" entering getFilteredActions By filterType = " + filterType + " With value = " + filterId);
                 try {
                     switch (filterType) {
        -            case FILTER_TYPE_VENDOR:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VENDOR, TARGET_ENTITY_DB);
        -                result = accessor.getActionsByVendor(filterId);
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                break;
        -            case FILTER_TYPE_CATEGORY:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_CATEGORY, TARGET_ENTITY_DB);
        -                result = accessor.getActionsByCategory(filterId);
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                break;
        -            case FILTER_TYPE_MODEL:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_MODEL, TARGET_ENTITY_DB);
        -                result = accessor.getActionsByModel(filterId);
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                break;
        -            case FILTER_TYPE_OPEN_ECOMP_COMPONENT:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_COMPONENT, TARGET_ENTITY_DB);
        -                result = accessor.getActionsByOpenEcompComponent(filterId);
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                break;
        -            case FILTER_TYPE_NONE:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ALL_ACTIONS, TARGET_ENTITY_DB);
        -                result = accessor.getAllActions();
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                break;
        -            case FILTER_TYPE_NAME:
        -                ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONINVID_BY_NAME, TARGET_ENTITY_DB);
        -                result = accessor.getInvIdByName(filterId);
        -                ActionUtil.actionLogPostProcessor(COMPLETE);
        -                log.metrics("");
        -                List actionEntities = result.all();
        -                if (actionEntities != null && !actionEntities.isEmpty()) {
        -                    String actionInvariantUuId = actionEntities.get(0)
        -                            .getActionInvariantUuId();
        -                    if (actionInvariantUuId != null) {
        -                        return getActionsByActionInvariantUuId(actionInvariantUuId);
        -                    } else {
        -                        return actions;
        +                case FILTER_TYPE_VENDOR:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_VENDOR, TARGET_ENTITY_DB);
        +                    result = accessor.getActionsByVendor(filterId);
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    break;
        +                case FILTER_TYPE_CATEGORY:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_CATEGORY, TARGET_ENTITY_DB);
        +                    result = accessor.getActionsByCategory(filterId);
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    break;
        +                case FILTER_TYPE_MODEL:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_MODEL, TARGET_ENTITY_DB);
        +                    result = accessor.getActionsByModel(filterId);
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    break;
        +                case FILTER_TYPE_OPEN_ECOMP_COMPONENT:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_COMPONENT, TARGET_ENTITY_DB);
        +                    result = accessor.getActionsByOpenEcompComponent(filterId);
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    break;
        +                case FILTER_TYPE_NONE:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ALL_ACTIONS, TARGET_ENTITY_DB);
        +                    result = accessor.getAllActions();
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    break;
        +                case FILTER_TYPE_NAME:
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONINVID_BY_NAME, TARGET_ENTITY_DB);
        +                    result = accessor.getInvIdByName(filterId);
        +                    ActionUtil.actionLogPostProcessor(COMPLETE);
        +                    log.metrics("");
        +                    List actionEntities = result.all();
        +                    if (actionEntities != null && !actionEntities.isEmpty()) {
        +                        String actionInvariantUuId = actionEntities.get(0).getActionInvariantUuId();
        +                        if (actionInvariantUuId != null) {
        +                            return getActionsByActionInvariantUuId(actionInvariantUuId);
        +                        } else {
        +                            return actions;
        +                        }
                             }
        -                }
        -                break;
        -            default:
        -                break;
        +                    break;
        +                default:
        +                    break;
                     }
                     if (result != null) {
        -                actions.addAll(result.all()
        -                        .stream()
        -                        .map(ActionEntity::toDto)
        -                        .collect(Collectors.toList()));
        +                actions.addAll(result.all().stream().map(ActionEntity::toDto).collect(Collectors.toList()));
                     }
                     log.debug(" exit getFilteredActions By filterType = " + filterType + " With value = " + filterId);
                 } catch (NoHostAvailableException noHostAvailableException) {
        @@ -291,10 +263,7 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                     ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                     log.metrics("");
                     if (result != null) {
        -                openEcompComponents.addAll(result.all()
        -                        .stream()
        -                        .map(OpenEcompComponentEntity::toDto)
        -                        .collect(Collectors.toList()));
        +                openEcompComponents.addAll(result.all().stream().map(OpenEcompComponentEntity::toDto).collect(Collectors.toList()));
                     }
                 } catch (NoHostAvailableException noHostAvailableException) {
                     logGenericException(noHostAvailableException);
        @@ -313,11 +282,11 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                     VersionPredicate filter = new VersionPredicate();
                     ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
                     VersionInfoEntity versionInfoEntity = versionInfoDao
        -                    .get(new VersionInfoEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
        +                .get(new VersionInfoEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
                     if (versionInfoEntity == null) {
                         // Check for action in the Delete version info table
        -                VersionInfoDeletedEntity versionInfoDeletedEntity = versionInfoDeletedDao.get(
        -                        new VersionInfoDeletedEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
        +                VersionInfoDeletedEntity versionInfoDeletedEntity = versionInfoDeletedDao
        +                    .get(new VersionInfoDeletedEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
                         if (versionInfoDeletedEntity != null) {
                             viewableVersions = versionInfoDeletedEntity.getViewableVersions();
                             // Remove intermediate minor versions from viewable versions
        @@ -337,30 +306,21 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                         }
                         // Add candidate version if available
                         if (versionInfoEntity.getCandidate() != null) {
        -                    viewableVersions.add(versionInfoEntity.getCandidate()
        -                            .getVersion());
        +                    viewableVersions.add(versionInfoEntity.getCandidate().getVersion());
                         }
                     }
        -
                     MDC.put(TARGET_ENTITY, TARGET_ENTITY_DB);
                     ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                     log.metrics("");
        -
        -            log.debug("Found " + viewableVersions + " viewable version for action with actionInvariantUuId "
        -                    + actionInvariantUuId);
        -
        +            log.debug("Found " + viewableVersions + " viewable version for action with actionInvariantUuId " + actionInvariantUuId);
                     // Fetch action data for the viewable versions
                     if (!viewableVersions.isEmpty()) {
                         ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB);
        -                Result result = accessor.getActionsByInvId(actionInvariantUuId,
        -                        new ArrayList<>(viewableVersions));
        +                Result result = accessor.getActionsByInvId(actionInvariantUuId, new ArrayList<>(viewableVersions));
                         ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                         log.metrics("");
                         if (result != null) {
        -                    actions.addAll(result.all()
        -                            .stream()
        -                            .map(ActionEntity::toDto)
        -                            .collect(Collectors.toList()));
        +                    actions.addAll(result.all().stream().map(ActionEntity::toDto).collect(Collectors.toList()));
                         }
                     }
                 } catch (NoHostAvailableException noHostAvailableException) {
        @@ -376,22 +336,17 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                 log.debug(" entering getLockedAction with actionInvariantUuId= " + actionInvariantUuId);
                 ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
                 Action action = null;
        -        VersionInfoEntity versionInfoEntity = versionInfoDao
        -                .get(new VersionInfoEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
        +        VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(ActionConstants.ACTION_VERSIONABLE_TYPE, actionInvariantUuId));
                 ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                 log.metrics("");
                 if (versionInfoEntity != null) {
                     if (versionInfoEntity.getCandidate() != null) {
        -                String actionUser = versionInfoEntity.getCandidate()
        -                        .getUser();
        +                String actionUser = versionInfoEntity.getCandidate().getUser();
                         if (actionUser != null && actionUser.equals(user)) {
                             Set versions = new HashSet<>();
        -                    versions.add(versionInfoEntity.getCandidate()
        -                            .getVersion());
        -                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID,
        -                            TARGET_ENTITY_DB);
        -                    Result result = accessor.getActionsByInvId(actionInvariantUuId,
        -                            new ArrayList<>(versions));
        +                    versions.add(versionInfoEntity.getCandidate().getVersion());
        +                    ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTIONENTITY_BY_ACTIONINVID, TARGET_ENTITY_DB);
        +                    Result result = accessor.getActionsByInvId(actionInvariantUuId, new ArrayList<>(versions));
                             ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                             log.metrics("");
                             if (result != null) {
        @@ -400,7 +355,7 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                             }
                         } else {
                             throw new ActionException(ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE,
        -                            String.format(ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER, actionUser));
        +                        String.format(ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER, actionUser));
                         }
                     } else {
                         throw new ActionException(ACTION_NOT_LOCKED_CODE, ACTION_NOT_LOCKED_MSG);
        @@ -412,8 +367,7 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
             }
         
             private void logGenericException(Exception exception) {
        -        ActionUtil.actionLogPostProcessor(ERROR, ACTION_QUERY_FAILURE_CODE,
        -                ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, false);
        +        ActionUtil.actionLogPostProcessor(ERROR, ACTION_QUERY_FAILURE_CODE, ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG, false);
                 log.metrics("");
                 ActionUtil.actionErrorLogProcessor(CategoryLogLevel.FATAL, ACTION_QUERY_FAILURE_CODE, ACTION_QUERY_FAILURE_MSG);
                 log.error(exception.getMessage());
        @@ -426,47 +380,38 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
         
             @Override
             protected Object[] getKeys(ActionEntity entity) {
        -        return new Object[] { entity.getActionInvariantUuId(), entity.getVersion() };
        +        return new Object[]{entity.getActionInvariantUuId(), entity.getVersion()};
             }
         
             @Override
             public Collection list(ActionEntity entity) {
        -        return accessor.getAllActions()
        -                .all();
        +        return accessor.getAllActions().all();
             }
         
             private void updateActionStatusForDelete(String actionInvariantUuId, List versions) {
        -        log.debug("entering updateActionStatusForDelete with actionInvariantUuId = " + actionInvariantUuId
        -                + FOR_VERSIONS + versions);
        +        log.debug("entering updateActionStatusForDelete with actionInvariantUuId = " + actionInvariantUuId + FOR_VERSIONS + versions);
                 ActionUtil.actionLogPreProcessor(ActionSubOperation.UPDATE_ACTION_STATUS, TARGET_ENTITY_DB);
                 // Update the status column of action table
        -        Statement updateStatusStatement = QueryBuilder.update("dox", ACTION)
        -                .with(set("status", ActionStatus.Deleted.name()))
        -                .where(eq("actioninvariantuuid", actionInvariantUuId))
        -                .and(in(VERSION, versions));
        +        Statement updateStatusStatement = QueryBuilder.update("dox", ACTION).with(set("status", ActionStatus.Deleted.name()))
        +            .where(eq("actioninvariantuuid", actionInvariantUuId)).and(in(VERSION, versions));
                 getSession().execute(updateStatusStatement);
                 ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                 log.metrics("");
                 // Update the status in the data field of action table
                 updateStatusInActionData(actionInvariantUuId, versions, ActionStatus.Deleted);
        -        log.debug("exit updateActionStatusForDelete with actionInvariantUuId = " + actionInvariantUuId + FOR_VERSIONS
        -                + versions);
        +        log.debug("exit updateActionStatusForDelete with actionInvariantUuId = " + actionInvariantUuId + FOR_VERSIONS + versions);
             }
         
             /**
              * Update status for a list of versions for a given action.
              *
        -     * @param actionInvariantUuId
        -     *            Invariant UUID of the action.
        -     * @param versions
        -     *            List of {@link Version} for which the status has to be
        -     *            updated.
        -     * @param status
        -     *            The status value.
        +     * @param actionInvariantUuId Invariant UUID of the action.
        +     * @param versions            List of {@link Version} for which the status has to be updated.
        +     * @param status              The status value.
              */
             private void updateStatusInActionData(String actionInvariantUuId, List versions, ActionStatus status) {
        -        log.debug("entering updateStatusInActionData for actionInvariantUuId = " + actionInvariantUuId
        -                + " and status = " + status + FOR_VERSIONS + versions);
        +        log.debug("entering updateStatusInActionData for actionInvariantUuId = " + actionInvariantUuId + " and status = " + status + FOR_VERSIONS
        +            + versions);
                 for (Version v : versions) {
                     ActionEntity entity = this.get(new ActionEntity(actionInvariantUuId, v));
                     String currentData = entity.getData();
        @@ -480,24 +425,18 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
             }
         
             /**
        -     * Get list of all major and minor version values for a given action by
        -     * action name.
        +     * Get list of all major and minor version values for a given action by action name.
              *
        -     * @param name
        -     *            Name of the action.
        +     * @param name Name of the action.
              * @return List of {@link Version} objects for the action.
              */
             private List getVersionsByName(String name) {
                 log.debug("entering getVersionsByName for Action Name = " + name);
                 ActionUtil.actionLogPreProcessor(ActionSubOperation.GET_ACTION_VERSION, TARGET_ENTITY_DB);
        -        Statement statement = QueryBuilder.select()
        -                .column(VERSION)
        -                .from("dox", ACTION)
        -                .where(eq("name", name));
        +        Statement statement = QueryBuilder.select().column(VERSION).from("dox", ACTION).where(eq("name", name));
                 ResultSet results = getSession().execute(statement);
                 ActionUtil.actionLogPostProcessor(COMPLETE, null, "", false);
                 log.metrics("");
        -
                 List versionList = new ArrayList<>();
                 for (Row row : results) {
                     Version version = row.get(VERSION, Version.class);
        @@ -536,10 +475,10 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
         
                 @Query("SELECT * FROM Action where actionUUID = ?")
                 Result actionInvariantUuId(String actionUuId);
        -
             }
         
             class VersionPredicate {
        +
                 Version activeVersion;
                 Version finalVersion;
         
        @@ -548,7 +487,6 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                     int activeMinorVersion = activeVersion.getMinor();
                     int currentMinorVersion = version.getMinor();
                     int currentMajorVersion = version.getMajor();
        -
                     if (finalVersion != null) {
                         if (finalVersion.getMajor() == activeMajorVersion && currentMajorVersion == finalVersion.getMajor()) {
                             if (currentMinorVersion < activeMinorVersion && currentMinorVersion != 0) {
        @@ -562,9 +500,7 @@ public class ActionDaoImpl extends CassandraBaseDao implements Act
                             return true;
                         }
                     }
        -
                     return false;
                 }
        -
             }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java
        index 6ca1010a2d..26b2abb794 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java
        @@ -13,11 +13,11 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.activitylog.dao;
         
         import org.openecomp.core.dao.BaseDao;
         import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
         
         public interface ActivityLogDao extends BaseDao {
        +
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java
        index 1fc7de7cbc..9b8ea62d7d 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java
        @@ -18,8 +18,8 @@ package org.openecomp.sdc.activitylog.dao;
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         
        -
         public abstract class ActivityLogDaoFactory extends AbstractComponentFactory {
        +
             public static ActivityLogDaoFactory getInstance() {
                 return AbstractFactory.getInstance(ActivityLogDaoFactory.class);
             }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java
        index f878bea2df..6b4ece08db 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java
        @@ -13,54 +13,52 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.activitylog.dao.type;
         
         import com.datastax.driver.mapping.annotations.ClusteringColumn;
         import com.datastax.driver.mapping.annotations.Column;
         import com.datastax.driver.mapping.annotations.PartitionKey;
         import com.datastax.driver.mapping.annotations.Table;
        +import java.util.Date;
         import lombok.Getter;
         import lombok.NoArgsConstructor;
         import lombok.Setter;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.Date;
        -
         @Getter
         @Setter
         @NoArgsConstructor
         @Table(keyspace = "dox", name = "activity_log")
         public class ActivityLogEntity {
        -  @PartitionKey
        -  @Column(name = "item_id")
        -  private String itemId;
        -  @ClusteringColumn(value = 1)
        -  @Column(name = "version_id")
        -  private String versionId;
        -  @ClusteringColumn
        -  @Column(name = "activity_id")
        -  private String id;
        -  private ActivityType type;
        -  private String user;
        -  private Date timestamp;
        -  private boolean success;
        -  private String message;
        -  private String comment;
         
        -  public ActivityLogEntity(String itemId, Version version) {
        -    this.itemId = itemId;
        -    this.versionId = version == null ? null : version.getId();
        -  }
        +    @PartitionKey
        +    @Column(name = "item_id")
        +    private String itemId;
        +    @ClusteringColumn(value = 1)
        +    @Column(name = "version_id")
        +    private String versionId;
        +    @ClusteringColumn
        +    @Column(name = "activity_id")
        +    private String id;
        +    private ActivityType type;
        +    private String user;
        +    private Date timestamp;
        +    private boolean success;
        +    private String message;
        +    private String comment;
        +
        +    public ActivityLogEntity(String itemId, Version version) {
        +        this.itemId = itemId;
        +        this.versionId = version == null ? null : version.getId();
        +    }
         
        -  public ActivityLogEntity(String itemId, Version version, ActivityType type, String user,
        -                           boolean success, String message, String comment) {
        -    this(itemId, version);
        -    this.type = type;
        -    this.user = user;
        -    this.success = success;
        -    this.message = message;
        -    this.comment = comment;
        -    this.timestamp = new Date();
        -  }
        +    public ActivityLogEntity(String itemId, Version version, ActivityType type, String user, boolean success, String message, String comment) {
        +        this(itemId, version);
        +        this.type = type;
        +        this.user = user;
        +        this.success = success;
        +        this.message = message;
        +        this.comment = comment;
        +        this.timestamp = new Date();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java
        index 7b2cd9ff54..5566d2b788 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.activitylog.dao.type;
         
         public enum ActivityType {
        @@ -31,5 +30,4 @@ public enum ActivityType {
           Upload_Network_Package,
           Revert,
           Reset
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java
        index e6dd5a6d3b..0eae247869 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java
        @@ -21,48 +21,44 @@ import com.datastax.driver.mapping.MappingManager;
         import com.datastax.driver.mapping.Result;
         import com.datastax.driver.mapping.annotations.Accessor;
         import com.datastax.driver.mapping.annotations.Query;
        +import java.util.Collection;
         import org.openecomp.core.dao.impl.CassandraBaseDao;
         import org.openecomp.core.nosqldb.factory.NoSqlDbFactory;
         import org.openecomp.sdc.activitylog.dao.ActivityLogDao;
         import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
         import org.openecomp.sdc.activitylog.dao.type.ActivityType;
         
        -import java.util.Collection;
        -
        -public class ActivityLogDaoCassandraImpl extends CassandraBaseDao
        -    implements ActivityLogDao {
        -
        -  private static final Mapper mapper;
        -  private static final ActivityLogAccessor accessor;
        +public class ActivityLogDaoCassandraImpl extends CassandraBaseDao implements ActivityLogDao {
         
        -  static {
        -    MappingManager mappingManager = NoSqlDbFactory.getInstance().createInterface().getMappingManager();
        -    mappingManager.getSession().getCluster().getConfiguration().getCodecRegistry()
        -                  .register(new EnumNameCodec<>(ActivityType.class));
        +    private static final Mapper mapper;
        +    private static final ActivityLogAccessor accessor;
         
        -    mapper = mappingManager.mapper(ActivityLogEntity.class);
        -    accessor = mappingManager.createAccessor(ActivityLogAccessor.class);
        -  }
        +    static {
        +        MappingManager mappingManager = NoSqlDbFactory.getInstance().createInterface().getMappingManager();
        +        mappingManager.getSession().getCluster().getConfiguration().getCodecRegistry().register(new EnumNameCodec<>(ActivityType.class));
        +        mapper = mappingManager.mapper(ActivityLogEntity.class);
        +        accessor = mappingManager.createAccessor(ActivityLogAccessor.class);
        +    }
         
        -  @Override
        -  protected Mapper getMapper() {
        -    return mapper;
        -  }
        +    @Override
        +    protected Mapper getMapper() {
        +        return mapper;
        +    }
         
        -  @Override
        -  protected Object[] getKeys(ActivityLogEntity entity) {
        -    return new Object[]{entity.getItemId(), entity.getVersionId(), entity.getId()};
        -  }
        +    @Override
        +    protected Object[] getKeys(ActivityLogEntity entity) {
        +        return new Object[]{entity.getItemId(), entity.getVersionId(), entity.getId()};
        +    }
         
        -  @Override
        -  public Collection list(ActivityLogEntity entity) {
        -    return accessor.listByItemVersion(entity.getItemId(), entity.getVersionId()).all();
        -  }
        +    @Override
        +    public Collection list(ActivityLogEntity entity) {
        +        return accessor.listByItemVersion(entity.getItemId(), entity.getVersionId()).all();
        +    }
         
        -  @Accessor
        -  interface ActivityLogAccessor {
        +    @Accessor
        +    interface ActivityLogAccessor {
         
        -    @Query("select * from activity_log where item_id=? and version_id=?")
        -    Result listByItemVersion(String itemId, String versionId);
        -  }
        +        @Query("select * from activity_log where item_id=? and version_id=?")
        +        Result listByItemVersion(String itemId, String versionId);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java
        index 02c8a71b0e..0da29828e2 100644
        --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java
        @@ -19,10 +19,11 @@ import org.openecomp.sdc.activitylog.dao.ActivityLogDao;
         import org.openecomp.sdc.activitylog.dao.ActivityLogDaoFactory;
         
         public class ActivityLogDaoFactoryImpl extends ActivityLogDaoFactory {
        -  private static final ActivityLogDao INSTANCE = new ActivityLogDaoCassandraImpl();
         
        -  @Override
        -  public ActivityLogDao createInterface() {
        -    return INSTANCE;
        -  }
        +    private static final ActivityLogDao INSTANCE = new ActivityLogDaoCassandraImpl();
        +
        +    @Override
        +    public ActivityLogDao createInterface() {
        +        return INSTANCE;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/configuration/ImplementationConfiguration.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/configuration/ImplementationConfiguration.java
        index 64ff886b24..c6b9a6ca81 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/configuration/ImplementationConfiguration.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/configuration/ImplementationConfiguration.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,14 +17,12 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.configuration;
         
        -import org.onap.config.api.Config;
        -
         import java.util.Map;
         import lombok.Getter;
         import lombok.Setter;
        +import org.onap.config.api.Config;
         
         /**
          * @author shiria
        @@ -34,14 +32,15 @@ import lombok.Setter;
         @Getter
         @Setter
         public class ImplementationConfiguration {
        -  @Config(key = "enable")
        -  Boolean enable = true;
        -  @Config(key = "implementationClass")
        -  String implementationClass;
        -  @Config(key = "properties")
        -  Map properties;
         
        -  public Boolean isEnable() {
        -    return enable;
        -  }
        +    @Config(key = "enable")
        +    Boolean enable = true;
        +    @Config(key = "implementationClass")
        +    String implementationClass;
        +    @Config(key = "properties")
        +    Map properties;
        +
        +    public Boolean isEnable() {
        +        return enable;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorLevel.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorLevel.java
        index 5477a35d8f..5c33e7b1cd 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorLevel.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorLevel.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.error;
         
        -
        -public enum ErrorLevel {
        -  ERROR, WARNING, INFO
        -}
        +public enum ErrorLevel {ERROR, WARNING, INFO}
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorMessage.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorMessage.java
        index a8aeb17a51..334639db0e 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorMessage.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/error/ErrorMessage.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.error;
         
         import java.util.ArrayList;
        @@ -32,38 +31,35 @@ import org.apache.commons.collections4.CollectionUtils;
         @EqualsAndHashCode
         @ToString
         public class ErrorMessage {
        -  private final ErrorLevel level;
        -  private final String message;
        -
        -  public ErrorMessage(ErrorLevel level, String message) {
        -    this.level = level;
        -    this.message = message;
        -  }
         
        -  public static class ErrorMessageUtil {
        +    private final ErrorLevel level;
        +    private final String message;
         
        -    private ErrorMessageUtil() {
        +    public ErrorMessage(ErrorLevel level, String message) {
        +        this.level = level;
        +        this.message = message;
             }
         
        -    /**
        -     * Add message list.
        -     *
        -     * @param fileName the file name
        -     * @param errorMap the error map
        -     * @return the list
        -     */
        -    public static List addMessage(String fileName,
        -                                                Map> errorMap) {
        -      List fileErrorList;
        -      fileErrorList = errorMap.get(fileName);
        -      if (CollectionUtils.isEmpty(fileErrorList)) {
        -        fileErrorList = new ArrayList<>();
        -        errorMap.put(fileName, fileErrorList);
        -      }
        -
        -      return fileErrorList;
        -    }
        -  }
        +    public static class ErrorMessageUtil {
         
        +        private ErrorMessageUtil() {
        +        }
         
        +        /**
        +         * Add message list.
        +         *
        +         * @param fileName the file name
        +         * @param errorMap the error map
        +         * @return the list
        +         */
        +        public static List addMessage(String fileName, Map> errorMap) {
        +            List fileErrorList;
        +            fileErrorList = errorMap.get(fileName);
        +            if (CollectionUtils.isEmpty(fileErrorList)) {
        +                fileErrorList = new ArrayList<>();
        +                errorMap.put(fileName, fileErrorList);
        +            }
        +            return fileErrorList;
        +        }
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/AsdcModel.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/AsdcModel.java
        index 7d873432b9..503e182f08 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/AsdcModel.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/AsdcModel.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,8 +17,8 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.model;
         
         public interface AsdcModel {
        +
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java
        index d1ddc5c48d..99ef5a0d9a 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java
        @@ -13,38 +13,39 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.datatypes.model;
         
         public enum ElementType {
        -  itemVersion,
        +    itemVersion,
         
        -  VendorLicenseModel,
        -  LicenseAgreements, LicenseAgreement,
        -  FeatureGroups, FeatureGroup,
        -  LicenseKeyGroups, LicenseKeyGroup,
        -  EntitlementPools, EntitlementPool,
        -  Limits, Limit,
        +    VendorLicenseModel,
        +    LicenseAgreements, LicenseAgreement,
        +    FeatureGroups, FeatureGroup,
        +    LicenseKeyGroups, LicenseKeyGroup,
        +    EntitlementPools, EntitlementPool,
        +    Limits, Limit,
         
        -  VendorSoftwareProduct,
        -  VSPQuestionnaire,
        +    VendorSoftwareProduct,
        +    VSPQuestionnaire,
         
        -  VspModel, NetworkPackage,
        -  OrchestrationTemplateCandidate, OrchestrationTemplateCandidateContent,
        -  OrchestrationTemplateCandidateValidationData, ORIGINAL_ONBOARDED_PACKAGE,
        -  OrchestrationTemplateStructure, OrchestrationTemplate,
        -  OrchestrationTemplateValidationData,
        -  // todo - remove OrchestrationTemplateContent
        -  OrchestrationTemplateContent,
        -  Networks, Network,
        -  Components, Component, ComponentQuestionnaire, ComponentDependencies, ComponentDependency,
        -  Nics, Nic, NicQuestionnaire,
        -  Mibs, SNMP_POLL, SNMP_TRAP, VES_EVENTS,
        -  Processes, Process,
        -  DeploymentFlavors, DeploymentFlavor,
        -  Computes, Compute, ComputeQuestionnaire,
        -  Images, Image, ImageQuestionnaire,
        -  ServiceModel, EnrichedServiceModel, ServiceTemplate, Templates, Artifact, Artifacts,
        +    VspModel, NetworkPackage,
        +    OrchestrationTemplateCandidate,
        +    OrchestrationTemplateCandidateContent,
        +    OrchestrationTemplateCandidateValidationData,
        +    ORIGINAL_ONBOARDED_PACKAGE,
        +    OrchestrationTemplateStructure, OrchestrationTemplate,
        +    OrchestrationTemplateValidationData,
        +    // todo - remove OrchestrationTemplateContent
        +    OrchestrationTemplateContent,
        +    Networks, Network,
        +    Components, Component, ComponentQuestionnaire, ComponentDependencies, ComponentDependency,
        +    Nics, Nic, NicQuestionnaire,
        +    Mibs, SNMP_POLL, SNMP_TRAP, VES_EVENTS,
        +    Processes, Process,
        +    DeploymentFlavors, DeploymentFlavor,
        +    Computes, Compute, ComputeQuestionnaire,
        +    Images, Image, ImageQuestionnaire,
        +    ServiceModel, EnrichedServiceModel, ServiceTemplate, Templates, Artifact, Artifacts,
         
        -  test
        +    test
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java
        index 98b64cabfb..ff4bfd95ab 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.model;
         
        -public enum ItemType {
        -  vlm,
        -  vsp
        -}
        +public enum ItemType {vlm, vsp}
        diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/heat/ForbiddenHeatResourceTypes.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/heat/ForbiddenHeatResourceTypes.java
        index f0310ba68a..99b55e9964 100644
        --- a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/heat/ForbiddenHeatResourceTypes.java
        +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/heat/ForbiddenHeatResourceTypes.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,41 +17,34 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.datatypes.model.heat;
         
         import java.util.HashMap;
         import java.util.Map;
         import java.util.Objects;
         
        -
         public enum ForbiddenHeatResourceTypes {
        -  HEAT_FLOATING_IP_TYPE("OS::Neutron::FloatingIP");
        -
        -
        -  private static Map stringToForbiddenHeatResourceTypeMap;
        -
        -  static {
        -    stringToForbiddenHeatResourceTypeMap = new HashMap<>();
        -
        -    for (ForbiddenHeatResourceTypes type : ForbiddenHeatResourceTypes.values()) {
        -      stringToForbiddenHeatResourceTypeMap.put(type.forbiddenType, type);
        +    HEAT_FLOATING_IP_TYPE("OS::Neutron::FloatingIP");
        +    private static Map stringToForbiddenHeatResourceTypeMap;
        +
        +    static {
        +        stringToForbiddenHeatResourceTypeMap = new HashMap<>();
        +        for (ForbiddenHeatResourceTypes type : ForbiddenHeatResourceTypes.values()) {
        +            stringToForbiddenHeatResourceTypeMap.put(type.forbiddenType, type);
        +        }
             }
        -  }
         
        -  private String forbiddenType;
        +    private String forbiddenType;
         
        +    ForbiddenHeatResourceTypes(String forbiddenType) {
        +        this.forbiddenType = forbiddenType;
        +    }
         
        -  ForbiddenHeatResourceTypes(String forbiddenType) {
        -    this.forbiddenType = forbiddenType;
        -  }
        -
        -  public static ForbiddenHeatResourceTypes findByForbiddenHeatResource(String heatResource) {
        -    return stringToForbiddenHeatResourceTypeMap.get(heatResource);
        -  }
        -
        +    public static ForbiddenHeatResourceTypes findByForbiddenHeatResource(String heatResource) {
        +        return stringToForbiddenHeatResourceTypeMap.get(heatResource);
        +    }
         
        -  public static boolean isResourceTypeValid(String resourceType) {
        -    return Objects.nonNull(findByForbiddenHeatResource(resourceType));
        -  }
        +    public static boolean isResourceTypeValid(String resourceType) {
        +        return Objects.nonNull(findByForbiddenHeatResource(resourceType));
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/api/EnrichmentManager.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/api/EnrichmentManager.java
        index 1185527c03..a2979824bc 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/api/EnrichmentManager.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/api/EnrichmentManager.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,30 +17,23 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.api;
         
        +import java.util.List;
        +import java.util.Map;
         import org.openecomp.core.enrichment.types.EntityInfo;
         import org.openecomp.sdc.datatypes.error.ErrorMessage;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.List;
        -import java.util.Map;
        -
        -
        -public interface
        -
        -EnrichmentManager {
        -
        -
        -  Map> enrich();
        +public interface EnrichmentManager {
         
        -  void addEntityInfo(String entityKey, EntityInfo entityInfo);
        +    Map> enrich();
         
        -  void init(String key, Version version);
        +    void addEntityInfo(String entityKey, EntityInfo entityInfo);
         
        -  T getModel();
        +    void init(String key, Version version);
         
        -  void setModel(T model);
        +    T getModel();
         
        +    void setModel(T model);
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/factory/EnrichmentManagerFactory.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/factory/EnrichmentManagerFactory.java
        index 9d72a88fa9..39ef9305c1 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/factory/EnrichmentManagerFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/factory/EnrichmentManagerFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,19 +17,15 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.factory;
         
         import org.openecomp.core.enrichment.api.EnrichmentManager;
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         
        -
        -
        -
         public abstract class EnrichmentManagerFactory extends AbstractComponentFactory {
         
        -  public static EnrichmentManagerFactory getInstance() {
        -    return AbstractFactory.getInstance(EnrichmentManagerFactory.class);
        -  }
        +    public static EnrichmentManagerFactory getInstance() {
        +        return AbstractFactory.getInstance(EnrichmentManagerFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ArtifactCategory.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ArtifactCategory.java
        index c037832e58..e1405d5435 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ArtifactCategory.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ArtifactCategory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.types;
         
         import java.util.Collections;
        @@ -26,42 +25,36 @@ import java.util.Map;
         import lombok.AllArgsConstructor;
         import lombok.Getter;
         
        -
         @AllArgsConstructor
         public enum ArtifactCategory {
        -
        -  INFORMATIONAL("Informational"),
        -  DEPLOYMENT("Deployment");
        -
        -  private static final Map mMap =
        -      Collections.unmodifiableMap(initializeMapping());
        -
        -  @Getter
        -  private String displayName;
        -
        -  /**
        -   * Initialize mapping map.
        -   *
        -   * @return the map
        -   */
        -  public static Map initializeMapping() {
        -    Map typeMap = new HashMap<>();
        -    for (ArtifactCategory v : ArtifactCategory.values()) {
        -      typeMap.put(v.displayName, v);
        +    INFORMATIONAL("Informational"), DEPLOYMENT("Deployment");
        +    private static final Map mMap = Collections.unmodifiableMap(initializeMapping());
        +    @Getter
        +    private String displayName;
        +
        +    /**
        +     * Initialize mapping map.
        +     *
        +     * @return the map
        +     */
        +    public static Map initializeMapping() {
        +        Map typeMap = new HashMap<>();
        +        for (ArtifactCategory v : ArtifactCategory.values()) {
        +            typeMap.put(v.displayName, v);
        +        }
        +        return typeMap;
             }
        -    return typeMap;
        -  }
         
        -  /**
        -   * Gets artifact type by display name.
        -   *
        -   * @param displayName the display name
        -   * @return the artifact type by display name
        -   */
        -  public static ArtifactCategory getArtifactTypeByDisplayName(String displayName) {
        -    if (mMap.containsKey(displayName)) {
        -      return mMap.get(displayName);
        +    /**
        +     * Gets artifact type by display name.
        +     *
        +     * @param displayName the display name
        +     * @return the artifact type by display name
        +     */
        +    public static ArtifactCategory getArtifactTypeByDisplayName(String displayName) {
        +        if (mMap.containsKey(displayName)) {
        +            return mMap.get(displayName);
        +        }
        +        return null;
             }
        -    return null;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetric.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetric.java
        index e795a94b46..b93a483dfc 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetric.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetric.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.enrichment.types;
         
         import lombok.Data;
        @@ -21,11 +20,9 @@ import lombok.Data;
         @Data
         public class CeilometerMetric {
         
        -  private String name;
        -  private String type;
        -  private String unit;
        -  private String category;
        -  private String description;
        -
        -
        +    private String name;
        +    private String type;
        +    private String unit;
        +    private String category;
        +    private String description;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetrics.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetrics.java
        index f85100b038..70ac71b4c4 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetrics.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/CeilometerMetrics.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.enrichment.types;
         
         import java.util.List;
        @@ -21,5 +20,6 @@ import lombok.Data;
         
         @Data
         public class CeilometerMetrics {
        +
             private List ceilometerMetricList;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentMonitoringUploadInfo.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentMonitoringUploadInfo.java
        index 63e161fae9..bd14e5a1e5 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentMonitoringUploadInfo.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentMonitoringUploadInfo.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,33 +17,32 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.types;
         
        +import static org.openecomp.core.enrichment.types.MonitoringUploadType.SNMP_POLL;
        +import static org.openecomp.core.enrichment.types.MonitoringUploadType.SNMP_TRAP;
        +import static org.openecomp.core.enrichment.types.MonitoringUploadType.VES_EVENTS;
        +
         import java.util.HashMap;
         import java.util.Map;
         
        -import static org.openecomp.core.enrichment.types.MonitoringUploadType.*;
        -
         public class ComponentMonitoringUploadInfo {
         
        +    private Map infoByType = new HashMap<>();
         
        -  private Map infoByType = new HashMap<>();
        -
        -  public MonitoringArtifactInfo getSnmpTrap() {
        -    return infoByType.get(SNMP_TRAP);
        -  }
        +    public MonitoringArtifactInfo getSnmpTrap() {
        +        return infoByType.get(SNMP_TRAP);
        +    }
         
        -  public MonitoringArtifactInfo getSnmpPoll() {
        -    return infoByType.get(SNMP_POLL);
        -  }
        +    public MonitoringArtifactInfo getSnmpPoll() {
        +        return infoByType.get(SNMP_POLL);
        +    }
         
        -  public MonitoringArtifactInfo getVesEvent() {
        -    return infoByType.get(VES_EVENTS);
        -  }
        +    public MonitoringArtifactInfo getVesEvent() {
        +        return infoByType.get(VES_EVENTS);
        +    }
         
        -  public void setMonitoringArtifactFile(MonitoringUploadType type,
        -                                        MonitoringArtifactInfo monitoringArtifactInfo) {
        -    infoByType.put(type, monitoringArtifactInfo);
        -  }
        +    public void setMonitoringArtifactFile(MonitoringUploadType type, MonitoringArtifactInfo monitoringArtifactInfo) {
        +        infoByType.put(type, monitoringArtifactInfo);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentProcessInfo.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentProcessInfo.java
        index 3abbd13475..4e6599d18f 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentProcessInfo.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/ComponentProcessInfo.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.enrichment.types;
         
         import java.io.ByteArrayInputStream;
        @@ -21,20 +20,15 @@ import java.io.InputStream;
         import lombok.Getter;
         import lombok.Setter;
         
        -
         public class ComponentProcessInfo {
         
             @Setter
             @Getter
             private String name;
        -
             @Setter
             private byte[] content;
         
        -
             public InputStream getContent() {
                 return new ByteArrayInputStream(this.content);
             }
        -
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/EntityInfo.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/EntityInfo.java
        index ac80eb9d03..b9da11c221 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/EntityInfo.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/EntityInfo.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,11 +17,8 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.types;
         
        -
         public interface EntityInfo {
         
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/InformationArtifactFolderNames.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/InformationArtifactFolderNames.java
        index 68f0db3524..c54d4af181 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/InformationArtifactFolderNames.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/InformationArtifactFolderNames.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,12 +17,9 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.types;
         
         /**
          * Created by Talio on 12/5/2016.
          */
        -public enum InformationArtifactFolderNames {
        -  Guide;
        -}
        +public enum InformationArtifactFolderNames {Guide;}
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringArtifactInfo.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringArtifactInfo.java
        index cbb883162c..c2e72f0ab6 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringArtifactInfo.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringArtifactInfo.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.enrichment.types;
         
         import java.io.ByteArrayInputStream;
        @@ -21,7 +20,6 @@ import java.io.InputStream;
         import lombok.Getter;
         import lombok.Setter;
         
        -
         public class MonitoringArtifactInfo {
         
             @Setter
        @@ -33,5 +31,4 @@ public class MonitoringArtifactInfo {
             public InputStream getContent() {
                 return new ByteArrayInputStream(this.content);
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringUploadType.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringUploadType.java
        index 077480f95f..1a13d3cb48 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringUploadType.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-api/src/main/java/org/openecomp/core/enrichment/types/MonitoringUploadType.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,13 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.core.enrichment.types;
         
        -public enum MonitoringUploadType {
        -  SNMP_POLL,
        -  SNMP_TRAP,
        -  VES_EVENTS
        -}
        -
        -
        +public enum MonitoringUploadType {SNMP_POLL, SNMP_TRAP, VES_EVENTS}
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerFactoryImpl.java
        index abbb577075..cd991241ee 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,18 +17,15 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl;
         
        -
         import org.openecomp.core.enrichment.api.EnrichmentManager;
         import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory;
         
        -
         public class EnrichmentManagerFactoryImpl extends EnrichmentManagerFactory {
         
        -  @Override
        -  public EnrichmentManager createInterface() {
        -    return new EnrichmentManagerImpl();
        -  }
        +    @Override
        +    public EnrichmentManager createInterface() {
        +        return new EnrichmentManagerImpl();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java
        index 40bd3964cb..9854bc0a74 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,12 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl;
         
        +import java.util.Arrays;
        +import java.util.HashMap;
        +import java.util.List;
        +import java.util.Map;
         import org.openecomp.core.enrichment.api.EnrichmentManager;
         import org.openecomp.core.enrichment.types.EntityInfo;
         import org.openecomp.sdc.datatypes.error.ErrorLevel;
        @@ -32,60 +35,48 @@ import org.openecomp.sdc.logging.api.LoggerFactory;
         import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.Arrays;
        -import java.util.HashMap;
        -import java.util.List;
        -import java.util.Map;
        -
         public class EnrichmentManagerImpl implements EnrichmentManager {
         
        -  private static Logger logger = (Logger) LoggerFactory.getLogger(EnrichmentManagerImpl.class);
        +    private static Logger logger = (Logger) LoggerFactory.getLogger(EnrichmentManagerImpl.class);
        +    private EnrichmentInfo data = null;
        +    private ToscaServiceModel model;
         
        -  private EnrichmentInfo data = null;
        -  private ToscaServiceModel model;
        -
        -
        -  @Override
        -  public Map> enrich() {
        -    Map> enrichErrors = new HashMap<>();
        -    List enricherList =
        -        EnricherHandlerFactory.getInstance().createInterface().getEnrichers();
        -      for (Enricher enricher : enricherList) {
        -        enricher.setData(data);
        -        enricher.setModel(model);
        -        try {
        -          enrichErrors.putAll(enricher.enrich());
        -        } catch (Exception exception) {
        -          enrichErrors.put("Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, exception
        -                  .getMessage())));
        -          logger.error("Exception occurred during enrichment", exception);
        +    @Override
        +    public Map> enrich() {
        +        Map> enrichErrors = new HashMap<>();
        +        List enricherList = EnricherHandlerFactory.getInstance().createInterface().getEnrichers();
        +        for (Enricher enricher : enricherList) {
        +            enricher.setData(data);
        +            enricher.setModel(model);
        +            try {
        +                enrichErrors.putAll(enricher.enrich());
        +            } catch (Exception exception) {
        +                enrichErrors.put("Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, exception.getMessage())));
        +                logger.error("Exception occurred during enrichment", exception);
        +            }
                 }
        +        return enrichErrors;
             }
        -    return enrichErrors;
        -  }
        -
        -  @Override
        -  public void addEntityInfo(String entityKey, EntityInfo entityInfo) {
        -    this.data.addEntityInfo(entityKey, entityInfo);
        -  }
        -
        -
        -  @Override
        -  public void init(String key, Version version) {
        -    data = new EnrichmentInfo();
        -    data.setKey(key);
        -    data.setVersion(version);
        -  }
         
        -  @Override
        -  public ToscaServiceModel getModel() {
        -    return this.model;
        -  }
        +    @Override
        +    public void addEntityInfo(String entityKey, EntityInfo entityInfo) {
        +        this.data.addEntityInfo(entityKey, entityInfo);
        +    }
         
        -  @Override
        -  public void setModel(ToscaServiceModel model) {
        -    this.model = model;
        -  }
        +    @Override
        +    public void init(String key, Version version) {
        +        data = new EnrichmentInfo();
        +        data.setKey(key);
        +        data.setVersion(version);
        +    }
         
        +    @Override
        +    public ToscaServiceModel getModel() {
        +        return this.model;
        +    }
         
        +    @Override
        +    public void setModel(ToscaServiceModel model) {
        +        this.model = model;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/EnrichmentInfo.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/EnrichmentInfo.java
        index 8f3798f764..15d0e12d39 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/EnrichmentInfo.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/EnrichmentInfo.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,17 +17,16 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment;
         
        -import org.openecomp.core.enrichment.types.EntityInfo;
        -import org.openecomp.sdc.versioning.dao.types.Version;
        -
         import java.util.HashMap;
         import java.util.List;
         import java.util.Map;
        +import org.openecomp.core.enrichment.types.EntityInfo;
        +import org.openecomp.sdc.versioning.dao.types.Version;
         
         public class EnrichmentInfo {
        +
             Map> additionalInfo = new HashMap<>();
             Map entitiesInfo = new HashMap<>();
             String key;
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/factory/EnricherHandlerFactory.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/factory/EnricherHandlerFactory.java
        index 1167a6df9a..2c05055a90 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/factory/EnricherHandlerFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/factory/EnricherHandlerFactory.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,15 +17,12 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.factory;
         
        -
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
         import org.openecomp.sdc.enrichment.inter.EnricherHandler;
         
        -
         public abstract class EnricherHandlerFactory extends AbstractComponentFactory {
         
             public static EnricherHandlerFactory getInstance() {
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerFactoryImpl.java
        index 9898ef678a..197256ecb5 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerFactoryImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerFactoryImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,8 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl;
         
        -
         import org.openecomp.sdc.enrichment.factory.EnricherHandlerFactory;
         import org.openecomp.sdc.enrichment.inter.EnricherHandler;
         
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java
        index c9d89ee38f..08e61ed3cf 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,10 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl;
         
        +import java.util.ArrayList;
        +import java.util.List;
         import org.openecomp.sdc.enrichment.impl.external.artifact.ExternalArtifactEnricher;
         import org.openecomp.sdc.enrichment.impl.tosca.ToscaEnricher;
         import org.openecomp.sdc.enrichment.inter.Enricher;
        @@ -27,9 +28,6 @@ import org.openecomp.sdc.enrichment.inter.EnricherHandler;
         import org.openecomp.sdc.logging.api.Logger;
         import org.openecomp.sdc.logging.api.LoggerFactory;
         
        -import java.util.ArrayList;
        -import java.util.List;
        -
         public class EnricherHandlerImpl implements EnricherHandler {
         
             private static Logger logger = (Logger) LoggerFactory.getLogger(EnricherHandlerImpl.class);
        @@ -41,5 +39,4 @@ public class EnricherHandlerImpl implements EnricherHandler {
                 enricherList.add(new ExternalArtifactEnricher());
                 return enricherList;
             }
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java
        index 49ba6148c0..faa377c4d3 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ExternalArtifactEnricher.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,13 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl.external.artifact;
         
        +import java.lang.reflect.Constructor;
        +import java.util.Collection;
        +import java.util.HashMap;
        +import java.util.List;
        +import java.util.Map;
         import org.openecomp.core.utilities.file.FileUtils;
         import org.openecomp.core.utilities.json.JsonUtil;
         import org.openecomp.sdc.datatypes.error.ErrorMessage;
        @@ -27,41 +31,30 @@ import org.openecomp.sdc.enrichment.inter.Enricher;
         import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface;
         import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
         
        -import java.lang.reflect.Constructor;
        -import java.util.Collection;
        -import java.util.HashMap;
        -import java.util.List;
        -import java.util.Map;
        -
         public class ExternalArtifactEnricher extends Enricher {
        -  private static final String EXTERNAL_ARTIFACT_ENRICH_CONF_FILE = "ExternalArtifactConfiguration"
        -      + ".json";
        -  private static Collection implementingClasses =
        -      getExternalArtifactEnrichedImplClassesList();
        -
        -  private static Collection getExternalArtifactEnrichedImplClassesList() {
        -    @SuppressWarnings("unchecked")
        -    Map confFileAsMap = FileUtils.readViaInputStream(EXTERNAL_ARTIFACT_ENRICH_CONF_FILE,
        -        stream -> JsonUtil.json2Object(stream, Map.class));
        -
        -    return confFileAsMap.values();
        -  }
        -
        -  @Override
        -  public Map> enrich() throws Exception{
        -    Map> errors = new HashMap<>();
        -
        -            for (String implementingClassName : implementingClasses) {
        -                ExternalArtifactEnricherInterface externalArtifactEnricherInstance = getExternalArtifactEnricherInstance(implementingClassName);
        -                errors.putAll(externalArtifactEnricherInstance.enrich(this.data, (ToscaServiceModel) this.model));
        -            }
        -    return errors;
        -  }
         
        -  private ExternalArtifactEnricherInterface getExternalArtifactEnricherInstance(
        -      String implementingClassName) throws Exception {
        -    Class clazz = Class.forName(implementingClassName);
        -    Constructor constructor = clazz.getConstructor();
        -    return (ExternalArtifactEnricherInterface) constructor.newInstance();
        -  }
        +    private static final String EXTERNAL_ARTIFACT_ENRICH_CONF_FILE = "ExternalArtifactConfiguration" + ".json";
        +    private static Collection implementingClasses = getExternalArtifactEnrichedImplClassesList();
        +
        +    private static Collection getExternalArtifactEnrichedImplClassesList() {
        +        @SuppressWarnings("unchecked") Map confFileAsMap = FileUtils
        +            .readViaInputStream(EXTERNAL_ARTIFACT_ENRICH_CONF_FILE, stream -> JsonUtil.json2Object(stream, Map.class));
        +        return confFileAsMap.values();
        +    }
        +
        +    @Override
        +    public Map> enrich() throws Exception {
        +        Map> errors = new HashMap<>();
        +        for (String implementingClassName : implementingClasses) {
        +            ExternalArtifactEnricherInterface externalArtifactEnricherInstance = getExternalArtifactEnricherInstance(implementingClassName);
        +            errors.putAll(externalArtifactEnricherInstance.enrich(this.data, (ToscaServiceModel) this.model));
        +        }
        +        return errors;
        +    }
        +
        +    private ExternalArtifactEnricherInterface getExternalArtifactEnricherInstance(String implementingClassName) throws Exception {
        +        Class clazz = Class.forName(implementingClassName);
        +        Constructor constructor = clazz.getConstructor();
        +        return (ExternalArtifactEnricherInterface) constructor.newInstance();
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricher.java
        index 34954bdbbb..06a5b3a2c2 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricher.java
        @@ -12,8 +12,7 @@
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
        -*/
        -
        + */
         package org.openecomp.sdc.enrichment.impl.external.artifact;
         
         import static org.openecomp.sdc.tosca.services.ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME;
        @@ -61,251 +60,187 @@ import org.openecomp.sdc.versioning.dao.types.Version;
         
         public class MonitoringMibEnricher implements ExternalArtifactEnricherInterface {
         
        -  private EnrichedServiceModelDao enrichedServiceModelDao;
        -  private ComponentDao componentDao;
        -  private ComponentArtifactDao componentArtifactDao;
        -  private static final String COMPONENT_PREFIX = "org.openecomp.resource.vfc.";
        -
        -  private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
        -
        -  /**
        -   * Enrich map.
        -   *
        -   * @param enrichmentInfo the enrichmentInfo
        -   * @return the map
        -   */
        -  @Override
        -  public Map> enrich(EnrichmentInfo enrichmentInfo,
        -                                                ToscaServiceModel serviceModel) {
        -
        -    Map> errors = new HashMap<>();
        -    String vspId = enrichmentInfo.getKey();
        -    Version version = enrichmentInfo.getVersion();
        -
        -    Collection components =
        -        getComponentDao().list(new ComponentEntity(vspId, version, null));
        -    components
        -        .forEach(componentEntry -> errors.putAll(enrichComponent(vspId, version, componentEntry,
        -            serviceModel)));
        -
        -    return errors;
        -  }
        -
        -  private Map> enrichComponent(String vspId,
        -                                                  Version version,
        -                                                  ComponentEntity component,
        -                                                  ToscaServiceModel serviceModel) {
        -    Set abstractNodeTypes =
        -        extractAbstractTypesFromSameTypeFromServiceModel(component, serviceModel);
        -    return enrichComponent(vspId, version, component, abstractNodeTypes);
        -  }
        -
        -  private Set extractAbstractTypesFromSameTypeFromServiceModel(ComponentEntity component,
        -                                                                       ToscaServiceModel serviceModel) {
        -    Set abstractNodeTypes = new HashSet<>();
        -    Map serviceTemplates = serviceModel.getServiceTemplates();
        -    String typeToCheck =
        -        getComponentVfcTypeToCheck(component.getComponentCompositionData().getName());
        -
        -    for (ServiceTemplate serviceTemplate : serviceTemplates.values()) {
        -      collectAllAbstractNodeTypesPointingToType(
        -          typeToCheck, serviceTemplate, serviceTemplates, abstractNodeTypes);
        +    private static final String COMPONENT_PREFIX = "org.openecomp.resource.vfc.";
        +    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());
        +    private EnrichedServiceModelDao enrichedServiceModelDao;
        +    private ComponentDao componentDao;
        +    private ComponentArtifactDao componentArtifactDao;
        +
        +    /**
        +     * Enrich map.
        +     *
        +     * @param enrichmentInfo the enrichmentInfo
        +     * @return the map
        +     */
        +    @Override
        +    public Map> enrich(EnrichmentInfo enrichmentInfo, ToscaServiceModel serviceModel) {
        +        Map> errors = new HashMap<>();
        +        String vspId = enrichmentInfo.getKey();
        +        Version version = enrichmentInfo.getVersion();
        +        Collection components = getComponentDao().list(new ComponentEntity(vspId, version, null));
        +        components.forEach(componentEntry -> errors.putAll(enrichComponent(vspId, version, componentEntry, serviceModel)));
        +        return errors;
             }
         
        -    return abstractNodeTypes;
        -  }
        -
        -  private String getComponentVfcTypeToCheck(String type) {
        -    return Objects.isNull(type) ? ""
        -        : type.replace(COMPONENT_PREFIX, COMPONENT_PREFIX + "compute.");
        -  }
        -
        -  private void collectAllAbstractNodeTypesPointingToType(String typeToCheck,
        -                                                         ServiceTemplate serviceTemplate,
        -                                                         Map serviceTemplates,
        -                                                         Set abstractNodeTypes) {
        -    Map nodeTemplates =
        -        DataModelUtil.getNodeTemplates(serviceTemplate);
        -
        -    for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) {
        -      handleNodeTemplate(nodeTemplateEntry.getValue(), typeToCheck,
        -          serviceTemplates, abstractNodeTypes);
        +    private Map> enrichComponent(String vspId, Version version, ComponentEntity component,
        +                                                            ToscaServiceModel serviceModel) {
        +        Set abstractNodeTypes = extractAbstractTypesFromSameTypeFromServiceModel(component, serviceModel);
        +        return enrichComponent(vspId, version, component, abstractNodeTypes);
             }
        -  }
         
        -  private void handleNodeTemplate(NodeTemplate nodeTemplate,
        -                                  String typeToCheck,
        -                                  Map serviceTemplates,
        -                                  Set abstractNodeTypes) {
        -    List directives = DataModelUtil.getDirectives(nodeTemplate);
        -    if (directives.contains(Directive.SUBSTITUTABLE.getDisplayName())) {
        -      handleSubstitutionServiceTemplate(typeToCheck, nodeTemplate, serviceTemplates,
        -          abstractNodeTypes);
        +    private Set extractAbstractTypesFromSameTypeFromServiceModel(ComponentEntity component, ToscaServiceModel serviceModel) {
        +        Set abstractNodeTypes = new HashSet<>();
        +        Map serviceTemplates = serviceModel.getServiceTemplates();
        +        String typeToCheck = getComponentVfcTypeToCheck(component.getComponentCompositionData().getName());
        +        for (ServiceTemplate serviceTemplate : serviceTemplates.values()) {
        +            collectAllAbstractNodeTypesPointingToType(typeToCheck, serviceTemplate, serviceTemplates, abstractNodeTypes);
        +        }
        +        return abstractNodeTypes;
             }
        -  }
         
        -  private void handleSubstitutionServiceTemplate(String typeToCheck,
        -                                                 NodeTemplate nodeTemplate,
        -                                                 Map serviceTemplates,
        -                                                 Set abstractNodeTypes) {
        -    Object serviceTemplateFilter =
        -        DataModelUtil.getPropertyValue(nodeTemplate, SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
        -    if (Objects.nonNull(serviceTemplateFilter) && serviceTemplateFilter instanceof Map) {
        -      String substituteServiceTemplateName =
        -          (String) ((Map) serviceTemplateFilter)
        -              .get(SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
        -      ServiceTemplate substituteServiceTemplate =
        -          serviceTemplates.get(substituteServiceTemplateName);
        -      if (doesNodeTypeExistInSubServiceTemplate(typeToCheck, substituteServiceTemplate)) {
        -        abstractNodeTypes.add(nodeTemplate.getType());
        -      }
        +    private String getComponentVfcTypeToCheck(String type) {
        +        return Objects.isNull(type) ? "" : type.replace(COMPONENT_PREFIX, COMPONENT_PREFIX + "compute.");
             }
        -  }
        -
        -  private boolean doesNodeTypeExistInSubServiceTemplate(String nodeTypeId,
        -                                                        ServiceTemplate substituteServiceTemplate) {
        -    return Objects
        -        .nonNull(DataModelUtil.getNodeType(substituteServiceTemplate, nodeTypeId));
        -  }
        -
        -  Map> enrichComponent(String vspId,
        -                                                  Version version,
        -                                                  ComponentEntity componentEntry,
        -                                                  Set abstractNodeTypes) {
        -    Map> errors = new HashMap<>();
         
        -    List componentMonitoringUploadInfoList =
        -        extractComponentMibInfo(vspId, version, componentEntry, abstractNodeTypes);
        -
        -    componentMonitoringUploadInfoList.forEach(
        -        componentUploadInfo -> enrichComponentMib(vspId, version, componentUploadInfo, errors));
        -    return errors;
        -  }
        -
        -  private List extractComponentMibInfo(String vspId, Version version,
        -                                                                      ComponentEntity componentEntity,
        -                                                                      Set abstractNodeTypes) {
        -    String componentId = componentEntity.getId();
        -    ComponentMonitoringUploadEntity entity = new ComponentMonitoringUploadEntity();
        -
        -    entity.setVspId(vspId);
        -    entity.setVersion(version);
        -    entity.setComponentId(componentId);
        -    List componentMonitoringUploadInfoList = new ArrayList<>();
        -
        -    abstractNodeTypes.forEach(unifiedComponentNodeType -> componentMonitoringUploadInfoList
        -        .add(updComponentMibInfoByType(unifiedComponentNodeType, entity)));
        -    return componentMonitoringUploadInfoList;
        -  }
        +    private void collectAllAbstractNodeTypesPointingToType(String typeToCheck, ServiceTemplate serviceTemplate,
        +                                                           Map serviceTemplates, Set abstractNodeTypes) {
        +        Map nodeTemplates = DataModelUtil.getNodeTemplates(serviceTemplate);
        +        for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) {
        +            handleNodeTemplate(nodeTemplateEntry.getValue(), typeToCheck, serviceTemplates, abstractNodeTypes);
        +        }
        +    }
         
        -  private ComponentMonitoringUploadInfo updComponentMibInfoByType(String componentName,
        -                                                                  ComponentMonitoringUploadEntity componentMonitoringUploadEntity) {
        -    ComponentMonitoringUploadInfo componentMonitoringUploadInfo =
        -        new ComponentMonitoringUploadInfo();
        +    private void handleNodeTemplate(NodeTemplate nodeTemplate, String typeToCheck, Map serviceTemplates,
        +                                    Set abstractNodeTypes) {
        +        List directives = DataModelUtil.getDirectives(nodeTemplate);
        +        if (directives.contains(Directive.SUBSTITUTABLE.getDisplayName())) {
        +            handleSubstitutionServiceTemplate(typeToCheck, nodeTemplate, serviceTemplates, abstractNodeTypes);
        +        }
        +    }
         
        -    for (MonitoringUploadType type : MonitoringUploadType.values()) {
        -      componentMonitoringUploadEntity.setType(type);
        -      Optional artifact =
        -          getComponentArtifactDao().getByType(componentMonitoringUploadEntity);
        +    private void handleSubstitutionServiceTemplate(String typeToCheck, NodeTemplate nodeTemplate, Map serviceTemplates,
        +                                                   Set abstractNodeTypes) {
        +        Object serviceTemplateFilter = DataModelUtil.getPropertyValue(nodeTemplate, SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
        +        if (Objects.nonNull(serviceTemplateFilter) && serviceTemplateFilter instanceof Map) {
        +            String substituteServiceTemplateName = (String) ((Map) serviceTemplateFilter)
        +                .get(SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
        +            ServiceTemplate substituteServiceTemplate = serviceTemplates.get(substituteServiceTemplateName);
        +            if (doesNodeTypeExistInSubServiceTemplate(typeToCheck, substituteServiceTemplate)) {
        +                abstractNodeTypes.add(nodeTemplate.getType());
        +            }
        +        }
        +    }
         
        -      if (!artifact.isPresent()) {
        -        continue;
        -      }
        -      ComponentMonitoringUploadEntity mibArtifact = artifact.get();
        -      updateComponentMonitoringUploadInfoWithMib(getArtifactPath(type, componentName), type,
        -          mibArtifact,
        -          componentMonitoringUploadInfo);
        +    private boolean doesNodeTypeExistInSubServiceTemplate(String nodeTypeId, ServiceTemplate substituteServiceTemplate) {
        +        return Objects.nonNull(DataModelUtil.getNodeType(substituteServiceTemplate, nodeTypeId));
             }
        -    return componentMonitoringUploadInfo;
        -  }
         
        -  private String getArtifactPath(MonitoringUploadType type, String unifiedComponentNodeType) {
        -    return unifiedComponentNodeType + File.separator + ArtifactCategory.DEPLOYMENT.getDisplayName()
        -        + File.separator + type.name();
        -  }
        +    Map> enrichComponent(String vspId, Version version, ComponentEntity componentEntry, Set abstractNodeTypes) {
        +        Map> errors = new HashMap<>();
        +        List componentMonitoringUploadInfoList = extractComponentMibInfo(vspId, version, componentEntry,
        +            abstractNodeTypes);
        +        componentMonitoringUploadInfoList.forEach(componentUploadInfo -> enrichComponentMib(vspId, version, componentUploadInfo, errors));
        +        return errors;
        +    }
         
        -  private void updateComponentMonitoringUploadInfoWithMib(String path,
        -                                                          MonitoringUploadType type,
        -                                                          ComponentMonitoringUploadEntity mibArtifact,
        -                                                          ComponentMonitoringUploadInfo componentMonitoringUploadInfo) {
        -    MonitoringArtifactInfo monitoringArtifactInfo = new MonitoringArtifactInfo();
        -    monitoringArtifactInfo.setName(path);
        -    monitoringArtifactInfo.setContent(mibArtifact.getArtifact().array());
        -    componentMonitoringUploadInfo.setMonitoringArtifactFile(type, monitoringArtifactInfo);
        -  }
        +    private List extractComponentMibInfo(String vspId, Version version, ComponentEntity componentEntity,
        +                                                                        Set abstractNodeTypes) {
        +        String componentId = componentEntity.getId();
        +        ComponentMonitoringUploadEntity entity = new ComponentMonitoringUploadEntity();
        +        entity.setVspId(vspId);
        +        entity.setVersion(version);
        +        entity.setComponentId(componentId);
        +        List componentMonitoringUploadInfoList = new ArrayList<>();
        +        abstractNodeTypes
        +            .forEach(unifiedComponentNodeType -> componentMonitoringUploadInfoList.add(updComponentMibInfoByType(unifiedComponentNodeType, entity)));
        +        return componentMonitoringUploadInfoList;
        +    }
         
        -  private void enrichComponentMib(String vspId,
        -                                  Version version,
        -                                  ComponentMonitoringUploadInfo componentUploadInfo,
        -                                  Map> errors) {
        -    ServiceArtifact mibServiceArtifact = new ServiceArtifact();
        -    mibServiceArtifact.setVspId(vspId);
        -    mibServiceArtifact.setVersion(version);
        -    enrichMibFiles(mibServiceArtifact, componentUploadInfo, errors);
        -  }
        +    private ComponentMonitoringUploadInfo updComponentMibInfoByType(String componentName,
        +                                                                    ComponentMonitoringUploadEntity componentMonitoringUploadEntity) {
        +        ComponentMonitoringUploadInfo componentMonitoringUploadInfo = new ComponentMonitoringUploadInfo();
        +        for (MonitoringUploadType type : MonitoringUploadType.values()) {
        +            componentMonitoringUploadEntity.setType(type);
        +            Optional artifact = getComponentArtifactDao().getByType(componentMonitoringUploadEntity);
        +            if (!artifact.isPresent()) {
        +                continue;
        +            }
        +            ComponentMonitoringUploadEntity mibArtifact = artifact.get();
        +            updateComponentMonitoringUploadInfoWithMib(getArtifactPath(type, componentName), type, mibArtifact, componentMonitoringUploadInfo);
        +        }
        +        return componentMonitoringUploadInfo;
        +    }
         
        -  private void enrichMibFiles(ServiceArtifact monitoringArtifact,
        -                              ComponentMonitoringUploadInfo componentMonitoringUploadInfo,
        -                              Map> errors) {
        -    if (componentMonitoringUploadInfo == null) {
        -      return;
        +    private String getArtifactPath(MonitoringUploadType type, String unifiedComponentNodeType) {
        +        return unifiedComponentNodeType + File.separator + ArtifactCategory.DEPLOYMENT.getDisplayName() + File.separator + type.name();
             }
        -    enrichMibByType(componentMonitoringUploadInfo.getSnmpTrap(), MonitoringUploadType.SNMP_TRAP,
        -        monitoringArtifact,
        -        errors);
        -    enrichMibByType(componentMonitoringUploadInfo.getSnmpPoll(), MonitoringUploadType.SNMP_POLL,
        -        monitoringArtifact,
        -        errors);
        -    enrichMibByType(componentMonitoringUploadInfo.getVesEvent(), MonitoringUploadType.VES_EVENTS,
        -        monitoringArtifact,
        -        errors);
        -  }
         
        -  private void enrichMibByType(MonitoringArtifactInfo monitoringArtifactInfo,
        -                               MonitoringUploadType type,
        -                               ServiceArtifact mibServiceArtifact,
        -                               Map> errors) {
        -    if (monitoringArtifactInfo == null) {
        -      return;
        +    private void updateComponentMonitoringUploadInfoWithMib(String path, MonitoringUploadType type, ComponentMonitoringUploadEntity mibArtifact,
        +                                                            ComponentMonitoringUploadInfo componentMonitoringUploadInfo) {
        +        MonitoringArtifactInfo monitoringArtifactInfo = new MonitoringArtifactInfo();
        +        monitoringArtifactInfo.setName(path);
        +        monitoringArtifactInfo.setContent(mibArtifact.getArtifact().array());
        +        componentMonitoringUploadInfo.setMonitoringArtifactFile(type, monitoringArtifactInfo);
             }
        -    FileContentHandler mibs;
        -    try {
        -      mibs = FileUtils
        -          .getFileContentMapFromZip(FileUtils.toByteArray(monitoringArtifactInfo.getContent()));
        -    } catch (ZipException ex) {
        -      log.error("Failed to get file content map from zip ", ex);
        -      ErrorMessage.ErrorMessageUtil
        -          .addMessage(mibServiceArtifact.getName() + "." + type.name(), errors)
        -          .add(new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage()));
        -      return;
        +
        +    private void enrichComponentMib(String vspId, Version version, ComponentMonitoringUploadInfo componentUploadInfo,
        +                                    Map> errors) {
        +        ServiceArtifact mibServiceArtifact = new ServiceArtifact();
        +        mibServiceArtifact.setVspId(vspId);
        +        mibServiceArtifact.setVersion(version);
        +        enrichMibFiles(mibServiceArtifact, componentUploadInfo, errors);
             }
        -    Set fileList = mibs.getFileList();
        -    for (String fileName : fileList) {
        -      mibServiceArtifact.setContentData(mibs.getFileContent(fileName));
        -      mibServiceArtifact.setName(monitoringArtifactInfo.getName() + File.separator + fileName);
        -      getEnrichedServiceModelDao().storeExternalArtifact(mibServiceArtifact);
        +
        +    private void enrichMibFiles(ServiceArtifact monitoringArtifact, ComponentMonitoringUploadInfo componentMonitoringUploadInfo,
        +                                Map> errors) {
        +        if (componentMonitoringUploadInfo == null) {
        +            return;
        +        }
        +        enrichMibByType(componentMonitoringUploadInfo.getSnmpTrap(), MonitoringUploadType.SNMP_TRAP, monitoringArtifact, errors);
        +        enrichMibByType(componentMonitoringUploadInfo.getSnmpPoll(), MonitoringUploadType.SNMP_POLL, monitoringArtifact, errors);
        +        enrichMibByType(componentMonitoringUploadInfo.getVesEvent(), MonitoringUploadType.VES_EVENTS, monitoringArtifact, errors);
             }
        -  }
         
        -  private EnrichedServiceModelDao getEnrichedServiceModelDao() {
        -    if (enrichedServiceModelDao == null) {
        -      enrichedServiceModelDao = EnrichedServiceModelDaoFactory.getInstance().createInterface();
        +    private void enrichMibByType(MonitoringArtifactInfo monitoringArtifactInfo, MonitoringUploadType type, ServiceArtifact mibServiceArtifact,
        +                                 Map> errors) {
        +        if (monitoringArtifactInfo == null) {
        +            return;
        +        }
        +        FileContentHandler mibs;
        +        try {
        +            mibs = FileUtils.getFileContentMapFromZip(FileUtils.toByteArray(monitoringArtifactInfo.getContent()));
        +        } catch (ZipException ex) {
        +            log.error("Failed to get file content map from zip ", ex);
        +            ErrorMessage.ErrorMessageUtil.addMessage(mibServiceArtifact.getName() + "." + type.name(), errors)
        +                .add(new ErrorMessage(ErrorLevel.ERROR, Messages.INVALID_ZIP_FILE.getErrorMessage()));
        +            return;
        +        }
        +        Set fileList = mibs.getFileList();
        +        for (String fileName : fileList) {
        +            mibServiceArtifact.setContentData(mibs.getFileContent(fileName));
        +            mibServiceArtifact.setName(monitoringArtifactInfo.getName() + File.separator + fileName);
        +            getEnrichedServiceModelDao().storeExternalArtifact(mibServiceArtifact);
        +        }
             }
        -    return enrichedServiceModelDao;
        -  }
         
        -  private ComponentDao getComponentDao() {
        -    if (componentDao == null) {
        -      componentDao = ComponentDaoFactory.getInstance().createInterface();
        +    private EnrichedServiceModelDao getEnrichedServiceModelDao() {
        +        if (enrichedServiceModelDao == null) {
        +            enrichedServiceModelDao = EnrichedServiceModelDaoFactory.getInstance().createInterface();
        +        }
        +        return enrichedServiceModelDao;
             }
        -    return componentDao;
        -  }
         
        -  private ComponentArtifactDao getComponentArtifactDao() {
        -    if (componentArtifactDao == null) {
        -      componentArtifactDao = MonitoringUploadDaoFactory.getInstance().createInterface();
        +    private ComponentDao getComponentDao() {
        +        if (componentDao == null) {
        +            componentDao = ComponentDaoFactory.getInstance().createInterface();
        +        }
        +        return componentDao;
             }
        -    return componentArtifactDao;
        -  }
         
        +    private ComponentArtifactDao getComponentArtifactDao() {
        +        if (componentArtifactDao == null) {
        +            componentArtifactDao = MonitoringUploadDaoFactory.getInstance().createInterface();
        +        }
        +        return componentArtifactDao;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java
        index bade8ec66b..dd64bfb137 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,9 +17,14 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl.external.artifact;
         
        +import java.io.File;
        +import java.io.IOException;
        +import java.util.Collection;
        +import java.util.HashMap;
        +import java.util.List;
        +import java.util.Map;
         import org.openecomp.core.enrichment.types.ArtifactCategory;
         import org.openecomp.core.enrichment.types.ComponentProcessInfo;
         import org.openecomp.core.model.dao.EnrichedServiceModelDao;
        @@ -39,99 +44,75 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity;
         import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.io.File;
        -import java.io.IOException;
        -import java.util.Collection;
        -import java.util.HashMap;
        -import java.util.List;
        -import java.util.Map;
        -
         public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterface {
         
        -  private ComponentDao componentDao;
        -  private ProcessDao processDao;
        -  private EnrichedServiceModelDao enrichedServiceModelDao;
        -
        -  @Override
        -  public Map> enrich(EnrichmentInfo enrichmentInfo,
        -                                                ToscaServiceModel serviceModel) throws IOException {
        -    Map> errors = new HashMap<>();
        -    String vspId = enrichmentInfo.getKey();
        -    Version version = enrichmentInfo.getVersion();
        -
        -    Collection components =
        -        getComponentDao().list(new ComponentEntity(vspId, version, null));
        -    components.forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry,
        -        vspId, version)));
        -
        -    return errors;
        -  }
        -
        -  Map> enrichComponent(ComponentEntity componentEntry, String vspId,
        -                                                  Version version) {
        -    Map> errors = new HashMap<>();
        -    enrichComponentProcessArtifact(componentEntry, vspId, version, errors);
        -    return errors;
        -  }
        -
        -  void enrichComponentProcessArtifact(ComponentEntity componentEntity,
        -                                      String vspId, Version version,
        -                                      Map> errors) {
        -    String componentId = componentEntity.getId();
        -    ProcessEntity processEntity = new ProcessEntity(vspId, version, componentId, null);
        -    final Collection processes = getProcessDao().list(processEntity);
        -
        -    processes.forEach(entity -> {
        -      ProcessEntity artifactEntity = new ProcessEntity(vspId, version,
        -          componentId, entity.getId());
        -
        -          ProcessEntity artifactProcessEntity = getProcessDao().getArtifact(artifactEntity);
        -          if (artifactProcessEntity != null && ProcessType.Lifecycle_Operations.equals(
        -              artifactProcessEntity.getType())
        -              && artifactProcessEntity.getArtifactName() != null ) {
        -            String componentName = componentEntity.getComponentCompositionData().getName();
        -            String path = componentName + File.separator
        -                + ArtifactCategory.DEPLOYMENT.getDisplayName() + File.separator
        -                + "Lifecycle Operations" + File.separator + artifactProcessEntity.getArtifactName();
        +    private ComponentDao componentDao;
        +    private ProcessDao processDao;
        +    private EnrichedServiceModelDao enrichedServiceModelDao;
        +
        +    @Override
        +    public Map> enrich(EnrichmentInfo enrichmentInfo, ToscaServiceModel serviceModel) throws IOException {
        +        Map> errors = new HashMap<>();
        +        String vspId = enrichmentInfo.getKey();
        +        Version version = enrichmentInfo.getVersion();
        +        Collection components = getComponentDao().list(new ComponentEntity(vspId, version, null));
        +        components.forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry, vspId, version)));
        +        return errors;
        +    }
         
        -            ComponentProcessInfo componentProcessInfo = new ComponentProcessInfo();
        -            componentProcessInfo.setName(path);
        -            componentProcessInfo.setContent(artifactProcessEntity.getArtifact().array());
        +    Map> enrichComponent(ComponentEntity componentEntry, String vspId, Version version) {
        +        Map> errors = new HashMap<>();
        +        enrichComponentProcessArtifact(componentEntry, vspId, version, errors);
        +        return errors;
        +    }
         
        -            ServiceArtifact processServiceArtifact = new ServiceArtifact();
        -            processServiceArtifact.setVspId(vspId);
        -            processServiceArtifact.setVersion(version);
        -            enrichServiceArtifact(componentProcessInfo, processServiceArtifact);
        -          }
        +    void enrichComponentProcessArtifact(ComponentEntity componentEntity, String vspId, Version version, Map> errors) {
        +        String componentId = componentEntity.getId();
        +        ProcessEntity processEntity = new ProcessEntity(vspId, version, componentId, null);
        +        final Collection processes = getProcessDao().list(processEntity);
        +        processes.forEach(entity -> {
        +            ProcessEntity artifactEntity = new ProcessEntity(vspId, version, componentId, entity.getId());
        +            ProcessEntity artifactProcessEntity = getProcessDao().getArtifact(artifactEntity);
        +            if (artifactProcessEntity != null && ProcessType.Lifecycle_Operations.equals(artifactProcessEntity.getType())
        +                && artifactProcessEntity.getArtifactName() != null) {
        +                String componentName = componentEntity.getComponentCompositionData().getName();
        +                String path = componentName + File.separator + ArtifactCategory.DEPLOYMENT.getDisplayName() + File.separator + "Lifecycle Operations"
        +                    + File.separator + artifactProcessEntity.getArtifactName();
        +                ComponentProcessInfo componentProcessInfo = new ComponentProcessInfo();
        +                componentProcessInfo.setName(path);
        +                componentProcessInfo.setContent(artifactProcessEntity.getArtifact().array());
        +                ServiceArtifact processServiceArtifact = new ServiceArtifact();
        +                processServiceArtifact.setVspId(vspId);
        +                processServiceArtifact.setVersion(version);
        +                enrichServiceArtifact(componentProcessInfo, processServiceArtifact);
        +            }
                 });
        -  }
        -
        -  void enrichServiceArtifact(ComponentProcessInfo componentProcessInfo,
        -                             ServiceArtifact processServiceArtifact) {
        -    processServiceArtifact.setName(componentProcessInfo.getName());
        -    processServiceArtifact.setContentData(FileUtils.toByteArray(componentProcessInfo.getContent()));
        -    getEnrichedServiceModelDao().storeExternalArtifact(processServiceArtifact);
        -  }
        +    }
         
        -  private ComponentDao getComponentDao() {
        -    if (componentDao == null) {
        -      componentDao = ComponentDaoFactory.getInstance().createInterface();
        +    void enrichServiceArtifact(ComponentProcessInfo componentProcessInfo, ServiceArtifact processServiceArtifact) {
        +        processServiceArtifact.setName(componentProcessInfo.getName());
        +        processServiceArtifact.setContentData(FileUtils.toByteArray(componentProcessInfo.getContent()));
        +        getEnrichedServiceModelDao().storeExternalArtifact(processServiceArtifact);
             }
        -    return componentDao;
        -  }
         
        -  private ProcessDao getProcessDao() {
        -    if (processDao == null) {
        -      processDao = ProcessDaoFactory.getInstance().createInterface();
        +    private ComponentDao getComponentDao() {
        +        if (componentDao == null) {
        +            componentDao = ComponentDaoFactory.getInstance().createInterface();
        +        }
        +        return componentDao;
             }
        -    return processDao;
        -  }
         
        -  private EnrichedServiceModelDao getEnrichedServiceModelDao() {
        +    private ProcessDao getProcessDao() {
        +        if (processDao == null) {
        +            processDao = ProcessDaoFactory.getInstance().createInterface();
        +        }
        +        return processDao;
        +    }
         
        -    if (enrichedServiceModelDao == null) {
        -      enrichedServiceModelDao = EnrichedServiceModelDaoFactory.getInstance().createInterface();
        +    private EnrichedServiceModelDao getEnrichedServiceModelDao() {
        +        if (enrichedServiceModelDao == null) {
        +            enrichedServiceModelDao = EnrichedServiceModelDaoFactory.getInstance().createInterface();
        +        }
        +        return enrichedServiceModelDao;
             }
        -    return enrichedServiceModelDao;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java
        index 8f3c57f432..6be1b5f2cd 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,10 +17,16 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl.external.artifact;
         
        -
        +import java.io.File;
        +import java.io.IOException;
        +import java.nio.ByteBuffer;
        +import java.util.ArrayList;
        +import java.util.HashMap;
        +import java.util.List;
        +import java.util.Map;
        +import java.util.Objects;
         import org.openecomp.core.enrichment.types.ArtifactCategory;
         import org.openecomp.core.enrichment.types.InformationArtifactFolderNames;
         import org.openecomp.core.model.dao.EnrichedServiceModelDao;
        @@ -39,70 +45,46 @@ import org.openecomp.sdc.vendorsoftwareproduct.factory.InformationArtifactGenera
         import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.io.File;
        -import java.io.IOException;
        -import java.nio.ByteBuffer;
        -import java.util.*;
        -
         /**
          * Created by Talio on 11/24/2016
          */
         public class VspInformationArtifactEnricher implements ExternalArtifactEnricherInterface {
        -  private static InformationArtifactGenerator informationArtifactGenerator =
        -      InformationArtifactGeneratorFactory.getInstance().createInterface();
        -  private EnrichedServiceModelDao enrichedServiceModelDao =
        -      EnrichedServiceModelDaoFactory.getInstance().createInterface();
        -  private VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory
        -      .getInstance().createInterface();
        -
        -  public VspInformationArtifactEnricher() {
        -  }
         
        -  public Map> enrich(EnrichmentInfo enrichmentInfo,
        -                                                ToscaServiceModel serviceModel)
        -      throws IOException {
        +    private static InformationArtifactGenerator informationArtifactGenerator = InformationArtifactGeneratorFactory.getInstance().createInterface();
        +    private EnrichedServiceModelDao enrichedServiceModelDao = EnrichedServiceModelDaoFactory.getInstance().createInterface();
        +    private VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface();
         
        -    String vspId = enrichmentInfo.getKey();
        -    Version version = enrichmentInfo.getVersion();
        -    return enrichInformationArtifact(vspId, version);
        -  }
        -
        -  private Map> enrichInformationArtifact(String vspId, Version version)
        -      throws IOException {
        -    Map> errors = new HashMap<>();
        -    ByteBuffer infoArtifactByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate(
        -        vspId, version).getBytes());
        -
        -    if (Objects.isNull(infoArtifactByteBuffer)) {
        -      List errorList = new ArrayList<>();
        -      errorList.add(new ErrorMessage(ErrorLevel.ERROR, String.format(
        -          "Cannot enrich information artifact for vendor software product with id %s and version %s",
        -          vspId, version.toString())));
        -      return errors;
        +    public VspInformationArtifactEnricher() {
             }
         
        -    enrichInformationArtifact(vspId, version, infoArtifactByteBuffer);
        -    return errors;
        -  }
        -
        -  private void enrichInformationArtifact(String vspId, Version version,
        -                                         ByteBuffer infoArtifactByteBuffer) {
        -    ServiceArtifact infoArtifactServiceArtifact = new ServiceArtifact();
        -
        -    String vspName = vspInfoDao.get(new VspDetails(vspId, version)).getName();
        -
        -    infoArtifactServiceArtifact.setVspId(vspId);
        -    infoArtifactServiceArtifact.setVersion(version);
        -    infoArtifactServiceArtifact
        -        .setName(ArtifactCategory.INFORMATIONAL.getDisplayName() + File.separator
        -            + InformationArtifactFolderNames.Guide + File.separator + String.format(
        -            VendorSoftwareProductConstants
        -                .INFORMATION_ARTIFACT_NAME,
        -            vspName));
        -    infoArtifactServiceArtifact.setContentData(infoArtifactByteBuffer.array());
        -
        -    enrichedServiceModelDao.storeExternalArtifact(infoArtifactServiceArtifact);
        +    public Map> enrich(EnrichmentInfo enrichmentInfo, ToscaServiceModel serviceModel) throws IOException {
        +        String vspId = enrichmentInfo.getKey();
        +        Version version = enrichmentInfo.getVersion();
        +        return enrichInformationArtifact(vspId, version);
        +    }
         
        -  }
        +    private Map> enrichInformationArtifact(String vspId, Version version) throws IOException {
        +        Map> errors = new HashMap<>();
        +        ByteBuffer infoArtifactByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate(vspId, version).getBytes());
        +        if (Objects.isNull(infoArtifactByteBuffer)) {
        +            List errorList = new ArrayList<>();
        +            errorList.add(new ErrorMessage(ErrorLevel.ERROR, String
        +                .format("Cannot enrich information artifact for vendor software product with id %s and version %s", vspId, version.toString())));
        +            return errors;
        +        }
        +        enrichInformationArtifact(vspId, version, infoArtifactByteBuffer);
        +        return errors;
        +    }
         
        +    private void enrichInformationArtifact(String vspId, Version version, ByteBuffer infoArtifactByteBuffer) {
        +        ServiceArtifact infoArtifactServiceArtifact = new ServiceArtifact();
        +        String vspName = vspInfoDao.get(new VspDetails(vspId, version)).getName();
        +        infoArtifactServiceArtifact.setVspId(vspId);
        +        infoArtifactServiceArtifact.setVersion(version);
        +        infoArtifactServiceArtifact.setName(
        +            ArtifactCategory.INFORMATIONAL.getDisplayName() + File.separator + InformationArtifactFolderNames.Guide + File.separator + String
        +                .format(VendorSoftwareProductConstants.INFORMATION_ARTIFACT_NAME, vspName));
        +        infoArtifactServiceArtifact.setContentData(infoArtifactByteBuffer.array());
        +        enrichedServiceModelDao.storeExternalArtifact(infoArtifactServiceArtifact);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
        index a6bb9323ee..7148d1b3d9 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/AbstractSubstituteToscaEnricher.java
        @@ -13,9 +13,29 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.enrichment.impl.tosca;
         
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.HIGH_AVAIL_MODE;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MANDATORY;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MAX_INSTANCES;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MIN_INSTANCES;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.NFC_FUNCTION;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.NFC_NAMING_CODE;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_CODE;
        +import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VM_TYPE_TAG;
        +import static org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType.NATIVE_NODE;
        +import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.MULTIDEPLOYMENTFLAVOR_NODE_TYPE;
        +import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE;
        +import static org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType.NATIVE_DEPENDS_ON;
        +import static org.openecomp.sdc.tosca.services.ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME;
        +import static org.openecomp.sdc.translator.services.heattotosca.Constants.VNF_NODE_TEMPLATE_ID_SUFFIX;
        +
        +import java.util.ArrayList;
        +import java.util.HashMap;
        +import java.util.List;
        +import java.util.Map;
        +import java.util.Objects;
        +import java.util.Optional;
         import org.apache.commons.collections4.CollectionUtils;
         import org.apache.commons.lang3.StringUtils;
         import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
        @@ -33,98 +53,51 @@ import org.openecomp.sdc.tosca.services.ToscaConstants;
         import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -import java.util.ArrayList;
        -import java.util.HashMap;
        -import java.util.List;
        -import java.util.Map;
        -import java.util.Objects;
        -import java.util.Optional;
        -
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.HIGH_AVAIL_MODE;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MANDATORY;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MAX_INSTANCES;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MIN_INSTANCES;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.NFC_FUNCTION;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.NFC_NAMING_CODE;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_CODE;
        -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VM_TYPE_TAG;
        -import static org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType.NATIVE_NODE;
        -import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.MULTIDEPLOYMENTFLAVOR_NODE_TYPE;
        -import static org.openecomp.sdc.tosca.datatypes.ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE;
        -import static org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType.NATIVE_DEPENDS_ON;
        -import static org.openecomp.sdc.tosca.services.ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME;
        -import static org.openecomp.sdc.translator.services.heattotosca.Constants.VNF_NODE_TEMPLATE_ID_SUFFIX;
        -
         public class AbstractSubstituteToscaEnricher {
         
             private ToscaAnalyzerService toscaAnalyzerService;
             private ComponentQuestionnaireData componentQuestionnaireData;
         
        -
             public Map> enrich(ToscaServiceModel toscaModel, String vspId, Version version) {
                 componentQuestionnaireData = getComponentQuestionnaireData();
                 toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
        -
        -        Map> componentProperties =
        -                componentQuestionnaireData.getPropertiesfromCompQuestionnaire(vspId, version);
        -
        +        Map> componentProperties = componentQuestionnaireData.getPropertiesfromCompQuestionnaire(vspId, version);
                 final Map> sourceToTargetDependencies = componentQuestionnaireData
        -                                                                             .populateDependencies(vspId, version,
        -                                                                                     componentQuestionnaireData
        -                                                                                      .getSourceToTargetComponent());
        +            .populateDependencies(vspId, version, componentQuestionnaireData.getSourceToTargetComponent());
                 Map> errors = new HashMap<>();
        -
        -        final ServiceTemplate serviceTemplate =
        -                toscaModel.getServiceTemplates().get(toscaModel.getEntryDefinitionServiceTemplate());
        -
        +        final ServiceTemplate serviceTemplate = toscaModel.getServiceTemplates().get(toscaModel.getEntryDefinitionServiceTemplate());
                 if (serviceTemplate == null) {
                     return errors;
                 }
        -
                 final TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template();
                 if (topologyTemplate == null) {
                     return errors;
                 }
        -
                 final Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates();
                 if (nodeTemplates == null) {
                     return errors;
                 }
        -
        -        final Map> componentDisplayNameToNodeTemplateIds =
        -                populateAllNodeTemplateIdForComponent(nodeTemplates, serviceTemplate, toscaModel);
        -
        +        final Map> componentDisplayNameToNodeTemplateIds = populateAllNodeTemplateIdForComponent(nodeTemplates, serviceTemplate,
        +            toscaModel);
                 nodeTemplates.keySet().forEach(nodeTemplateId -> {
        -            final NodeTemplate nodeTemplate =
        -                    toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId).orElse(null);
        -
        -            if (nodeTemplate != null && toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE,
        -                    serviceTemplate, toscaModel)) {
        -
        +            final NodeTemplate nodeTemplate = toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId).orElse(null);
        +            if (nodeTemplate != null && toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate, toscaModel)) {
                         String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
        -
                         enrichProperties(nodeTemplate, componentDisplayName, componentProperties);
        -
        -                enrichRequirements(sourceToTargetDependencies, componentDisplayName, nodeTemplate,
        -                        componentDisplayNameToNodeTemplateIds, serviceTemplate, toscaModel);
        +                enrichRequirements(sourceToTargetDependencies, componentDisplayName, nodeTemplate, componentDisplayNameToNodeTemplateIds,
        +                    serviceTemplate, toscaModel);
                     }
                 });
                 return errors;
             }
         
        -    private void enrichProperties(NodeTemplate nodeTemplate, String componentDisplayName,
        -            Map> componentProperties) {
        +    private void enrichProperties(NodeTemplate nodeTemplate, String componentDisplayName, Map> componentProperties) {
                 setProperty(nodeTemplate, VM_TYPE_TAG, componentDisplayName);
        -
                 if (componentProperties != null && componentProperties.containsKey(componentDisplayName)) {
        -            final String mandatory =
        -                    getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, MANDATORY);
        -
        +            final String mandatory = getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, MANDATORY);
                     boolean isServiceTemplateFilterNotExists = false;
                     if (!StringUtils.isEmpty(mandatory)) {
        -                Map innerProps = (Map) nodeTemplate.getProperties()
        -                                                                   .get(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
        -
        +                Map innerProps = (Map) nodeTemplate.getProperties().get(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
                         if (innerProps == null) {
                             innerProps = new HashMap<>();
                             isServiceTemplateFilterNotExists = true;
        @@ -133,55 +106,31 @@ public class AbstractSubstituteToscaEnricher {
                         if (mandatoryValue.isPresent()) {
                             innerProps.put(MANDATORY, mandatoryValue.get());
                         }
        -
                         if (isServiceTemplateFilterNotExists) {
                             nodeTemplate.getProperties().put(SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
                         }
                     }
        -
        -            setProperty(nodeTemplate, HIGH_AVAIL_MODE,
        -                    getValueFromQuestionnaireDetails(componentProperties, componentDisplayName,
        -                            HIGH_AVAIL_MODE));
        -
        -            setProperty(nodeTemplate, NFC_NAMING_CODE,
        -                    getValueFromQuestionnaireDetails(componentProperties, componentDisplayName,
        -                            NFC_NAMING_CODE));
        -
        -            setProperty(nodeTemplate, VFC_CODE,
        -                    getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, VFC_CODE));
        -
        -            setProperty(nodeTemplate, NFC_FUNCTION,
        -                    getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, NFC_FUNCTION));
        -
        +            setProperty(nodeTemplate, HIGH_AVAIL_MODE, getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, HIGH_AVAIL_MODE));
        +            setProperty(nodeTemplate, NFC_NAMING_CODE, getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, NFC_NAMING_CODE));
        +            setProperty(nodeTemplate, VFC_CODE, getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, VFC_CODE));
        +            setProperty(nodeTemplate, NFC_FUNCTION, getValueFromQuestionnaireDetails(componentProperties, componentDisplayName, NFC_FUNCTION));
                     if (componentProperties.get(componentDisplayName).get(MIN_INSTANCES) != null) {
        -                nodeTemplate.getProperties().put(MIN_INSTANCES,
        -                        componentProperties.get(componentDisplayName).get(MIN_INSTANCES));
        +                nodeTemplate.getProperties().put(MIN_INSTANCES, componentProperties.get(componentDisplayName).get(MIN_INSTANCES));
                     }
        -
                     if (componentProperties.get(componentDisplayName).get(MAX_INSTANCES) != null) {
        -                nodeTemplate.getProperties().put(MAX_INSTANCES,
        -                        componentProperties.get(componentDisplayName).get(MAX_INSTANCES));
        +                nodeTemplate.getProperties().put(MAX_INSTANCES, componentProperties.get(componentDisplayName).get(MAX_INSTANCES));
                     }
                 }
             }
         
        -    private Map> populateAllNodeTemplateIdForComponent(Map nodeTemplates,
        -                                                                                   ServiceTemplate serviceTemplate,
        -                                                                                   ToscaServiceModel toscaModel) {
        -
        -
        +    private Map> populateAllNodeTemplateIdForComponent(Map nodeTemplates, ServiceTemplate serviceTemplate,
        +                                                                            ToscaServiceModel toscaModel) {
                 Map> componentDisplayNameToNodeTempalteIds = new HashMap<>();
        -
                 //set dependency target
                 nodeTemplates.keySet().forEach(nodeTemplateId -> {
        -            final NodeTemplate nodeTemplate =
        -                    toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId).orElse(null);
        -
        -            if (nodeTemplate != null &&
        -                    toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate, toscaModel)) {
        -
        +            final NodeTemplate nodeTemplate = toscaAnalyzerService.getNodeTemplateById(serviceTemplate, nodeTemplateId).orElse(null);
        +            if (nodeTemplate != null && toscaAnalyzerService.isTypeOf(nodeTemplate, VFC_ABSTRACT_SUBSTITUTE, serviceTemplate, toscaModel)) {
                         String componentDisplayName = getComponentDisplayName(nodeTemplateId, nodeTemplate);
        -
                         if (componentDisplayNameToNodeTempalteIds.containsKey(componentDisplayName)) {
                             componentDisplayNameToNodeTempalteIds.get(componentDisplayName).add(nodeTemplateId);
                         } else {
        @@ -189,49 +138,42 @@ public class AbstractSubstituteToscaEnricher {
                             nodeTemplateIds.add(nodeTemplateId);
                             componentDisplayNameToNodeTempalteIds.put(componentDisplayName, nodeTemplateIds);
                         }
        -
                     }
                 });
        -
                 return componentDisplayNameToNodeTempalteIds;
             }
         
        -    private void enrichRequirements(Map> sourceToTargetDependencies, String componentDisplayName,
        -                                           NodeTemplate nodeTemplate,
        -                                           Map> componentDisplayNameToNodeTempalteIds,
        -                                           ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) {
        +    private void enrichRequirements(Map> sourceToTargetDependencies, String componentDisplayName, NodeTemplate nodeTemplate,
        +                                    Map> componentDisplayNameToNodeTempalteIds, ServiceTemplate serviceTemplate,
        +                                    ToscaServiceModel toscaServiceModel) {
                 final List targets = sourceToTargetDependencies.get(componentDisplayName);
                 if (CollectionUtils.isEmpty(targets)) {
                     return;
                 }
        -
                 for (String target : targets) {
                     List targetNodeTemplateIds = componentDisplayNameToNodeTempalteIds.get(target);
                     if (CollectionUtils.isEmpty(targetNodeTemplateIds)) {
                         continue;
                     }
                     for (String targetNodeTemplateId : targetNodeTemplateIds) {
        -                Optional dependencyRequirementKey =
        -                        getDependencyRequirementKey(serviceTemplate, componentDisplayName, nodeTemplate,
        -                                toscaServiceModel);
        +                Optional dependencyRequirementKey = getDependencyRequirementKey(serviceTemplate, componentDisplayName, nodeTemplate,
        +                    toscaServiceModel);
                         if (dependencyRequirementKey.isPresent()) {
                             RequirementAssignment requirementAssignment = new RequirementAssignment();
                             requirementAssignment.setCapability(NATIVE_NODE);
                             requirementAssignment.setRelationship(NATIVE_DEPENDS_ON);
                             requirementAssignment.setNode(targetNodeTemplateId);
        -                    DataModelUtil.addRequirementAssignment(nodeTemplate, dependencyRequirementKey.get(),
        -                            requirementAssignment);
        +                    DataModelUtil.addRequirementAssignment(nodeTemplate, dependencyRequirementKey.get(), requirementAssignment);
                         }
                     }
                 }
             }
         
        -    private Optional getDependencyRequirementKey(ServiceTemplate serviceTemplate, String componentDisplayName,
        -                                                                NodeTemplate nodeTemplate,
        -                                                                ToscaServiceModel toscaServiceModel) {
        +    private Optional getDependencyRequirementKey(ServiceTemplate serviceTemplate, String componentDisplayName, NodeTemplate nodeTemplate,
        +                                                         ToscaServiceModel toscaServiceModel) {
                 String nodeType = nodeTemplate.getType();
        -        NodeType flatNodeType = (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType,
        -                serviceTemplate, toscaServiceModel).getFlatEntity();
        +        NodeType flatNodeType = (NodeType) toscaAnalyzerService
        +            .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType, serviceTemplate, toscaServiceModel).getFlatEntity();
                 List> flatNodeTypeRequirements = flatNodeType.getRequirements();
                 if (Objects.isNull(flatNodeTypeRequirements)) {
                     return Optional.empty();
        @@ -259,14 +201,15 @@ public class AbstractSubstituteToscaEnricher {
                 return componentDisplayName;
             }
         
        -    private String getValueFromQuestionnaireDetails(Map> componentTypetoParams,
        -                                                           String componentDisplayName, String propertyName) {
        +    private String getValueFromQuestionnaireDetails(Map> componentTypetoParams, String componentDisplayName,
        +                                                    String propertyName) {
                 return (String) componentTypetoParams.get(componentDisplayName).get(propertyName);
             }
         
             private void setProperty(NodeTemplate nodeTemplate, String key, String value) {
                 if (!StringUtils.isEmpty(value)) {
                     //YamlUtil throws IllegalStateException("duplicate key: " + key) if key is already present.
        +
                     // So first removing and then populating same key with new updated value
                     nodeTemplate.getProperties().remove(key);
                     nodeTemplate.getProperties().put(key, value);
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java
        index 4b9ed4f45e..db6f37ad85 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.enrichment.impl.tosca;
         
         import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.HIGH_AVAIL_MODE;
        @@ -39,105 +38,73 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData;
         import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ComponentQuestionnaire;
         import org.openecomp.sdc.versioning.dao.types.Version;
         
        -
         public class ComponentQuestionnaireData {
         
        -  ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface();
        -  ComponentDependencyModelDao componentDependencyModelDao =
        -      ComponentDependencyModelDaoFactory.getInstance().createInterface();
        -
        -  private Map sourceToTargetComponent;
        -
        -  public Map getSourceToTargetComponent() {
        -    return sourceToTargetComponent;
        -  }
        -
        -  public void setSourceToTargetComponent(Map sourceToTargetComponent) {
        -    this.sourceToTargetComponent = sourceToTargetComponent;
        -  }
        -
        -  public Map> getPropertiesfromCompQuestionnaire(String key,
        -                                                                             Version version) {
        -    Map> componentProperties = new HashMap<>();
        -
        -    final Collection componentEntities =
        -        componentDao.listCompositionAndQuestionnaire(key, version);
        -
        -    Map sourceToTarget = new HashMap<>();
        -
        -    for (ComponentEntity component : componentEntities) {
        -      Map questionnaireParams = new HashMap<>();
        -
        -      final ComponentQuestionnaire componentQuestionnaire =
        -          JsonUtil.json2Object(component.getQuestionnaireData(), ComponentQuestionnaire.class);
        -
        -      final ComponentData componentData =
        -          JsonUtil.json2Object(component.getCompositionData(), ComponentData.class);
        -
        -      sourceToTarget.put(component.getId(), componentData.getDisplayName());
        -
        -      String nfcNamingCode = componentQuestionnaire.getGeneral().getNfcNamingCode();
        -      questionnaireParams.put(NFC_NAMING_CODE, nfcNamingCode);
        +    ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface();
        +    ComponentDependencyModelDao componentDependencyModelDao = ComponentDependencyModelDaoFactory.getInstance().createInterface();
        +    private Map sourceToTargetComponent;
         
        -      String vfcDescription = componentQuestionnaire.getGeneral().getNfcFunction();
        -      questionnaireParams.put(EnrichmentConstants.NFC_FUNCTION, vfcDescription);
        -
        -
        -      if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null) {
        -        String mandatory = componentQuestionnaire.getHighAvailabilityAndLoadBalancing()
        -            .getIsComponentMandatory();
        -        questionnaireParams.put(MANDATORY, mandatory);
        -
        -        String mode = componentQuestionnaire.getHighAvailabilityAndLoadBalancing()
        -            .getHighAvailabilityMode();
        -
        -        questionnaireParams.put(HIGH_AVAIL_MODE, mode);
        -      }
        -
        -      final Integer maxVms =
        -          componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute()
        -              .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs()
        -              .getMaximum() : null) : null;
        -
        -      final Integer minVms =
        -          componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute()
        -              .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs()
        -              .getMinimum() : null) : null;
        -
        -      questionnaireParams.put(MIN_INSTANCES, minVms != null && minVms == 0 ? null : minVms);
        -      questionnaireParams.put(MAX_INSTANCES, maxVms != null && maxVms == 0 ? null : maxVms);
        -
        -      if (!questionnaireParams.isEmpty()) {
        -        componentProperties.put(JsonUtil.json2Object(component.getCompositionData(),
        -            ComponentData.class).getDisplayName(), questionnaireParams);
        -      }
        +    public Map getSourceToTargetComponent() {
        +        return sourceToTargetComponent;
             }
         
        -    setSourceToTargetComponent(sourceToTarget);
        -
        -    return componentProperties;
        -  }
        -
        -  public Map> populateDependencies(String vspId, Version version, Map componentNameData) {
        -    Collection componentDependencies =
        -        componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null));
        -
        -    Map> dependencies = new HashMap<>();
        -    List targetComponents;
        -    for (ComponentDependencyModelEntity dependency : componentDependencies) {
        -      String sourceComponentName = componentNameData.get(dependency.getSourceComponentId());
        -      String targetComponentName = componentNameData.get(dependency.getTargetComponentId());
        -      if (!dependencies.containsKey(sourceComponentName)) {
        -        targetComponents = new ArrayList<>();
        -      } else {
        -        targetComponents = dependencies.get(sourceComponentName);
        -      }
        -      targetComponents.add(targetComponentName);
        -      dependencies.put(sourceComponentName, targetComponents);
        +    public void setSourceToTargetComponent(Map sourceToTargetComponent) {
        +        this.sourceToTargetComponent = sourceToTargetComponent;
             }
         
        -    return dependencies;
        -  }
        +    public Map> getPropertiesfromCompQuestionnaire(String key, Version version) {
        +        Map> componentProperties = new HashMap<>();
        +        final Collection componentEntities = componentDao.listCompositionAndQuestionnaire(key, version);
        +        Map sourceToTarget = new HashMap<>();
        +        for (ComponentEntity component : componentEntities) {
        +            Map questionnaireParams = new HashMap<>();
        +            final ComponentQuestionnaire componentQuestionnaire = JsonUtil
        +                .json2Object(component.getQuestionnaireData(), ComponentQuestionnaire.class);
        +            final ComponentData componentData = JsonUtil.json2Object(component.getCompositionData(), ComponentData.class);
        +            sourceToTarget.put(component.getId(), componentData.getDisplayName());
        +            String nfcNamingCode = componentQuestionnaire.getGeneral().getNfcNamingCode();
        +            questionnaireParams.put(NFC_NAMING_CODE, nfcNamingCode);
        +            String vfcDescription = componentQuestionnaire.getGeneral().getNfcFunction();
        +            questionnaireParams.put(EnrichmentConstants.NFC_FUNCTION, vfcDescription);
        +            if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null) {
        +                String mandatory = componentQuestionnaire.getHighAvailabilityAndLoadBalancing().getIsComponentMandatory();
        +                questionnaireParams.put(MANDATORY, mandatory);
        +                String mode = componentQuestionnaire.getHighAvailabilityAndLoadBalancing().getHighAvailabilityMode();
        +                questionnaireParams.put(HIGH_AVAIL_MODE, mode);
        +            }
        +            final Integer maxVms =
        +                componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute().getNumOfVMs() != null ? componentQuestionnaire
        +                    .getCompute().getNumOfVMs().getMaximum() : null) : null;
        +            final Integer minVms =
        +                componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute().getNumOfVMs() != null ? componentQuestionnaire
        +                    .getCompute().getNumOfVMs().getMinimum() : null) : null;
        +            questionnaireParams.put(MIN_INSTANCES, minVms != null && minVms == 0 ? null : minVms);
        +            questionnaireParams.put(MAX_INSTANCES, maxVms != null && maxVms == 0 ? null : maxVms);
        +            if (!questionnaireParams.isEmpty()) {
        +                componentProperties
        +                    .put(JsonUtil.json2Object(component.getCompositionData(), ComponentData.class).getDisplayName(), questionnaireParams);
        +            }
        +        }
        +        setSourceToTargetComponent(sourceToTarget);
        +        return componentProperties;
        +    }
         
        +    public Map> populateDependencies(String vspId, Version version, Map componentNameData) {
        +        Collection componentDependencies = componentDependencyModelDao
        +            .list(new ComponentDependencyModelEntity(vspId, version, null));
        +        Map> dependencies = new HashMap<>();
        +        List targetComponents;
        +        for (ComponentDependencyModelEntity dependency : componentDependencies) {
        +            String sourceComponentName = componentNameData.get(dependency.getSourceComponentId());
        +            String targetComponentName = componentNameData.get(dependency.getTargetComponentId());
        +            if (!dependencies.containsKey(sourceComponentName)) {
        +                targetComponents = new ArrayList<>();
        +            } else {
        +                targetComponents = dependencies.get(sourceComponentName);
        +            }
        +            targetComponents.add(targetComponentName);
        +            dependencies.put(sourceComponentName, targetComponents);
        +        }
        +        return dependencies;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java
        index 266d1346e4..b2d1a218f4 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java
        @@ -13,11 +13,23 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.enrichment.impl.tosca;
         
        +import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject;
        +import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_CP_PROPERTY_NAME;
        +import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_ID;
        +
         import com.google.common.collect.ImmutableMap;
         import com.google.common.collect.ImmutableSet;
        +import java.util.ArrayList;
        +import java.util.HashMap;
        +import java.util.LinkedList;
        +import java.util.List;
        +import java.util.Map;
        +import java.util.Objects;
        +import java.util.Optional;
        +import java.util.Set;
        +import java.util.stream.Collectors;
         import org.apache.commons.collections4.CollectionUtils;
         import org.apache.commons.collections4.MapUtils;
         import org.onap.sdc.tosca.datatypes.model.Import;
        @@ -35,32 +47,24 @@ import org.openecomp.sdc.tosca.services.ToscaUtil;
         import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil;
         import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
         
        -import java.util.*;
        -import java.util.stream.Collectors;
        -
        -import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject;
        -import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_CP_PROPERTY_NAME;
        -import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_ID;
        -
         public class PortMirroringEnricher {
        +
             private static final String ABSTRACT_LINK_REQUIREMENT_ID_PREFIX = ToscaConstants.LINK_REQUIREMENT_ID + "_";
             private static final int ABSTRACT_LINK_REQUIREMENT_ID_PREFIX_LENGTH = ABSTRACT_LINK_REQUIREMENT_ID_PREFIX.length();
        -    private static final Map nodeTypeExternalNodeType =  initializeNodeTypeExternalNodeType();
        +    private static final Map nodeTypeExternalNodeType = initializeNodeTypeExternalNodeType();
             //Map of service template file name and map of all port node template ids, node template
             private final Map> portNodeTemplates = new HashMap<>();
             //Map of service template file name and map of external port node template ids, node template
             private final Map> externalPortNodeTemplates = new HashMap<>();
             //Map of substitution service template name and the list of ports with link requirement from the abstract
             private final Map> portNodeTemplateIdsFromAbstract = new HashMap<>();
        -    private final Map globalTypesServiceTemplate =
        -            GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP);
        +    private final Map globalTypesServiceTemplate = GlobalTypesGenerator
        +        .getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP);
         
        -    private static ImmutableMap initializeNodeTypeExternalNodeType() {
        -        return  ImmutableMap.builder()
        -                .put(ToscaNodeType.CONTRAIL_PORT, ToscaNodeType.EXTERNAL_CONTRAIL_PORT)
        -                .put(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE, ToscaNodeType.EXTERNAL_VMI_PORT)
        -                .put(ToscaNodeType.NEUTRON_PORT, ToscaNodeType.EXTERNAL_NEUTRON_PORT)
        -                .build();
        +    private static ImmutableMap initializeNodeTypeExternalNodeType() {
        +        return ImmutableMap.builder().put(ToscaNodeType.CONTRAIL_PORT, ToscaNodeType.EXTERNAL_CONTRAIL_PORT)
        +            .put(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE, ToscaNodeType.EXTERNAL_VMI_PORT)
        +            .put(ToscaNodeType.NEUTRON_PORT, ToscaNodeType.EXTERNAL_NEUTRON_PORT).build();
             }
         
             /**
        @@ -73,11 +77,10 @@ public class PortMirroringEnricher {
                 Map> errors = new HashMap<>();
                 Map serviceTemplates = toscaServiceModel.getServiceTemplates();
                 serviceTemplates.entrySet().stream()
        -                //Skipping the service templates which do not contain topology template
        -                .filter(serviceTemplateEntry -> serviceTemplateEntry.getValue().getTopology_template() != null)
        -                .forEach(serviceTemplateEntry ->
        -                        //Collect all the ports across all the service templates
        -                        collectPorts(serviceTemplateEntry.getValue()));
        +            //Skipping the service templates which do not contain topology template
        +            .filter(serviceTemplateEntry -> serviceTemplateEntry.getValue().getTopology_template() != null).forEach(serviceTemplateEntry ->
        +            //Collect all the ports across all the service templates
        +            collectPorts(serviceTemplateEntry.getValue()));
                 //Collect External ports from the list of all ports collected above
                 filterExternalPorts();
                 //Handle external port changes
        @@ -91,13 +94,10 @@ public class PortMirroringEnricher {
                     return;
                 }
                 //Get all concrete port node templates from the service template
        -        Map serviceTemplatePortNodeTemplates = nodeTemplates.entrySet().stream()
        -                .filter(nodeTemplateEntry -> (Objects.nonNull(nodeTemplateEntry.getValue()))
        -                        && (isPortNodeTemplate(nodeTemplateEntry.getValue().getType())))
        -                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        -
        -        portNodeTemplates.put(ToscaUtil.getServiceTemplateFileName(serviceTemplate),
        -                serviceTemplatePortNodeTemplates);
        +        Map serviceTemplatePortNodeTemplates = nodeTemplates.entrySet().stream().filter(
        +            nodeTemplateEntry -> (Objects.nonNull(nodeTemplateEntry.getValue())) && (isPortNodeTemplate(nodeTemplateEntry.getValue().getType())))
        +            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        +        portNodeTemplates.put(ToscaUtil.getServiceTemplateFileName(serviceTemplate), serviceTemplatePortNodeTemplates);
                 //Get all linked internal ports from abstract node template link requirements
                 collectLinkedInternalPorts(nodeTemplates);
             }
        @@ -112,22 +112,19 @@ public class PortMirroringEnricher {
                 }
             }
         
        -    private void handleSubstitutableNodeTemplate(List abstractLinkedPortNodeTemplates,
        -                                                 NodeTemplate nodeTemplate) {
        +    private void handleSubstitutableNodeTemplate(List abstractLinkedPortNodeTemplates, NodeTemplate nodeTemplate) {
                 List> requirements = nodeTemplate.getRequirements();
                 if (Objects.isNull(requirements)) {
                     return;
                 }
        -        requirements
        -                .forEach(requirement -> addInternalPortToAbstractNode(requirement, abstractLinkedPortNodeTemplates));
        +        requirements.forEach(requirement -> addInternalPortToAbstractNode(requirement, abstractLinkedPortNodeTemplates));
                 if (CollectionUtils.isNotEmpty(abstractLinkedPortNodeTemplates)) {
                     //Populate a map of the substitution service templates and list of internal ports
                     addCollectedPortsToAbstractServiceTemplatePortMap(nodeTemplate, abstractLinkedPortNodeTemplates);
                 }
             }
         
        -    private void addInternalPortToAbstractNode(Map requirement,
        -                                               List abstractLinkedPortNodeTemplates) {
        +    private void addInternalPortToAbstractNode(Map requirement, List abstractLinkedPortNodeTemplates) {
                 String requirementId = requirement.keySet().iterator().next();
                 if (requirementId.startsWith(ABSTRACT_LINK_REQUIREMENT_ID_PREFIX)) {
                     //Collect port node template ids from the link requirement ids in the abstract node template
        @@ -135,16 +132,13 @@ public class PortMirroringEnricher {
                 }
             }
         
        -    private void addCollectedPortsToAbstractServiceTemplatePortMap(NodeTemplate nodeTemplate,
        -                                                                   List abstractLinkedPortNodeTemplates) {
        +    private void addCollectedPortsToAbstractServiceTemplatePortMap(NodeTemplate nodeTemplate, List abstractLinkedPortNodeTemplates) {
                 String substitutionServiceTemplateName;
                 if (Objects.isNull(nodeTemplate.getProperties())) {
                     return;
                 }
        -        Map serviceTemplateFilter = (Map) nodeTemplate.getProperties()
        -                .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
        -        substitutionServiceTemplateName = (String)
        -                serviceTemplateFilter.get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
        +        Map serviceTemplateFilter = (Map) nodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME);
        +        substitutionServiceTemplateName = (String) serviceTemplateFilter.get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME);
                 if (Objects.isNull(substitutionServiceTemplateName)) {
                     return;
                 }
        @@ -194,8 +188,7 @@ public class PortMirroringEnricher {
                 }
             }
         
        -    private void handleExternalPortNodeTemplates(ServiceTemplate serviceTemplate,
        -                                                 Map externalPortNodeTemplates) {
        +    private void handleExternalPortNodeTemplates(ServiceTemplate serviceTemplate, Map externalPortNodeTemplates) {
                 for (Map.Entry externalNodeTemplate : externalPortNodeTemplates.entrySet()) {
                     updateExternalPortNodeTemplate(externalNodeTemplate.getValue());
                     if (Objects.nonNull(DataModelUtil.getSubstitutionMappings(serviceTemplate))) {
        @@ -205,14 +198,12 @@ public class PortMirroringEnricher {
                 }
             }
         
        -    private void addPortMirroringSubstitutionMappingCapability(ServiceTemplate serviceTemplate,
        -                                                               String externalPortNodeTemplateId) {
        +    private void addPortMirroringSubstitutionMappingCapability(ServiceTemplate serviceTemplate, String externalPortNodeTemplateId) {
                 List portMirroringCapability = new LinkedList<>();
                 portMirroringCapability.add(externalPortNodeTemplateId);
                 portMirroringCapability.add(PORT_MIRRORING_CAPABILITY_ID);
                 String substitutionMappingCapabilityId = PORT_MIRRORING_CAPABILITY_ID + "_" + externalPortNodeTemplateId;
        -        DataModelUtil.addSubstitutionMappingCapability(serviceTemplate,
        -                substitutionMappingCapabilityId, portMirroringCapability);
        +        DataModelUtil.addSubstitutionMappingCapability(serviceTemplate, substitutionMappingCapabilityId, portMirroringCapability);
             }
         
             private void addPortMirroringCapability(NodeTemplate portNodeTemplate) {
        @@ -226,17 +217,14 @@ public class PortMirroringEnricher {
                 }
                 if (!connectionPoint.isEmpty()) {
                     portMirroringCapabilityProperties.put(PORT_MIRRORING_CAPABILITY_CP_PROPERTY_NAME, connectionPoint);
        -            DataModelUtil.addNodeTemplateCapability(portNodeTemplate,
        -                    PORT_MIRRORING_CAPABILITY_ID, portMirroringCapabilityProperties, null);
        +            DataModelUtil.addNodeTemplateCapability(portNodeTemplate, PORT_MIRRORING_CAPABILITY_ID, portMirroringCapabilityProperties, null);
                 }
             }
         
        -    private void setConnectionPointNfcType(NodeTemplate portNodeTemplate,
        -                                           PortMirroringConnectionPointDescription connectionPoint) {
        +    private void setConnectionPointNfcType(NodeTemplate portNodeTemplate, PortMirroringConnectionPointDescription connectionPoint) {
                 //Get NFC_Type from the binding requirement node
        -        Optional> requirementAssignment =
        -                DataModelUtil.getRequirementAssignment(portNodeTemplate.getRequirements(), ToscaConstants
        -                        .BINDING_REQUIREMENT_ID);
        +        Optional> requirementAssignment = DataModelUtil
        +            .getRequirementAssignment(portNodeTemplate.getRequirements(), ToscaConstants.BINDING_REQUIREMENT_ID);
                 if (requirementAssignment.isPresent()) {
                     RequirementAssignment bindingRequirementAssignment = requirementAssignment.get().get(0);
                     String node = bindingRequirementAssignment.getNode();
        @@ -244,10 +232,8 @@ public class PortMirroringEnricher {
                 }
             }
         
        -    private void setConnectionPointNetworkRole(NodeTemplate portNodeTemplate,
        -                                               PortMirroringConnectionPointDescription connectionPoint) {
        -        Object networkRolePropertyValue =
        -                portNodeTemplate.getProperties().get(ToscaConstants.PORT_NETWORK_ROLE_PROPERTY_NAME);
        +    private void setConnectionPointNetworkRole(NodeTemplate portNodeTemplate, PortMirroringConnectionPointDescription connectionPoint) {
        +        Object networkRolePropertyValue = portNodeTemplate.getProperties().get(ToscaConstants.PORT_NETWORK_ROLE_PROPERTY_NAME);
                 if (Objects.nonNull(networkRolePropertyValue)) {
                     Object portMirroringNetworkRolePropertyVal = getClonedObject(networkRolePropertyValue);
                     connectionPoint.setNetwork_role(portMirroringNetworkRolePropertyVal);
        @@ -257,9 +243,8 @@ public class PortMirroringEnricher {
             private void addGlobalTypeImport(ServiceTemplate serviceTemplate) {
                 List> imports = serviceTemplate.getImports();
                 Map openecompIndexImport = new HashMap<>();
        -        openecompIndexImport.put("openecomp_index",
        -                HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate
        -                        .get("openecomp/_index.yml")));
        +        openecompIndexImport
        +            .put("openecomp_index", HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get("openecomp/_index.yml")));
                 imports.add(openecompIndexImport);
             }
         
        @@ -270,26 +255,22 @@ public class PortMirroringEnricher {
             }
         
             private Set getPortNodeTypes() {
        -        return ImmutableSet.of(ToscaNodeType.NEUTRON_PORT,
        -                ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE, ToscaNodeType.CONTRAIL_PORT);
        +        return ImmutableSet.of(ToscaNodeType.NEUTRON_PORT, ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE, ToscaNodeType.CONTRAIL_PORT);
             }
         
             private boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) {
        -        return Objects.nonNull(nodeTemplate.getDirectives())
        -                && nodeTemplate.getDirectives()
        -                .contains(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
        +        return Objects.nonNull(nodeTemplate.getDirectives()) && nodeTemplate.getDirectives()
        +            .contains(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
             }
         
        -    private boolean isInternalPort(String serviceTemplateFileName, String nodeTemplateId,
        -                                   NodeTemplate nodeTemplate) {
        -        return isAbstractInternalPort(serviceTemplateFileName, nodeTemplateId)
        -                || isConcreteInternalPort(nodeTemplate);
        +    private boolean isInternalPort(String serviceTemplateFileName, String nodeTemplateId, NodeTemplate nodeTemplate) {
        +        return isAbstractInternalPort(serviceTemplateFileName, nodeTemplateId) || isConcreteInternalPort(nodeTemplate);
             }
         
             private boolean isAbstractInternalPort(String serviceTemplateFileName, String nodeTemplateId) {
                 //Check if port corresponds to an abstract internal port
        -        return portNodeTemplateIdsFromAbstract.containsKey(serviceTemplateFileName)
        -                && portNodeTemplateIdsFromAbstract.get(serviceTemplateFileName).contains(nodeTemplateId);
        +        return portNodeTemplateIdsFromAbstract.containsKey(serviceTemplateFileName) && portNodeTemplateIdsFromAbstract.get(serviceTemplateFileName)
        +            .contains(nodeTemplateId);
             }
         
             private boolean isConcreteInternalPort(NodeTemplate nodeTemplate) {
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java
        index 26c1be9938..ee459afa0d 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,57 +17,48 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl.tosca;
         
        -import org.openecomp.sdc.datatypes.error.ErrorLevel;
        -import org.openecomp.sdc.datatypes.error.ErrorMessage;
        -import org.openecomp.sdc.enrichment.inter.Enricher;
        -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
        -
         import java.util.Arrays;
         import java.util.HashMap;
         import java.util.List;
         import java.util.Map;
        +import org.openecomp.sdc.datatypes.error.ErrorLevel;
        +import org.openecomp.sdc.datatypes.error.ErrorMessage;
        +import org.openecomp.sdc.enrichment.inter.Enricher;
        +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
         
         public class ToscaEnricher extends Enricher {
        -  @Override
        -  public Map> enrich() {
        -    Map> errors = new HashMap<>();
        -    errors.putAll(enrichAbstractSubstitute());
        -    errors.putAll(enrichPortMirroring());
        -
        -    return errors;
        -  }
         
        -  private Map> enrichAbstractSubstitute() {
        -    Map> enrichErrors = new HashMap<>();
        -
        -    ToscaServiceModel toscaModel = (ToscaServiceModel) model;
        -    AbstractSubstituteToscaEnricher abstractSubstituteToscaEnricher =
        -        new AbstractSubstituteToscaEnricher();
        -
        -    try {
        -      enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(),
        -          data.getVersion());
        -    }catch (Exception e){
        -      enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e
        -          .getMessage())));
        +    @Override
        +    public Map> enrich() {
        +        Map> errors = new HashMap<>();
        +        errors.putAll(enrichAbstractSubstitute());
        +        errors.putAll(enrichPortMirroring());
        +        return errors;
             }
        -    return enrichErrors;
        -  }
         
        -  private Map> enrichPortMirroring() {
        -    Map> enrichErrors = new HashMap<>();
        -    ToscaServiceModel toscaModel = (ToscaServiceModel) model;
        -    PortMirroringEnricher portMirroringEnricher = new PortMirroringEnricher();
        +    private Map> enrichAbstractSubstitute() {
        +        Map> enrichErrors = new HashMap<>();
        +        ToscaServiceModel toscaModel = (ToscaServiceModel) model;
        +        AbstractSubstituteToscaEnricher abstractSubstituteToscaEnricher = new AbstractSubstituteToscaEnricher();
        +        try {
        +            enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(), data.getVersion());
        +        } catch (Exception e) {
        +            enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e.getMessage())));
        +        }
        +        return enrichErrors;
        +    }
         
        -    try {
        -      enrichErrors = portMirroringEnricher.enrich(toscaModel);
        -    }catch (Exception e){
        -      enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e
        -          .getMessage())));
        +    private Map> enrichPortMirroring() {
        +        Map> enrichErrors = new HashMap<>();
        +        ToscaServiceModel toscaModel = (ToscaServiceModel) model;
        +        PortMirroringEnricher portMirroringEnricher = new PortMirroringEnricher();
        +        try {
        +            enrichErrors = portMirroringEnricher.enrich(toscaModel);
        +        } catch (Exception e) {
        +            enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e.getMessage())));
        +        }
        +        return enrichErrors;
             }
        -    return enrichErrors;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/model/PortMirroringConnectionPointDescription.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/model/PortMirroringConnectionPointDescription.java
        index 9654ba5130..64d90262da 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/model/PortMirroringConnectionPointDescription.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/model/PortMirroringConnectionPointDescription.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,87 +17,83 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.impl.tosca.model;
         
         import java.util.Objects;
         
         @SuppressWarnings("CheckStyle")
         public class PortMirroringConnectionPointDescription {
        -  private String nf_type;
        -  private String nfc_type;
        -  private String nf_naming_code;
        -  private String nfc_naming_code;
        -
        -  //Keeping below attributes as objects to accomodate for tosca functions for property
        -  // values like get_input, get_attribute
        -  private Object network_role;
        -  private Object pps_capacity;
        -
        -  public PortMirroringConnectionPointDescription() {
        -    //Populating empty strings as default values to be populated in tosca
        -    nf_type = "";
        -    nfc_type = "";
        -    nf_naming_code = "";
        -    nfc_naming_code = "";
        -    network_role = "";
        -    pps_capacity = "";
        -  }
        -
        -  public String getNf_type() {
        -    return nf_type;
        -  }
        -
        -  public void setNf_type(String nf_type) {
        -    this.nf_type = nf_type;
        -  }
        -
        -  public String getNfc_type() {
        -    return nfc_type;
        -  }
        -
        -  public void setNfc_type(String nfc_type) {
        -    this.nfc_type = nfc_type;
        -  }
        -
        -  public String getNf_naming_code() {
        -    return nf_naming_code;
        -  }
        -
        -  public void setNf_naming_code(String nf_naming_code) {
        -    this.nf_naming_code = nf_naming_code;
        -  }
        -
        -  public String getNfc_naming_code() {
        -    return nfc_naming_code;
        -  }
        -
        -  public void setNfc_naming_code(String nfc_naming_code) {
        -    this.nfc_naming_code = nfc_naming_code;
        -  }
        -
        -  public Object getNetwork_role() {
        -    return network_role;
        -  }
        -
        -  public void setNetwork_role(Object network_role) {
        -    this.network_role = network_role;
        -  }
        -
        -  public Object getPps_capacity() {
        -    return pps_capacity;
        -  }
        -
        -  public void setPps_capacity(String pps_capacity) {
        -    this.pps_capacity = pps_capacity;
        -  }
        -
        -  public boolean isEmpty() {
        -    return Objects.isNull(nf_type)
        -        && Objects.isNull(nfc_type)
        -        && Objects.isNull(nf_naming_code)
        -        && Objects.isNull(nfc_naming_code)
        -        && Objects.isNull(network_role)
        -        && Objects.isNull(pps_capacity);
        -  }
        +
        +    private String nf_type;
        +    private String nfc_type;
        +    private String nf_naming_code;
        +    private String nfc_naming_code;
        +    //Keeping below attributes as objects to accomodate for tosca functions for property
        +
        +    // values like get_input, get_attribute
        +    private Object network_role;
        +    private Object pps_capacity;
        +
        +    public PortMirroringConnectionPointDescription() {
        +        //Populating empty strings as default values to be populated in tosca
        +        nf_type = "";
        +        nfc_type = "";
        +        nf_naming_code = "";
        +        nfc_naming_code = "";
        +        network_role = "";
        +        pps_capacity = "";
        +    }
        +
        +    public String getNf_type() {
        +        return nf_type;
        +    }
        +
        +    public void setNf_type(String nf_type) {
        +        this.nf_type = nf_type;
        +    }
        +
        +    public String getNfc_type() {
        +        return nfc_type;
        +    }
        +
        +    public void setNfc_type(String nfc_type) {
        +        this.nfc_type = nfc_type;
        +    }
        +
        +    public String getNf_naming_code() {
        +        return nf_naming_code;
        +    }
        +
        +    public void setNf_naming_code(String nf_naming_code) {
        +        this.nf_naming_code = nf_naming_code;
        +    }
        +
        +    public String getNfc_naming_code() {
        +        return nfc_naming_code;
        +    }
        +
        +    public void setNfc_naming_code(String nfc_naming_code) {
        +        this.nfc_naming_code = nfc_naming_code;
        +    }
        +
        +    public Object getNetwork_role() {
        +        return network_role;
        +    }
        +
        +    public void setNetwork_role(Object network_role) {
        +        this.network_role = network_role;
        +    }
        +
        +    public Object getPps_capacity() {
        +        return pps_capacity;
        +    }
        +
        +    public void setPps_capacity(String pps_capacity) {
        +        this.pps_capacity = pps_capacity;
        +    }
        +
        +    public boolean isEmpty() {
        +        return Objects.isNull(nf_type) && Objects.isNull(nfc_type) && Objects.isNull(nf_naming_code) && Objects.isNull(nfc_naming_code) && Objects
        +            .isNull(network_role) && Objects.isNull(pps_capacity);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/util/EnrichmentConstants.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/util/EnrichmentConstants.java
        index 18d28afb07..2f83b573e1 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/util/EnrichmentConstants.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/util/EnrichmentConstants.java
        @@ -13,22 +13,19 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.enrichment.impl.util;
         
         public class EnrichmentConstants {
         
        -  public static final String NFC_NAMING_CODE = "nfc_naming_code";
        -  public static final String MANDATORY = "mandatory";
        -  public static final String HIGH_AVAIL_MODE = "high_availablity";
        -  public static final String MIN_INSTANCES = "min_instances";
        -  public static final String MAX_INSTANCES = "max_instances";
        -  public static final String VM_TYPE_TAG = "vm_type_tag";
        -  public static final String VFC_CODE = "nfc_code";
        -  public static final String NFC_FUNCTION = "nfc_function";
        -
        -  private EnrichmentConstants() {
        -
        -  }
        +    public static final String NFC_NAMING_CODE = "nfc_naming_code";
        +    public static final String MANDATORY = "mandatory";
        +    public static final String HIGH_AVAIL_MODE = "high_availablity";
        +    public static final String MIN_INSTANCES = "min_instances";
        +    public static final String MAX_INSTANCES = "max_instances";
        +    public static final String VM_TYPE_TAG = "vm_type_tag";
        +    public static final String VFC_CODE = "nfc_code";
        +    public static final String NFC_FUNCTION = "nfc_function";
         
        +    private EnrichmentConstants() {
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/Enricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/Enricher.java
        index cc3a0d5186..f331da7863 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/Enricher.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/Enricher.java
        @@ -17,22 +17,18 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.inter;
         
        -
        +import java.util.List;
        +import java.util.Map;
         import lombok.Setter;
         import org.openecomp.sdc.datatypes.error.ErrorMessage;
         import org.openecomp.sdc.datatypes.model.AsdcModel;
         import org.openecomp.sdc.enrichment.EnrichmentInfo;
         
        -import java.util.List;
        -import java.util.Map;
        -
         @Setter
         public abstract class Enricher {
         
        -
             protected EnrichmentInfo data;
             protected AsdcModel model;
         
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/EnricherHandler.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/EnricherHandler.java
        index f0ffa0b1ad..cff0293a5a 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/EnricherHandler.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/EnricherHandler.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,7 +17,6 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.inter;
         
         import java.util.List;
        @@ -25,5 +24,4 @@ import java.util.List;
         public interface EnricherHandler {
         
             List getEnrichers();
        -
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java
        index dd1f13d034..8d77317a31 100644
        --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java
        +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java
        @@ -7,9 +7,9 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        @@ -17,22 +17,19 @@
          * limitations under the License.
          * ============LICENSE_END=========================================================
          */
        -
         package org.openecomp.sdc.enrichment.inter;
         
        -
        -import org.openecomp.sdc.datatypes.error.ErrorMessage;
        -import org.openecomp.sdc.enrichment.EnrichmentInfo;
        -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
        -
         import java.io.IOException;
         import java.util.List;
         import java.util.Map;
        +import org.openecomp.sdc.datatypes.error.ErrorMessage;
        +import org.openecomp.sdc.enrichment.EnrichmentInfo;
        +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
         
         /**
          * Created by Talio on 11/24/2016.
          */
         public interface ExternalArtifactEnricherInterface {
        -  Map> enrich(EnrichmentInfo enrichmentInfo,
        -                                         ToscaServiceModel serviceModel) throws IOException;
        +
        +    Map> enrich(EnrichmentInfo enrichmentInfo, ToscaServiceModel serviceModel) throws IOException;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ClientConfiguration.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ClientConfiguration.java
        index 9269e8bf22..285a5782cd 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ClientConfiguration.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ClientConfiguration.java
        @@ -13,17 +13,15 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.externaltesting.api;
         
         import lombok.Data;
         
         @Data
         public class ClientConfiguration {
        -  /**
        -   * Enable/disable state for the feature.  Client can use this
        -   * to show/hide menu items.
        -   */
        -  private boolean enabled;
         
        +    /**
        +     * Enable/disable state for the feature.  Client can use this to show/hide menu items.
        +     */
        +    private boolean enabled;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ExternalTestingManager.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ExternalTestingManager.java
        index 21d09edc91..0cbaf41583 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ExternalTestingManager.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/ExternalTestingManager.java
        @@ -23,8 +23,7 @@ import java.util.Map;
         public interface ExternalTestingManager {
         
             /**
        -     * Return the configuration of this feature that we want to
        -     * expose to the client.  Treated as a JSON blob for flexibility.
        +     * Return the configuration of this feature that we want to expose to the client.  Treated as a JSON blob for flexibility.
              */
             ClientConfiguration getConfig();
         
        @@ -34,8 +33,7 @@ public interface ExternalTestingManager {
             ClientConfiguration setConfig(ClientConfiguration config);
         
             /**
        -     * Build a tree of all test cases for the client including all
        -     * defined endpoints, scenarios, and test suites.
        +     * Build a tree of all test cases for the client including all defined endpoints, scenarios, and test suites.
              *
              * @return test case tree.
              */
        @@ -48,8 +46,7 @@ public interface ExternalTestingManager {
         
         
             /**
        -     * For functional testing purposes, allow the endpoint configuration
        -     * to be provisioned to the BE.
        +     * For functional testing purposes, allow the endpoint configuration to be provisioned to the BE.
              */
             List setEndpoints(List endpoints);
         
        @@ -84,8 +81,7 @@ public interface ExternalTestingManager {
             VtpTestCase getTestCase(String endpoint, String scenario, String testSuite, String testCaseName);
         
             /**
        -     * Execute a collection of tests where the manager must distribute
        -     * the tests to the appropriate endpoint and correlate the responses.
        +     * Execute a collection of tests where the manager must distribute the tests to the appropriate endpoint and correlate the responses.
              *
              * @param requests     collection of request items.
              * @param requestId    optional request ID provided from client.
        @@ -96,7 +92,7 @@ public interface ExternalTestingManager {
              */
         
             List execute(List requests, String vspId, String vspVersionId,
        -            String requestId, Map fileMap);
        +                                           String requestId, Map fileMap);
         
         
             /**
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/RemoteTestingEndpointDefinition.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/RemoteTestingEndpointDefinition.java
        index 0d5c30d593..22ebe9b465 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/RemoteTestingEndpointDefinition.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/RemoteTestingEndpointDefinition.java
        @@ -17,30 +17,30 @@
         package org.openecomp.core.externaltesting.api;
         
         import com.fasterxml.jackson.annotation.JsonIgnore;
        -import lombok.Data;
        -
         import java.util.regex.Pattern;
        +import lombok.Data;
         
         @Data
         public class RemoteTestingEndpointDefinition {
        -  private boolean enabled;
        -  private String title;
        -  private String url;
        -  private String id;
        -  private String apiKey;
        -  private String scenarioFilter;
         
        -  // a compact way to specify and endpoint to ease docker configuration.
        -  @JsonIgnore
        -  private String config;
        +    private boolean enabled;
        +    private String title;
        +    private String url;
        +    private String id;
        +    private String apiKey;
        +    private String scenarioFilter;
        +
        +    // a compact way to specify and endpoint to ease docker configuration.
        +    @JsonIgnore
        +    private String config;
         
        -  private Pattern scenarioFilterPattern;
        +    private Pattern scenarioFilterPattern;
         
        -  @JsonIgnore
        -  public Pattern getScenarioFilterPattern() {
        -    if ((scenarioFilterPattern == null) && (scenarioFilter != null)) {
        -      scenarioFilterPattern = Pattern.compile(scenarioFilter);
        +    @JsonIgnore
        +    public Pattern getScenarioFilterPattern() {
        +        if ((scenarioFilterPattern == null) && (scenarioFilter != null)) {
        +            scenarioFilterPattern = Pattern.compile(scenarioFilter);
        +        }
        +        return scenarioFilterPattern;
             }
        -    return scenarioFilterPattern;
        -  }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestErrorBody.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestErrorBody.java
        index d721f8997a..aa4d63c475 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestErrorBody.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestErrorBody.java
        @@ -18,9 +18,8 @@ package org.openecomp.core.externaltesting.api;
         
         import com.fasterxml.jackson.annotation.JsonInclude;
         import io.swagger.v3.oas.annotations.media.Schema;
        -import lombok.Data;
        -
         import java.io.Serializable;
        +import lombok.Data;
         
         /**
          * Error body to return to client per IETF RFC 7807.
        @@ -31,20 +30,20 @@ import java.io.Serializable;
         @Data
         public class TestErrorBody implements Serializable {
         
        -  private static final long serialVersionUID = 3504501412736665763L;
        +    private static final long serialVersionUID = 3504501412736665763L;
         
        -  private String code;
        -  private Integer httpStatus;
        -  private String message;
        +    private String code;
        +    private Integer httpStatus;
        +    private String message;
         
        -  TestErrorBody() {
        +    TestErrorBody() {
         
        -  }
        +    }
         
        -  public TestErrorBody(String code, Integer httpStatus, String message) {
        -    this();
        -    this.code = code;
        -    this.httpStatus = httpStatus;
        -    this.message = message;
        -  }
        +    public TestErrorBody(String code, Integer httpStatus, String message) {
        +        this();
        +        this.code = code;
        +        this.httpStatus = httpStatus;
        +        this.message = message;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestTreeNode.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestTreeNode.java
        index 1b75772476..4965abffcd 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestTreeNode.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/TestTreeNode.java
        @@ -17,34 +17,31 @@
         package org.openecomp.core.externaltesting.api;
         
         import com.fasterxml.jackson.annotation.JsonInclude;
        +import java.util.List;
         import lombok.Data;
         import lombok.EqualsAndHashCode;
         
        -import java.util.ArrayList;
        -import java.util.List;
        -
         /**
        - * Tree structure of tests.   VTP does not provide an organized
        - * tree of tests.  Here we define a tree node with tests and
        - * child nodes to represent our tree.
        + * Tree structure of tests.   VTP does not provide an organized tree of tests.  Here we define a tree node with tests and child nodes to represent our
        + * tree.
          */
         @SuppressWarnings("unused")
         @JsonInclude(JsonInclude.Include.NON_EMPTY)
         @Data()
        -@EqualsAndHashCode(callSuper=true)
        +@EqualsAndHashCode(callSuper = true)
         public class TestTreeNode extends VtpNameDescriptionPair {
         
        -  @JsonInclude(JsonInclude.Include.NON_EMPTY)
        -  private List tests;
        +    @JsonInclude(JsonInclude.Include.NON_EMPTY)
        +    private List tests;
         
        -  @JsonInclude(JsonInclude.Include.NON_EMPTY)
        -  private List children;
        +    @JsonInclude(JsonInclude.Include.NON_EMPTY)
        +    private List children;
         
        -  public TestTreeNode() {
        -    super();
        -  }
        +    public TestTreeNode() {
        +        super();
        +    }
         
        -  public TestTreeNode(String name, String description) {
        -    super(name, description);
        -  }
        +    public TestTreeNode(String name, String description) {
        +        super(name, description);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpNameDescriptionPair.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpNameDescriptionPair.java
        index 9a435de4ae..c34d4d4aea 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpNameDescriptionPair.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpNameDescriptionPair.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.core.externaltesting.api;
         
         import lombok.Data;
        @@ -23,16 +22,16 @@ import lombok.Data;
          */
         @Data
         public class VtpNameDescriptionPair {
        -  private String name;
        -  private String description;
         
        -  VtpNameDescriptionPair() {
        +    private String name;
        +    private String description;
         
        -  }
        +    VtpNameDescriptionPair() {
        +    }
         
        -  public VtpNameDescriptionPair(String name, String description) {
        -    this();
        -    this.name = name;
        -    this.description = description;
        -  }
        +    public VtpNameDescriptionPair(String name, String description) {
        +        this();
        +        this.name = name;
        +        this.description = description;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCase.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCase.java
        index ae39159f32..d8a81ae9fe 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCase.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCase.java
        @@ -16,27 +16,25 @@
         
         package org.openecomp.core.externaltesting.api;
         
        -import lombok.Data;
        -
         import java.util.List;
        +import lombok.Data;
         
         
         @Data
         public class VtpTestCase {
         
        -  private String scenario;
        -  private String testCaseName;
        -  private String testSuiteName;
        -  private String description;
        -  private String author;
        -  private List inputs;
        -  private List outputs;
        -
        -  /**
        -   * Extends VTP test case content with location where test case is defined.
        -   * This value is populated by the SDC-BE for consumption by the front end.
        -   * This allows the front end to tell the back end where to run the test.
        -   */
        -  private String endpoint;
        +    private String scenario;
        +    private String testCaseName;
        +    private String testSuiteName;
        +    private String description;
        +    private String author;
        +    private List inputs;
        +    private List outputs;
        +
        +    /**
        +     * Extends VTP test case content with location where test case is defined. This value is populated by the SDC-BE for consumption by the front end.
        +     * This allows the front end to tell the back end where to run the test.
        +     */
        +    private String endpoint;
         
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseInput.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseInput.java
        index 5c6db8eb72..19d6303f39 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseInput.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseInput.java
        @@ -16,27 +16,25 @@
         
         package org.openecomp.core.externaltesting.api;
         
        +import java.util.Map;
         import lombok.Data;
         import lombok.EqualsAndHashCode;
         
        -import java.util.Map;
        -
         
         @Data
        -@EqualsAndHashCode(callSuper=true)
        +@EqualsAndHashCode(callSuper = true)
         public class VtpTestCaseInput extends VtpNameDescriptionPair {
         
        -  private String type;
        -  private String defaultValue;
        -  private boolean isOptional;
        -  private Map metadata;
        +    private String type;
        +    private String defaultValue;
        +    private boolean isOptional;
        +    private Map metadata;
         
        -  /**
        -   * The VTP API has a field called isOptional, not just optional so
        -   * we need to add getter and setter.
        -   */
        -  @SuppressWarnings({"unused", "WeakerAccess"})
        -  public boolean getIsOptional() {
        -    return isOptional;
        -  }
        +    /**
        +     * The VTP API has a field called isOptional, not just optional so we need to add getter and setter.
        +     */
        +    @SuppressWarnings({"unused", "WeakerAccess"})
        +    public boolean getIsOptional() {
        +        return isOptional;
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseOutput.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseOutput.java
        index 7d4ae84544..b3781b3978 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseOutput.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestCaseOutput.java
        @@ -24,8 +24,8 @@ import lombok.EqualsAndHashCode;
         @JsonInclude(JsonInclude.Include.NON_NULL)
         @Schema(description = "VtpTestSuite")
         @Data
        -@EqualsAndHashCode(callSuper=true)
        +@EqualsAndHashCode(callSuper = true)
         class VtpTestCaseOutput extends VtpNameDescriptionPair {
         
        -  private String type;
        +    private String type;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionRequest.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionRequest.java
        index 481fd46906..59f3b7d566 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionRequest.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionRequest.java
        @@ -17,23 +17,22 @@
         package org.openecomp.core.externaltesting.api;
         
         import com.fasterxml.jackson.annotation.JsonInclude;
        -import lombok.Data;
        -
         import java.util.Map;
        +import lombok.Data;
         
         @Data
         public class VtpTestExecutionRequest {
         
        -  private String scenario;
        -  private String testSuiteName;
        -  private String testCaseName;
        +    private String scenario;
        +    private String testSuiteName;
        +    private String testCaseName;
         
        -  @JsonInclude(value = JsonInclude.Include.NON_NULL)
        -  private String profile;
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private String profile;
         
        -  @JsonInclude(value = JsonInclude.Include.NON_NULL)
        -  private Map parameters;
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private Map parameters;
         
        -  @JsonInclude(value = JsonInclude.Include.NON_NULL)
        -  private String endpoint;
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private String endpoint;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionResponse.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionResponse.java
        index add85210cb..c9756469ce 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionResponse.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/api/VtpTestExecutionResponse.java
        @@ -17,37 +17,37 @@
         package org.openecomp.core.externaltesting.api;
         
         import com.fasterxml.jackson.annotation.JsonInclude;
        -import lombok.Data;
        -
         import java.util.Map;
        +import lombok.Data;
         
         @Data
         public class VtpTestExecutionResponse {
        -  private String scenario;
        -  private String testCaseName;
        -  private String testSuiteName;
        -  private String executionId;
        -  private Map parameters;
        -  private Object results;
        -  private String status;
        -  private String startTime; // don't bother to convert various ISO8601 formats.
        -  private String endTime;   // don't bother to convert various ISO8601 formats.
         
        -  /**
        -   * In the event on an error, code provided.
        -   */
        -  @JsonInclude(value= JsonInclude.Include.NON_NULL)
        -  private String code;
        +    private String scenario;
        +    private String testCaseName;
        +    private String testSuiteName;
        +    private String executionId;
        +    private Map parameters;
        +    private Object results;
        +    private String status;
        +    private String startTime; // don't bother to convert various ISO8601 formats.
        +    private String endTime;   // don't bother to convert various ISO8601 formats.
        +
        +    /**
        +     * In the event on an error, code provided.
        +     */
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private String code;
         
        -  /**
        -   * Error message
        -   */
        -  @JsonInclude(value= JsonInclude.Include.NON_NULL)
        -  private String message;
        +    /**
        +     * Error message
        +     */
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private String message;
         
        -  /**
        -   * In the event of an unexpected status.
        -   */
        -  @JsonInclude(value= JsonInclude.Include.NON_NULL)
        -  private Integer httpStatus;
        +    /**
        +     * In the event of an unexpected status.
        +     */
        +    @JsonInclude(value = JsonInclude.Include.NON_NULL)
        +    private Integer httpStatus;
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingException.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingException.java
        index 3df64a40eb..731cf4ae54 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingException.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingException.java
        @@ -21,31 +21,31 @@ import lombok.EqualsAndHashCode;
         import org.apache.commons.lang3.builder.ToStringBuilder;
         
         @Data
        -@EqualsAndHashCode(callSuper=false)
        +@EqualsAndHashCode(callSuper = false)
         public class ExternalTestingException extends RuntimeException {
         
        -  private static final long serialVersionUID = -4357810130868566088L;
        -
        -  private final String messageCode;
        -  private final int httpStatus;
        -  private final String detail;
        -
        -  public ExternalTestingException(String messageCode, int httpStatus, String detail) {
        -    super(messageCode);
        -    this.messageCode = messageCode;
        -    this.httpStatus = httpStatus;
        -    this.detail = detail;
        -  }
        -
        -  public ExternalTestingException(String messageCode, int httpStatus, String detail, Throwable parent) {
        -    super(messageCode, parent);
        -    this.messageCode = messageCode;
        -    this.httpStatus = httpStatus;
        -    this.detail = detail;
        -  }
        -
        -  @Override
        -  public String toString() {
        -    return ToStringBuilder.reflectionToString(this);
        -  }
        +    private static final long serialVersionUID = -4357810130868566088L;
        +
        +    private final String messageCode;
        +    private final int httpStatus;
        +    private final String detail;
        +
        +    public ExternalTestingException(String messageCode, int httpStatus, String detail) {
        +        super(messageCode);
        +        this.messageCode = messageCode;
        +        this.httpStatus = httpStatus;
        +        this.detail = detail;
        +    }
        +
        +    public ExternalTestingException(String messageCode, int httpStatus, String detail, Throwable parent) {
        +        super(messageCode, parent);
        +        this.messageCode = messageCode;
        +        this.httpStatus = httpStatus;
        +        this.detail = detail;
        +    }
        +
        +    @Override
        +    public String toString() {
        +        return ToStringBuilder.reflectionToString(this);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingInitializationException.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingInitializationException.java
        index 28f40199ca..a54409b1a8 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingInitializationException.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/errors/ExternalTestingInitializationException.java
        @@ -21,13 +21,13 @@ import java.io.IOException;
         @SuppressWarnings("unused")
         public class ExternalTestingInitializationException extends IOException {
         
        -  private static final long serialVersionUID = -2422448175010311433L;
        +    private static final long serialVersionUID = -2422448175010311433L;
         
        -  public ExternalTestingInitializationException(String message) {
        -    super(message);
        -  }
        +    public ExternalTestingInitializationException(String message) {
        +        super(message);
        +    }
         
        -  public ExternalTestingInitializationException(String message, Throwable cause) {
        -    super(message, cause);
        -  }
        +    public ExternalTestingInitializationException(String message, Throwable cause) {
        +        super(message, cause);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/factory/ExternalTestingManagerFactory.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/factory/ExternalTestingManagerFactory.java
        index e84a4c86a1..05547799cc 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/factory/ExternalTestingManagerFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-api/src/main/java/org/openecomp/core/externaltesting/factory/ExternalTestingManagerFactory.java
        @@ -16,15 +16,15 @@
         
         package org.openecomp.core.externaltesting.factory;
         
        +import org.openecomp.core.externaltesting.api.ExternalTestingManager;
         import org.openecomp.core.factory.api.AbstractComponentFactory;
         import org.openecomp.core.factory.api.AbstractFactory;
        -import org.openecomp.core.externaltesting.api.ExternalTestingManager;
         
         
         @SuppressWarnings("unused")
         public abstract class ExternalTestingManagerFactory extends AbstractComponentFactory {
         
        -  public static ExternalTestingManagerFactory getInstance() {
        -    return AbstractFactory.getInstance(ExternalTestingManagerFactory.class);
        -  }
        +    public static ExternalTestingManagerFactory getInstance() {
        +        return AbstractFactory.getInstance(ExternalTestingManagerFactory.class);
        +    }
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/ExternalTestingManagerImpl.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/ExternalTestingManagerImpl.java
        index dfabf31568..f115a98e5b 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/ExternalTestingManagerImpl.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/ExternalTestingManagerImpl.java
        @@ -75,8 +75,8 @@ import org.springframework.web.util.UriComponentsBuilder;
         
         public class ExternalTestingManagerImpl implements ExternalTestingManager {
         
        -    private Logger logger = LoggerFactory.getLogger(ExternalTestingManagerImpl.class);
        -
        +    static final String VSP_ID = "vspId";
        +    static final String VSP_VERSION = "vspVersion";
             private static final String FILE_URL_PREFIX = "file://";
             private static final String HTTP_STATUS = "httpStatus";
             private static final String CODE = "code";
        @@ -84,7 +84,6 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             private static final String MESSAGE = "message";
             private static final String DETAIL = "detail";
             private static final String PATH = "path";
        -
             private static final String VTP_SCENARIOS_URI = "%s/v1/vtp/scenarios";
             private static final String VTP_TESTSUITE_URI = "%s/v1/vtp/scenarios/%s/testsuites";
             private static final String VTP_TESTCASES_URI = "%s/v1/vtp/scenarios/%s/testcases";
        @@ -92,23 +91,15 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             private static final String VTP_EXECUTIONS_URI = "%s/v1/vtp/executions";
             private static final String VTP_EXECUTION_URI = "%s/v1/vtp/executions/%s";
             private static final String VTP_EXECUTION_ID_URL = "%s/v1/vtp/executions?requestId=%s";
        -
        -
             private static final String INVALIDATE_STATE_ERROR_CODE = "SDC-TEST-001";
             private static final String NO_ACCESS_CONFIGURATION_DEFINED = "No access configuration defined";
        -
             private static final String NO_SUCH_ENDPOINT_ERROR_CODE = "SDC-TEST-002";
             private static final String ENDPOINT_ERROR_CODE = "SDC-TEST-003";
             private static final String TESTING_HTTP_ERROR_CODE = "SDC-TEST-004";
             private static final String SDC_RESOLVER_ERR = "SDC-TEST-005";
        -
        -    static final String VSP_ID = "vspId";
        -    static final String VSP_VERSION = "vspVersion";
        -
             private static final String VSP_CSAR = "vsp";
             private static final String VSP_HEAT = "vsp-zip";
        -
        -
        +    private Logger logger = LoggerFactory.getLogger(ExternalTestingManagerImpl.class);
             private VersioningManager versioningManager;
             private VendorSoftwareProductManager vendorSoftwareProductManager;
             private OrchestrationTemplateCandidateManager candidateManager;
        @@ -123,8 +114,8 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             ExternalTestingManagerImpl(VersioningManager versioningManager,
        -            VendorSoftwareProductManager vendorSoftwareProductManager,
        -            OrchestrationTemplateCandidateManager candidateManager) {
        +                               VendorSoftwareProductManager vendorSoftwareProductManager,
        +                               OrchestrationTemplateCandidateManager candidateManager) {
                 this();
                 this.versioningManager = versioningManager;
                 this.vendorSoftwareProductManager = vendorSoftwareProductManager;
        @@ -132,8 +123,8 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * Read the configuration from the yaml file for this bean.  If we get an exception during load,
        -     * don't force an error starting SDC but log a warning.  Do no warm...
        +     * Read the configuration from the yaml file for this bean.  If we get an exception during load, don't force an error starting SDC but log a
        +     * warning.  Do no warm...
              */
             @PostConstruct
             public void init() {
        @@ -173,9 +164,8 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * Load the configuration for this component.  When the SDC onboarding backend
        -     * runs, it gets a system property called config.location.  We can use that
        -     * to locate the config-externaltesting.yaml file.
        +     * Load the configuration for this component.  When the SDC onboarding backend runs, it gets a system property called config.location.  We can use
        +     * that to locate the config-externaltesting.yaml file.
              */
             private void loadConfig() {
                 String loc = System.getProperty("config.location");
        @@ -190,7 +180,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                     }
         
                     endpoints =
        -                    accessConfig.getEndpoints().stream().flatMap(this::mapEndpointString).collect(Collectors.toList());
        +                accessConfig.getEndpoints().stream().flatMap(this::mapEndpointString).collect(Collectors.toList());
         
                     if (logger.isInfoEnabled()) {
                         String s = new ObjectMapper().writeValueAsString(endpoints);
        @@ -207,8 +197,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * Return the configuration of this feature that we want to
        -     * expose to the client.  Treated as a JSON blob for flexibility.
        +     * Return the configuration of this feature that we want to expose to the client.  Treated as a JSON blob for flexibility.
              */
             @Override
             public ClientConfiguration getConfig() {
        @@ -224,9 +213,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * To allow for functional testing, we let a caller invoke
        -     * a setConfig request to enable/disable the client.  This
        -     * new value is not persisted.
        +     * To allow for functional testing, we let a caller invoke a setConfig request to enable/disable the client.  This new value is not persisted.
              *
              * @return new client configuration
              */
        @@ -240,8 +227,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * To allow for functional testing, we let a caller invoke
        -     * a setEndpoints request to configure where the BE makes request to.
        +     * To allow for functional testing, we let a caller invoke a setEndpoints request to configure where the BE makes request to.
              *
              * @return new endpoint definitions.
              */
        @@ -273,14 +259,14 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                 try {
                     logger.debug("process endpoint {}", ep.getId());
                     getScenarios(ep.getId()).stream()
        -                    .filter(s -> ((ep.getScenarioFilter() == null) || ep.getScenarioFilterPattern().matcher(s.getName())
        -                                                                              .matches())).forEach(s -> {
        +                .filter(s -> ((ep.getScenarioFilter() == null) || ep.getScenarioFilterPattern().matcher(s.getName())
        +                    .matches())).forEach(s -> {
                         addScenarioToTree(root, s);
                         getTestSuites(ep.getId(), s.getName()).forEach(suite -> addSuiteToTree(root, s, suite));
                         getTestCases(ep.getId(), s.getName()).forEach(tc -> {
                             try {
                                 VtpTestCase details =
        -                                getTestCase(ep.getId(), s.getName(), tc.getTestSuiteName(), tc.getTestCaseName());
        +                            getTestCase(ep.getId(), s.getName(), tc.getTestSuiteName(), tc.getTestCaseName());
                                 addTestCaseToTree(root, ep.getId(), s.getName(), tc.getTestSuiteName(), details);
                             } catch (@SuppressWarnings("squid:S1166") ExternalTestingException ex) {
                                 // Not logging stack trace on purpose.  VTP was throwing exceptions for certain test cases.
        @@ -310,19 +296,19 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * @param tc            test case to add.
              */
             private void addTestCaseToTree(TestTreeNode root, String endpointName, String scenarioName, String testSuiteName,
        -            VtpTestCase tc) {
        +                                   VtpTestCase tc) {
                 // return quickly.
                 if (tc == null) {
                     return;
                 }
                 findNamedChild(root, scenarioName)
        -                .ifPresent(scenarioNode -> findNamedChild(scenarioNode, testSuiteName).ifPresent(suiteNode -> {
        -                    massageTestCaseForUI(tc, endpointName, scenarioName);
        -                    if (suiteNode.getTests() == null) {
        -                        suiteNode.setTests(new ArrayList<>());
        -                    }
        -                    suiteNode.getTests().add(tc);
        -                }));
        +            .ifPresent(scenarioNode -> findNamedChild(scenarioNode, testSuiteName).ifPresent(suiteNode -> {
        +                massageTestCaseForUI(tc, endpointName, scenarioName);
        +                if (suiteNode.getTests() == null) {
        +                    suiteNode.setTests(new ArrayList<>());
        +                }
        +                suiteNode.getTests().add(tc);
        +            }));
             }
         
             private void massageTestCaseForUI(VtpTestCase testcase, String endpoint, String scenario) {
        @@ -341,7 +327,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * @param suite    test suite to add.
              */
             private void addSuiteToTree(final TestTreeNode root, final VtpNameDescriptionPair scenario,
        -            final VtpNameDescriptionPair suite) {
        +                                final VtpNameDescriptionPair suite) {
                 findNamedChild(root, scenario.getName()).ifPresent(parent -> {
                     if (parent.getChildren() == null) {
                         parent.setChildren(new ArrayList<>());
        @@ -387,7 +373,8 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              */
             private List returnNameDescriptionPairFromUrl(String url) {
                 ParameterizedTypeReference> t =
        -                new ParameterizedTypeReference>() { };
        +            new ParameterizedTypeReference>() {
        +            };
                 List rv = proxyGetRequestToExternalTestingSite(url, t);
                 if (rv == null) {
                     rv = new ArrayList<>();
        @@ -407,18 +394,19 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * Get the list of test suites for an endpoint for the given scenario.
              */
             public List getTestSuites(final String endpoint, final String scenario) {
        -        String url = buildEndpointUrl(VTP_TESTSUITE_URI, endpoint, new String[] {scenario});
        +        String url = buildEndpointUrl(VTP_TESTSUITE_URI, endpoint, new String[]{scenario});
                 return returnNameDescriptionPairFromUrl(url);
             }
         
             /**
        -     * Get the list of test cases under a scenario.  This is the VTP API.  It would
        -     * seem better to get the list of cases under a test suite but that is not supported.
        +     * Get the list of test cases under a scenario.  This is the VTP API.  It would seem better to get the list of cases under a test suite but that
        +     * is not supported.
              */
             @Override
             public List getTestCases(String endpoint, String scenario) {
        -        String url = buildEndpointUrl(VTP_TESTCASES_URI, endpoint, new String[] {scenario});
        -        ParameterizedTypeReference> t = new ParameterizedTypeReference>() { };
        +        String url = buildEndpointUrl(VTP_TESTCASES_URI, endpoint, new String[]{scenario});
        +        ParameterizedTypeReference> t = new ParameterizedTypeReference>() {
        +        };
                 List rv = proxyGetRequestToExternalTestingSite(url, t);
                 if (rv == null) {
                     rv = new ArrayList<>();
        @@ -431,8 +419,9 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              */
             @Override
             public VtpTestCase getTestCase(String endpoint, String scenario, String testSuite, String testCaseName) {
        -        String url = buildEndpointUrl(VTP_TESTCASE_URI, endpoint, new String[] {scenario, testSuite, testCaseName});
        -        ParameterizedTypeReference t = new ParameterizedTypeReference() { };
        +        String url = buildEndpointUrl(VTP_TESTCASE_URI, endpoint, new String[]{scenario, testSuite, testCaseName});
        +        ParameterizedTypeReference t = new ParameterizedTypeReference() {
        +        };
                 return proxyGetRequestToExternalTestingSite(url, t);
             }
         
        @@ -445,9 +434,10 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              */
             @Override
             public VtpTestExecutionResponse getExecution(String endpoint, String executionId) {
        -        String url = buildEndpointUrl(VTP_EXECUTION_URI, endpoint, new String[] {executionId});
        +        String url = buildEndpointUrl(VTP_EXECUTION_URI, endpoint, new String[]{executionId});
                 ParameterizedTypeReference t =
        -                new ParameterizedTypeReference() { };
        +            new ParameterizedTypeReference() {
        +            };
                 return proxyGetRequestToExternalTestingSite(url, t);
             }
         
        @@ -461,19 +451,19 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
         
             @Override
             public List execute(final List testsToRun, String vspId,
        -            String vspVersionId, String requestId, Map fileMap) {
        +                                                  String vspVersionId, String requestId, Map fileMap) {
                 if (endpoints == null) {
                     throw new ExternalTestingException(INVALIDATE_STATE_ERROR_CODE, 500, NO_ACCESS_CONFIGURATION_DEFINED);
                 }
         
                 // partition the requests by endpoint.
                 Map> partitions =
        -                testsToRun.stream().collect(Collectors.groupingBy(VtpTestExecutionRequest::getEndpoint));
        +            testsToRun.stream().collect(Collectors.groupingBy(VtpTestExecutionRequest::getEndpoint));
         
                 // process each group and collect the results.
                 return partitions.entrySet().stream().flatMap(
        -                e -> doExecute(e.getKey(), e.getValue(), vspId, vspVersionId, requestId, fileMap).stream())
        -                       .collect(Collectors.toList());
        +            e -> doExecute(e.getKey(), e.getValue(), vspId, vspVersionId, requestId, fileMap).stream())
        +            .collect(Collectors.toList());
             }
         
             /**
        @@ -481,9 +471,10 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              */
             @Override
             public List getExecutionIds(String endpoint, String requestId) {
        -        String url = buildEndpointUrl(VTP_EXECUTION_ID_URL, endpoint, new String[] {requestId});
        +        String url = buildEndpointUrl(VTP_EXECUTION_ID_URL, endpoint, new String[]{requestId});
                 ParameterizedTypeReference> t =
        -                new ParameterizedTypeReference>() { };
        +            new ParameterizedTypeReference>() {
        +            };
                 List rv = proxyGetRequestToExternalTestingSite(url, t);
                 if (rv == null) {
                     rv = new ArrayList<>();
        @@ -499,16 +490,17 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * @return list of execution responses.
              */
             private List doExecute(final String endpointName,
        -            final List testsToRun, String vspId, String vspVersionId, String requestId,
        -            Map fileMap) {
        +                                                     final List testsToRun, String vspId, String vspVersionId,
        +                                                     String requestId,
        +                                                     Map fileMap) {
                 if (endpoints == null) {
                     throw new ExternalTestingException(INVALIDATE_STATE_ERROR_CODE, 500, NO_ACCESS_CONFIGURATION_DEFINED);
                 }
         
                 RemoteTestingEndpointDefinition endpoint =
        -                endpoints.stream().filter(e -> StringUtils.equals(endpointName, e.getId())).findFirst().orElseThrow(
        -                        () -> new ExternalTestingException(NO_SUCH_ENDPOINT_ERROR_CODE, 400,
        -                                "No endpoint named " + endpointName + " is defined"));
        +            endpoints.stream().filter(e -> StringUtils.equals(endpointName, e.getId())).findFirst().orElseThrow(
        +                () -> new ExternalTestingException(NO_SUCH_ENDPOINT_ERROR_CODE, 400,
        +                    "No endpoint named " + endpointName + " is defined"));
         
                 // if the endpoint requires an API key, specify it in the headers.
                 HttpHeaders headers = new HttpHeaders();
        @@ -520,12 +512,11 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                 // build the body.
                 MultiValueMap body = new LinkedMultiValueMap<>();
         
        -
                 for (VtpTestExecutionRequest test : testsToRun) {
                     // it will true only noramal validation not for certification
                     if ((test.getParameters() != null) && (test.getParameters().containsKey(VSP_CSAR) || test.getParameters()
        -                                                                                                         .containsKey(
        -                                                                                                                 VSP_HEAT))) {
        +                .containsKey(
        +                    VSP_HEAT))) {
                         attachArchiveContent(test, body, vspId, vspVersionId);
                     }
         
        @@ -555,7 +546,8 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                     builder = builder.queryParam("requestId", requestId);
                 }
                 ParameterizedTypeReference> t =
        -                new ParameterizedTypeReference>() { };
        +            new ParameterizedTypeReference>() {
        +            };
                 try {
                     return proxyRequestToExternalTestingSite(builder.toUriString(), requestEntity, t);
                 } catch (ExternalTestingException ex) {
        @@ -582,9 +574,9 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             private String buildEndpointUrl(String format, String endpointName, String[] args) {
                 if (endpoints != null) {
                     RemoteTestingEndpointDefinition ep =
        -                    endpoints.stream().filter(e -> e.isEnabled() && e.getId().equals(endpointName)).findFirst()
        -                            .orElseThrow(() -> new ExternalTestingException(NO_SUCH_ENDPOINT_ERROR_CODE, 500,
        -                                    "No endpoint named " + endpointName + " is defined"));
        +                endpoints.stream().filter(e -> e.isEnabled() && e.getId().equals(endpointName)).findFirst()
        +                    .orElseThrow(() -> new ExternalTestingException(NO_SUCH_ENDPOINT_ERROR_CODE, 500,
        +                        "No endpoint named " + endpointName + " is defined"));
         
                     Object[] newArgs = ArrayUtils.add(args, 0, ep.getUrl());
                     return String.format(format, newArgs);
        @@ -614,7 +606,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * @return instance of expected type
              */
             private  T proxyRequestToExternalTestingSite(String url, HttpEntity request,
        -            ParameterizedTypeReference responseType) {
        +                                                       ParameterizedTypeReference responseType) {
                 if (request != null) {
                     logger.debug("POST request to {} with {} for {}", url, request, responseType.getType().getTypeName());
                 } else {
        @@ -636,9 +628,9 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                     // make my own exception out of this.
                     logger.warn("Unexpected HTTP Status from endpoint {}", ex.getRawStatusCode());
                     if ((ex.getResponseHeaders().getContentType() != null) && (
        -                    (ex.getResponseHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_JSON))
        -                            || (ex.getResponseHeaders().getContentType()
        -                                        .isCompatibleWith(MediaType.parseMediaType("application/problem+json"))))) {
        +                (ex.getResponseHeaders().getContentType().isCompatibleWith(MediaType.APPLICATION_JSON))
        +                    || (ex.getResponseHeaders().getContentType()
        +                    .isCompatibleWith(MediaType.parseMediaType("application/problem+json"))))) {
                         String s = ex.getResponseBodyAsString();
                         logger.warn("endpoint body content is {}", s);
                         try {
        @@ -647,11 +639,11 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                         } catch (JsonParseException e) {
                             logger.warn("unexpected JSON response", e);
                             throw new ExternalTestingException(ENDPOINT_ERROR_CODE, ex.getStatusCode().value(),
        -                            ex.getResponseBodyAsString(), ex);
        +                        ex.getResponseBodyAsString(), ex);
                         }
                     } else {
                         throw new ExternalTestingException(ENDPOINT_ERROR_CODE, ex.getStatusCode().value(),
        -                        ex.getResponseBodyAsString(), ex);
        +                    ex.getResponseBodyAsString(), ex);
                     }
                 } catch (ResourceAccessException ex) {
                     throw new ExternalTestingException(ENDPOINT_ERROR_CODE, 500, ex.getMessage(), ex);
        @@ -675,8 +667,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             /**
        -     * Errors from the endpoint could conform to the expected ETSI body or not.
        -     * Here we try to handle various response body elements.
        +     * Errors from the endpoint could conform to the expected ETSI body or not. Here we try to handle various response body elements.
              *
              * @param statusCode http status code in response.
              * @param o          JSON object parsed from the http response body
        @@ -713,7 +704,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             void attachArchiveContent(VtpTestExecutionRequest test, MultiValueMap body, String vspId,
        -            String vspVersionId) {
        +                              String vspVersionId) {
                 try {
                     extractMetadata(test, body, vspId, vspVersionId);
                 } catch (IOException ex) {
        @@ -729,7 +720,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
              * @param version     VSP version
              */
             private void extractMetadata(VtpTestExecutionRequest requestItem, MultiValueMap body, String vspId,
        -            String version) throws IOException {
        +                                 String version) throws IOException {
         
                 Version ver = new Version(version);
                 logger.debug("attempt to retrieve archive for VSP {} version {}", vspId, ver.getId());
        @@ -742,12 +733,12 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
                 if (!ozip.isPresent()) {
                     List versions = versioningManager.list(vspId);
                     String knownVersions = versions.stream()
        -                                           .map(v -> String.format("%d.%d: %s (%s)", v.getMajor(), v.getMinor(),
        -                                                   v.getStatus(), v.getId())).collect(Collectors.joining("\n"));
        +                .map(v -> String.format("%d.%d: %s (%s)", v.getMajor(), v.getMinor(),
        +                    v.getStatus(), v.getId())).collect(Collectors.joining("\n"));
         
                     String detail = String.format(
        -                    "Archive processing failed.  Unable to find archive for VSP ID %s and Version %s.  Known versions are:\n%s",
        -                    vspId, version, knownVersions);
        +                "Archive processing failed.  Unable to find archive for VSP ID %s and Version %s.  Known versions are:\n%s",
        +                vspId, version, knownVersions);
         
                     throw new ExternalTestingException(SDC_RESOLVER_ERR, 500, detail);
                 }
        @@ -758,8 +749,7 @@ public class ExternalTestingManagerImpl implements ExternalTestingManager {
             }
         
             private void processArchive(final VtpTestExecutionRequest test, final MultiValueMap body,
        -            final byte[] zip) {
        -
        +                                final byte[] zip) {
         
                 // VTP does not support concurrent executions of the same test with the same associated file name.
                 // It writes files to /tmp and if we were to send two requests with the same file, the results
        diff --git a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/TestingAccessConfig.java b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/TestingAccessConfig.java
        index b6bcb45516..ef5b2568eb 100644
        --- a/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/TestingAccessConfig.java
        +++ b/openecomp-be/lib/openecomp-sdc-externaltesting-lib/openecomp-sdc-externaltesting-impl/src/main/java/org/openecomp/core/externaltesting/impl/TestingAccessConfig.java
        @@ -16,16 +16,15 @@
         
         package org.openecomp.core.externaltesting.impl;
         
        +import java.util.List;
         import lombok.Data;
         import org.openecomp.core.externaltesting.api.ClientConfiguration;
         
        -import java.util.List;
        -
         @SuppressWarnings("WeakerAccess")
         @Data
         public class TestingAccessConfig {
         
        -  private ClientConfiguration client;
        -  private List endpoints;
        +    private ClientConfiguration client;
        +    private List endpoints;
         
         }
        diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java
        index e8635b2418..522ad28caf 100644
        --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java
        +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/LoggingConstants.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.logging;
         
         /**
        @@ -28,7 +27,6 @@ public class LoggingConstants {
              * Default HTTP header for propagation of a request ID for distributed tracing.
              */
             public static final String DEFAULT_REQUEST_ID_HEADER = "X-ECOMP-RequestID";
        -
             /**
              * Default HTTP header for exchanging a partner name between components.
              */
        diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java
        index 090f680aa7..8bf8852354 100644
        --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java
        +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/AuditData.java
        @@ -13,15 +13,14 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.logging.api;
         
        -import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
         import lombok.Getter;
        +import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
         
         /**
        - * Builder to populate audit data. This includes only data known to an application, and not otherwise available
        - * to the logging framework. As opposed, for example, to local runtime, host address, etc.
        + * Builder to populate audit data. This includes only data known to an application, and not otherwise available to the logging framework. As
        + * opposed, for example, to local runtime, host address, etc.
          *
          * @author KATYR, evitaliy
          * @since February 15, 2018
        @@ -30,7 +29,6 @@ import lombok.Getter;
         public class AuditData {
         
             // don't inherit from MetricsData because it has a very different meaning
        -
             private final long startTime;
             private final long endTime;
             private final ResponseStatus statusCode;
        @@ -47,17 +45,16 @@ public class AuditData {
                 this.clientIpAddress = builder.clientIpAddress;
             }
         
        -    @Override
        -    public String toString() {
        -        return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode
        -                + ", responseCode=" + responseCode + ", responseDescription=" + responseDescription
        -                + ", clientIpAddress=" + clientIpAddress + '}';
        -    }
        -
             public static AuditDataBuilder builder() {
                 return new AuditDataBuilder();
             }
         
        +    @Override
        +    public String toString() {
        +        return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode + ", responseCode=" + responseCode
        +            + ", responseDescription=" + responseDescription + ", clientIpAddress=" + clientIpAddress + '}';
        +    }
        +
             /**
              * Fluent API for building audit data.
              */
        @@ -95,8 +92,8 @@ public class AuditData {
                 }
         
                 /**
        -         * Indicate whether an invocation was successful. It is up the the application to decide if a particular result
        -         * must be treated as a success or a failure.
        +         * Indicate whether an invocation was successful. It is up the the application to decide if a particular result must be treated as a success
        +         * or a failure.
                  *
                  * @param statusCode invocation status success/failure
                  * @return this builder for fluent API
        @@ -118,8 +115,8 @@ public class AuditData {
                 }
         
                 /**
        -         * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it
        -         * is likely to be a standard HTTP response phrase.
        +         * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it is likely to be a standard HTTP
        +         * response phrase.
                  *
                  * @param responseDescription human-friendly response description
                  * @return this builder for fluent API
        diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java
        index 6eb747f9d9..ba556caac3 100644
        --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java
        +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ContextData.java
        @@ -13,15 +13,14 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.logging.api;
         
         import java.util.Objects;
         
         /**
        - * Builder to populate logging context data, i.e. data that should be available to any log writing event
        - * throughout an application. This includes only data known at some point to the application (e.g. at an API call),
        - * and not otherwise available to the logging framework (e.g. information about local runtime, machine, etc.).
        + * Builder to populate logging context data, i.e. data that should be available to any log writing event throughout an application. This
        + * includes only data known at some point to the application (e.g. at an API call), and not otherwise available to the logging framework (e.g.
        + * information about local runtime, machine, etc.).
          *
          * @author evitaliy
          * @since Mar 22, 2018
        @@ -38,6 +37,10 @@ public class ContextData {
                 this.partnerName = builder.partnerName;
             }
         
        +    public static ContextDataBuilder builder() {
        +        return new ContextDataBuilder();
        +    }
        +
             /**
              * Uniques request ID received from a calling peer, or created.
              *
        @@ -67,18 +70,15 @@ public class ContextData {
         
             @Override
             public boolean equals(Object o) {
        -
                 if (this == o) {
                     return true;
                 }
        -
                 if (o == null || getClass() != o.getClass()) {
                     return false;
                 }
        -
                 ContextData that = (ContextData) o;
        -        return Objects.equals(requestId, that.requestId) && Objects.equals(serviceName, that.serviceName)
        -                       && Objects.equals(partnerName, that.partnerName);
        +        return Objects.equals(requestId, that.requestId) && Objects.equals(serviceName, that.serviceName) && Objects
        +            .equals(partnerName, that.partnerName);
             }
         
             @Override
        @@ -88,12 +88,7 @@ public class ContextData {
         
             @Override
             public String toString() {
        -        return "ContextData{responseCode=" + requestId + ", responseDescription=" + serviceName
        -                       + ", clientIpAddress=" + partnerName + '}';
        -    }
        -
        -    public static ContextDataBuilder builder() {
        -        return new ContextDataBuilder();
        +        return "ContextData{responseCode=" + requestId + ", responseDescription=" + serviceName + ", clientIpAddress=" + partnerName + '}';
             }
         
             /**
        diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java
        index 6fbd25a134..9d670e8dcb 100644
        --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java
        +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/Logger.java
        @@ -4,16 +4,15 @@
          * Licensed under the Apache License, Version 2.0 (the "License");
          * you may not use this file except in compliance with the License.
          * You may obtain a copy of the License at
        - * 
        + *
          *      http://www.apache.org/licenses/LICENSE-2.0
        - * 
        + *
          * Unless required by applicable law or agreed to in writing, software
          * distributed under the License is distributed on an "AS IS" BASIS,
          * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.logging.api;
         
         /**
        diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java
        index 6ef57761d8..b772f5682c 100644
        --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java
        +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggerFactory.java
        @@ -13,7 +13,6 @@
          * See the License for the specific language governing permissions and
          * limitations under the License.
          */
        -
         package org.openecomp.sdc.logging.api;
         
         import java.util.Objects;
        @@ -22,22 +21,19 @@ import org.openecomp.sdc.logging.spi.LoggerCreationService;
         /**
          * Factory to hide a concrete, framework-specific implementation of logger creation.
          * 

        The service used by this factory must implement {@link LoggerCreationService}. If no - * implementation has been configured or could be instantiated, a no-op logger will be - * used, and no events will be logged. This is done to prevent recursion if attempts are - * being made to log exceptions that resulted from logger initialization.

        + * implementation has been configured or could be instantiated, a no-op logger will be used, and no events will be logged. This is done + * to prevent recursion if attempts are being made to log exceptions that resulted from logger initialization.

        * * @author evitaliy - * @since 13/09/2016. - * * @see ServiceBinder * @see LoggerCreationService + * @since 13/09/2016. */ public class LoggerFactory { - // use the no-op service to prevent recursion in case of an attempt to log an exception as a + // result of a logger initialization error - private static final LoggerCreationService SERVICE = ServiceBinder.getCreationServiceBinding().orElseGet( - NoOpLoggerCreationService::new); + private static final LoggerCreationService SERVICE = ServiceBinder.getCreationServiceBinding().orElseGet(NoOpLoggerCreationService::new); private LoggerFactory() { // prevent instantiation @@ -53,6 +49,18 @@ public class LoggerFactory { private static class NoOpLoggerCreationService implements LoggerCreationService { + @Override + public Logger getLogger(String className) { + Objects.requireNonNull(className, "Name cannot be null"); + return NoOpLogger.INSTANCE; + } + + @Override + public Logger getLogger(Class clazz) { + Objects.requireNonNull(clazz, "Class cannot be null"); + return NoOpLogger.INSTANCE; + } + private static class NoOpLogger implements Logger { private static final Logger INSTANCE = new NoOpLogger(); @@ -212,18 +220,5 @@ public class LoggerFactory { // no-op } } - - @Override - public Logger getLogger(String className) { - Objects.requireNonNull(className, "Name cannot be null"); - return NoOpLogger.INSTANCE; - } - - @Override - public Logger getLogger(Class clazz) { - Objects.requireNonNull(clazz, "Class cannot be null"); - return NoOpLogger.INSTANCE; - } } } - diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java index 894dd2c00c..29e3f33fa0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/LoggingContext.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Objects; @@ -24,9 +23,8 @@ import org.openecomp.sdc.logging.spi.LoggingContextService; *

        Factory to hide a concrete, framework-specific implementation of diagnostic context.

        * *

        The service used by this factory must implement {@link LoggingContextService}. If no implementation has been - * configured or could be instantiated, a no-op context service will be used, and no context will be - * stored or propagated. No errors will be generated, so that the application can still work (albeit without proper - * logging).

        + * configured or could be instantiated, a no-op context service will be used, and no context will be stored or propagated. No errors + * will be generated, so that the application can still work (albeit without proper logging).

        * * @author evitaliy * @see ServiceBinder @@ -35,8 +33,7 @@ import org.openecomp.sdc.logging.spi.LoggingContextService; */ public class LoggingContext { - private static final LoggingContextService SERVICE = - ServiceBinder.getContextServiceBinding().orElseGet(NoOpLoggingContextService::new); + private static final LoggingContextService SERVICE = ServiceBinder.getContextServiceBinding().orElseGet(NoOpLoggingContextService::new); private LoggingContext() { // prevent instantiation diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java index 2fef96d2bb..e85c22cb67 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/MetricsData.java @@ -13,15 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; -import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import lombok.Getter; +import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; /** - * Builder to populate metrics data. This includes only data known to an application, and not otherwise available - * to the logging framework. + * Builder to populate metrics data. This includes only data known to an application, and not otherwise available to the logging framework. * * @author evitaliy * @since 26 Mar 2018 @@ -30,7 +28,6 @@ import lombok.Getter; public class MetricsData { // don't inherit from AuditData because it has a very different meaning - private final long startTime; private final long endTime; private final ResponseStatus statusCode; @@ -51,17 +48,16 @@ public class MetricsData { this.targetVirtualEntity = builder.targetVirtualEntity; } - @Override - public String toString() { - return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode - + ", responseCode=" + responseCode + ", responseDescription=" + responseDescription - + ", clientIpAddress=" + clientIpAddress + '}'; - } - public static MetricsDataBuilder builder() { return new MetricsDataBuilder(); } + @Override + public String toString() { + return "AuditData{startTime=" + startTime + ", endTime=" + endTime + ", statusCode=" + statusCode + ", responseCode=" + responseCode + + ", responseDescription=" + responseDescription + ", clientIpAddress=" + clientIpAddress + '}'; + } + /** * Fluent API for building metrics data. */ @@ -101,8 +97,8 @@ public class MetricsData { } /** - * Indicate whether an invocation was successful. It is up the the application to decide if a particular result - * must be treated as a success or a failure. + * Indicate whether an invocation was successful. It is up the the application to decide if a particular result must be treated as a success + * or a failure. * * @param statusCode invocation status success/failure * @return this builder for fluent API @@ -124,8 +120,8 @@ public class MetricsData { } /** - * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it - * is likely to be a standard HTTP response phrase. + * Response description that explains {@link #responseCode(String)} in a human-friendly way. For a Web API, it is likely to be a standard HTTP + * response phrase. * * @param responseDescription human-friendly response description * @return this builder for fluent API diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java index 6e5b3e3501..65d624aa86 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/ServiceBinder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.api; import java.util.Iterator; @@ -35,6 +34,7 @@ import org.openecomp.sdc.logging.spi.LoggingServiceProvider; */ // No advanced logging can be used here because we don't know + // which underlying implementation will be used @SuppressWarnings({"UseOfSystemOutOrSystemErr", "squid:S106", "squid:S1166"}) class ServiceBinder { @@ -46,31 +46,23 @@ class ServiceBinder { } private static LoggingServiceProvider lookupProvider() { - ServiceLoader loader = ServiceLoader.load(LoggingServiceProvider.class); Iterator iterator = loader.iterator(); - if (!iterator.hasNext()) { - System.err.printf("[ERROR] No provider configured for logging services %s. " - + "Default implementation will be used.\n", LoggingServiceProvider.class.getName()); + System.err.printf("[ERROR] No provider configured for logging services %s. " + "Default implementation will be used.\n", + LoggingServiceProvider.class.getName()); return null; } - try { - LoggingServiceProvider provider = iterator.next(); if (!iterator.hasNext()) { return provider; } - Logger logger = provider.getLogger(ServiceBinder.class); if (logger.isWarnEnabled()) { - logger.warn("More than one provider for logging services {} found", - LoggingServiceProvider.class.getName()); + logger.warn("More than one provider for logging services {} found", LoggingServiceProvider.class.getName()); } - return provider; - } catch (Exception e) { // don't fail if the provider cannot be instantiated e.printStackTrace(System.err); @@ -86,4 +78,3 @@ class ServiceBinder { return Optional.ofNullable(PROVIDER); } } - diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java index cfe80da244..5faad5a7a3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/api/package-info.java @@ -17,9 +17,9 @@ /** *

        Client-visible API for logging, implemented according to * - * ONAP application logging guidelines. The actual implementation is delegated to a service provider bound through - * the Java SPI mechanism. The provider must - * implement {@link org.openecomp.sdc.logging.spi.LoggingServiceProvider}.

        + * ONAP application logging guidelines. The actual implementation is delegated to a service provider bound through the Java SPI mechanism. The provider must implement {@link + * org.openecomp.sdc.logging.spi.LoggingServiceProvider}.

        *

        The logging API collects the following types of data:

        *
          *
        1. Context that must be propagated throughout the application, and available at any point for debug and error @@ -35,4 +35,4 @@ * @author evitaliy * @since 26 Mar 2018 */ -package org.openecomp.sdc.logging.api; +package org.openecomp.sdc.logging.api; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java index 2aeacf1ad5..371aaf68b6 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/AuditTracker.java @@ -13,20 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; + import java.util.Objects; import javax.servlet.http.HttpServletRequest; import org.openecomp.sdc.logging.api.AuditData; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; - /** - * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and - * the pre- and post-request methods must be called only once. + * Tracks and logs audit information when a request is being processed. An instance of this class cannot be reused, and the pre- and post-request + * methods must be called only once. * * @author evitaliy * @since 31 Jul 2018 @@ -57,35 +56,27 @@ public class AuditTracker implements Tracker { @Override public synchronized void preRequest(HttpServletRequest request) { - if (this.started > 0) { throw new IllegalStateException("Pre-request has been already called"); } - this.started = System.currentTimeMillis(); this.clientIpAddress = request.getRemoteAddr(); - AuditData auditData = AuditData.builder().startTime(started).endTime(started).statusCode(COMPLETE) - .clientIpAddress(clientIpAddress) - .build(); + AuditData auditData = AuditData.builder().startTime(started).endTime(started).statusCode(COMPLETE).clientIpAddress(clientIpAddress).build(); logger.auditEntry(auditData); } @Override public synchronized void postRequest(RequestProcessingResult result) { - if (this.started == 0) { throw new IllegalStateException("Pre-request must be called first"); } - if (!logger.isAuditEnabled()) { return; } - long end = System.currentTimeMillis(); AuditData auditData = AuditData.builder().startTime(started).endTime(end).statusCode(result.getStatusCode()) - .responseCode(Integer.toString(result.getStatus())) - .responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress) - .build(); + .responseCode(Integer.toString(result.getStatus())).responseDescription(result.getStatusPhrase()).clientIpAddress(clientIpAddress) + .build(); logger.auditExit(auditData); } } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java index 5d940aa821..513a8a0361 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/CombinedTracker.java @@ -13,15 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; /** - * Tracker for all the elements of ONAP logging and tracing at an entry point to an application. - * The order of invocations is important, and on {@link #preRequest(HttpServletRequest)} it respects the order of - * trackers passed to the constructor. On {@link #postRequest(RequestProcessingResult)}, the invocation will be in the + * Tracker for all the elements of ONAP logging and tracing at an entry point to an application. The order of invocations is important, and on {@link + * #preRequest(HttpServletRequest)} it respects the order of trackers passed to the constructor. On {@link #postRequest(RequestProcessingResult)}, the + * invocation will be in the * reverse order. * * @author evitaliy @@ -38,7 +37,6 @@ public class CombinedTracker implements Tracker { @Override public void preRequest(HttpServletRequest request) { - for (Tracker t : trackers) { t.preRequest(request); } @@ -46,7 +44,6 @@ public class CombinedTracker implements Tracker { @Override public void postRequest(RequestProcessingResult result) { - for (int i = trackers.length - 1; i > -1; i--) { trackers[i].postRequest(result); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java index 02745f6287..51ba005521 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ContextTracker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import java.util.Objects; @@ -34,13 +33,12 @@ public class ContextTracker implements Tracker { private final HttpHeader partnerNameHeaders; private final HttpHeader requestIdHeaders; - private final Supplier loggingContextClear; private final Consumer loggingContextPut; /** - * Constructs tracker to handle required logging context in Servlet-based applications. Refer to ONAP logging - * guidelines for fields required to be put on logging context. + * Constructs tracker to handle required logging context in Servlet-based applications. Refer to ONAP logging guidelines for fields required to be + * put on logging context. * * @param partnerNameHeaders HTTP headers to check for a partner name, cannot be null * @param requestIdHeaders HTTP headers to check for a request ID, cannot be null @@ -56,36 +54,30 @@ public class ContextTracker implements Tracker { } /** - * Package level constructor used for tests. Clean and Put are passed as functions - * in order to avoid static mock and service loader config - LoggingServiceProvider in LoggingContext + * Package level constructor used for tests. Clean and Put are passed as functions in order to avoid static mock and service loader config - + * LoggingServiceProvider in LoggingContext * * @param partnerNameHeaders * @param requestIdHeaders * @param loggingContextClear * @param loggingContextPut */ - ContextTracker(HttpHeader partnerNameHeaders, - HttpHeader requestIdHeaders, - Supplier loggingContextClear, - Consumer loggingContextPut) { + ContextTracker(HttpHeader partnerNameHeaders, HttpHeader requestIdHeaders, Supplier loggingContextClear, + Consumer loggingContextPut) { this.partnerNameHeaders = Objects.requireNonNull(partnerNameHeaders); this.requestIdHeaders = Objects.requireNonNull(requestIdHeaders); this.loggingContextPut = loggingContextPut; - this.loggingContextClear =loggingContextClear; + this.loggingContextClear = loggingContextClear; } @Override public void preRequest(HttpServletRequest request) { - loggingContextClear.get(); - String serviceName = ServiceNameFormatter.format(request); String requestId = requestIdHeaders.getAny(request::getHeader).orElse(UUID.randomUUID().toString()); - ContextData.ContextDataBuilder contextBuilder = - ContextData.builder().serviceName(serviceName).requestId(requestId); + ContextData.ContextDataBuilder contextBuilder = ContextData.builder().serviceName(serviceName).requestId(requestId); String partnerName = partnerNameHeaders.getAny(request::getHeader).orElse("UNKNOWN"); contextBuilder.partnerName(partnerName); - loggingContextPut.accept(contextBuilder.build()); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java index dd5af859d4..95963b504f 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/HttpHeader.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import java.util.ArrayList; @@ -24,9 +23,9 @@ import java.util.Optional; import java.util.function.Function; /** - * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if - * multiple headers may have the same meaning. For instance, when requests come from multiple service, some using an old - * header and others using a new header to pass the same information. + * Handles any of possible header names to read a value for that header. This is useful for backward compatibility, if multiple headers may have the + * same meaning. For instance, when requests come from multiple service, some using an old header and others using a new header to pass the same + * information. * * @author evitaliy * @since 25 Mar 2018 @@ -35,7 +34,6 @@ public class HttpHeader { private static final String NAMES_CANNOT_BE_NULL = "Names cannot be null"; private static final String AT_LEAST_ONE_NAME_REQUIRED = "At least one name required"; - private final List headerNames; /** @@ -44,11 +42,9 @@ public class HttpHeader { * @param headerNames cannot be null or empty */ public HttpHeader(String... headerNames) { - if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).length < 1) { throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED); } - this.headerNames = Arrays.asList(headerNames); } @@ -58,11 +54,9 @@ public class HttpHeader { * @param headerNames cannot be null or empty */ public HttpHeader(List headerNames) { - if (Objects.requireNonNull(headerNames, NAMES_CANNOT_BE_NULL).isEmpty()) { throw new IllegalArgumentException(AT_LEAST_ONE_NAME_REQUIRED); } - this.headerNames = new ArrayList<>(headerNames); } @@ -73,29 +67,23 @@ public class HttpHeader { * @return value or empty if not found */ public Optional getAny(Function reader) { - for (String k : headerNames) { - String value = reader.apply(k); if (value != null) { return Optional.of(value); } } - return Optional.empty(); } @Override public boolean equals(Object o) { - if (this == o) { return true; } - if (o == null || getClass() != o.getClass()) { return false; } - HttpHeader that = (HttpHeader) o; return Objects.equals(headerNames, that.headerNames); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java index ff77ef8a93..bf1d1e5d0f 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/RequestProcessingResult.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java index fcbd281e88..dd5c0a7153 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/ServiceNameFormatter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java index c0337cfb4d..98b1d71969 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/Tracker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet; import javax.servlet.http.HttpServletRequest; @@ -34,9 +33,9 @@ public interface Tracker { void preRequest(HttpServletRequest request); /** - * Will be executed after a request has been processed. Results may be treated differently depending on a container - * and application. For instance, JAX-RS applications may take into account exception mappers before generating a - * response; some applications may Swagger annotations to map a response status to a human-friendly message, etc. + * Will be executed after a request has been processed. Results may be treated differently depending on a container and application. For + * instance, JAX-RS applications may take into account exception mappers before generating a response; some applications may Swagger annotations + * to map a response status to a human-friendly message, etc. * * @param result application- and container-specific request results */ diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java index fb651495ac..71d61b0de2 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingRequestFilter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet.jaxrs; import static org.openecomp.sdc.logging.LoggingConstants.DEFAULT_PARTNER_NAME_HEADER; @@ -35,8 +34,7 @@ import org.openecomp.sdc.logging.servlet.Tracker; /** *

          Takes care of logging initialization an HTTP request hits the application. This includes populating logging - * context and tracking the request for audit. The filter works in tandem with {@link LoggingResponseFilter} or - * a similar implementation.

          + * context and tracking the request for audit. The filter works in tandem with {@link LoggingResponseFilter} or a similar implementation.

          *

          The filter requires a few HTTP header names to be configured. These HTTP headers are used for propagating logging * and tracing information between ONAP components. Sample configuration for a Spring environment:

          *
          @@ -59,15 +57,11 @@ import org.openecomp.sdc.logging.servlet.Tracker;
           public class LoggingRequestFilter implements ContainerRequestFilter {
           
               static final String LOGGING_TRACKER_KEY = "onap.logging.tracker";
          -
               private static final String MULTI_VALUE_SEPARATOR = ",";
               private static final Logger LOGGER = LoggerFactory.getLogger(LoggingRequestFilter.class);
          -
               private HttpServletRequest httpRequest;
          -
               private HttpHeader requestIdHeader = new HttpHeader(DEFAULT_REQUEST_ID_HEADER);
               private HttpHeader partnerNameHeader = new HttpHeader(DEFAULT_PARTNER_NAME_HEADER);
          -
               private ResourceInfo resource;
           
               /**
          @@ -109,9 +103,7 @@ public class LoggingRequestFilter implements ContainerRequestFilter {
               @Override
               public void filter(ContainerRequestContext requestContext) {
                   Class resourceClass = resource.getResourceMethod().getDeclaringClass();
          -        Tracker tracker = new CombinedTracker(
          -                new ContextTracker(partnerNameHeader, requestIdHeader),
          -                new AuditTracker(resourceClass));
          +        Tracker tracker = new CombinedTracker(new ContextTracker(partnerNameHeader, requestIdHeader), new AuditTracker(resourceClass));
                   requestContext.setProperty(LOGGING_TRACKER_KEY, tracker);
                   tracker.preRequest(httpRequest);
               }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java
          index b0ae88ccaa..e5bdd56534 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/servlet/jaxrs/LoggingResponseFilter.java
          @@ -13,12 +13,12 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.servlet.jaxrs;
           
           import static javax.ws.rs.core.Response.Status.Family.REDIRECTION;
           import static javax.ws.rs.core.Response.Status.Family.SUCCESSFUL;
          -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.*;
          +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE;
          +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR;
           import static org.openecomp.sdc.logging.servlet.jaxrs.LoggingRequestFilter.LOGGING_TRACKER_KEY;
           
           import javax.ws.rs.container.ContainerRequestContext;
          @@ -26,7 +26,6 @@ import javax.ws.rs.container.ContainerResponseContext;
           import javax.ws.rs.container.ContainerResponseFilter;
           import javax.ws.rs.core.Response;
           import javax.ws.rs.ext.Provider;
          -
           import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus;
           import org.openecomp.sdc.logging.api.Logger;
           import org.openecomp.sdc.logging.api.LoggerFactory;
          @@ -35,8 +34,7 @@ import org.openecomp.sdc.logging.servlet.Tracker;
           
           /**
            * 

          Takes care of logging when an HTTP request leaves the application. This includes writing to audit and clearing - * logging context. This filter only works properly in tandem with {@link LoggingRequestFilter} or a similar - * implementation.

          + * logging context. This filter only works properly in tandem with {@link LoggingRequestFilter} or a similar implementation.

          *

          Sample configuration for a Spring environment:

          *
            *     <jaxrs:providers>
          @@ -57,14 +55,11 @@ public class LoggingResponseFilter implements ContainerResponseFilter {
           
               @Override
               public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
          -
                   Tracker tracker = (Tracker) requestContext.getProperty(LOGGING_TRACKER_KEY);
          -
                   if (tracker == null) {
                       LOGGER.debug("No logging tracker received");
                       return;
                   }
          -
                   tracker.postRequest(new ContainerResponseResult(responseContext.getStatusInfo()));
               }
           
          @@ -93,4 +88,3 @@ public class LoggingResponseFilter implements ContainerResponseFilter {
                   }
               }
           }
          -
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java
          index 54b5be3a27..d30412557a 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggerCreationService.java
          @@ -4,16 +4,15 @@
            * Licensed under the Apache License, Version 2.0 (the "License");
            * you may not use this file except in compliance with the License.
            * You may obtain a copy of the License at
          - * 
          + *
            *      http://www.apache.org/licenses/LICENSE-2.0
          - * 
          + *
            * Unless required by applicable law or agreed to in writing, software
            * distributed under the License is distributed on an "AS IS" BASIS,
            * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.spi;
           
           import org.openecomp.sdc.logging.api.Logger;
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java
          index 37e212ac54..7d08b2559c 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingContextService.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.spi;
           
           import java.util.concurrent.Callable;
          @@ -22,16 +21,14 @@ import org.openecomp.sdc.logging.api.ContextData;
           /**
            * Should be used to implement a framework-specific mechanism of managing a per-thread diagnostic context (for instance
            * MDC), and propagating it to child threads if needed. Context
          - * propagation should be used when creating a child thread directly, or submitting tasks for potentially postponed
          - * execution via an Executor
          - * (including any of the 
          - * executor services and 
          - * ForkJoinPool).
          + * propagation should be used when creating a child thread directly, or submitting tasks for potentially postponed execution via an Executor (including any of the  executor services and  ForkJoinPool).
            *
            * @author evitaliy
            * @since 07 Jan 2018
            */
          -
           public interface LoggingContextService {
           
               /**
          @@ -50,14 +47,14 @@ public interface LoggingContextService {
               void clear();
           
               /**
          -     * Copies logging context of current thread onto a {@link Runnable}, so that the context is available when this
          -     * {@link Runnable} runs in another thread.
          +     * Copies logging context of current thread onto a {@link Runnable}, so that the context is available when this {@link Runnable} runs in another
          +     * thread.
                */
               Runnable copyToRunnable(Runnable runnable);
           
               /**
          -     * Copies logging context of current thread onto a {@link Callable}, so that the context is available when this
          -     * {@link Callable} runs in another thread
          +     * Copies logging context of current thread onto a {@link Callable}, so that the context is available when this {@link Callable} runs in another
          +     * thread
                */
                Callable copyToCallable(Callable callable);
           }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java
          index 12e4040feb..4af0baebd2 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/spi/LoggingServiceProvider.java
          @@ -13,18 +13,17 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.spi;
           
           /**
            * 

          From the application code (consumer) perspective, logger creation (factory) and logging context are independent - * services. From the service provider perspective, however, these services are related and must be implemented together - * using the same underlying mechanism. Therefore, the service provider-facing interface combines the two services - * — to eliminate the chance that their implementations don't work well together.

          + * services. From the service provider perspective, however, these services are related and must be implemented together using the same underlying + * mechanism. Therefore, the service provider-facing interface combines the two services — to eliminate the chance that their implementations + * don't work well together.

          * * @author EVITALIY * @since 07 Jan 18 */ public interface LoggingServiceProvider extends LoggerCreationService, LoggingContextService { // single provider must implement two separate consumer services -} +} diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java index 6e63728a07..b27a0c857e 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/HostAddressCache.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.context; import java.net.InetAddress; @@ -25,10 +24,10 @@ import java.util.Optional; import java.util.function.Supplier; /** - * Holds a reference to local host address as returned by Java runtime. A value of host address will be cached for the - * interval specified in the constructor or {@link #DEFAULT_REFRESH_INTERVAL}. The caching helps to avoid many low-level - * calls, but at the same time pick up any IP or FQDN changes. Although the underlying JDK implementation uses caching - * too, the refresh interval for logging may be much longer due to the nature of the use. + * Holds a reference to local host address as returned by Java runtime. A value of host address will be cached for the interval specified in the + * constructor or {@link #DEFAULT_REFRESH_INTERVAL}. The caching helps to avoid many low-level calls, but at the same time pick up any IP or FQDN + * changes. Although the underlying JDK implementation uses caching too, the refresh interval for logging may be much longer due to the nature of the + * use. * * @author evitaliy * @since 26 Mar 2018 @@ -37,12 +36,9 @@ import java.util.function.Supplier; public class HostAddressCache { private static final long DEFAULT_REFRESH_INTERVAL = 60000L; // 1 min - private final long interval; - - private volatile CacheEntry cachedAddress; - private final Supplier readAddress; + private volatile CacheEntry cachedAddress; public HostAddressCache() { this(DEFAULT_REFRESH_INTERVAL); @@ -69,54 +65,27 @@ public class HostAddressCache { this.cachedAddress = new CacheEntry(System.currentTimeMillis(), this.readAddress.get()); } - /** - * Returns an address (host name and IP address) of the local system. - * - * @return local host address or null if it could not be read for some reason - */ - public synchronized Optional get() { - - long current = System.currentTimeMillis(); - if (current - cachedAddress.lastUpdated < interval) { - return Optional.ofNullable(cachedAddress.address); - } - - InetAddress address = readAddress.get(); // register the attempt even if null, i.e. failed to get a meaningful address - cachedAddress = new CacheEntry(current, address); - return Optional.ofNullable(address); - } - private static InetAddress read() { - try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { - System.err.println( - "[WARNING] Failed to get local host address. Using a fallback. If you are on Linux, make sure " - + "/etc/hosts contains the host name of your machine, " - + "e.g. '127.0.0.1 localhost my-host.example.com'."); - + System.err.println("[WARNING] Failed to get local host address. Using a fallback. If you are on Linux, make sure " + + "/etc/hosts contains the host name of your machine, " + "e.g. '127.0.0.1 localhost my-host.example.com'."); e.printStackTrace(); // can't really use logging return getFallbackLocalHost(); } } private static InetAddress getFallbackLocalHost() { - try { - Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); - while (networkInterfaces.hasMoreElements()) { - InetAddress address = getAddress(networkInterfaces.nextElement()); if (address != null) { return address; } } - return null; - } catch (SocketException e) { e.printStackTrace(); // can't really use logging return null; @@ -124,26 +93,36 @@ public class HostAddressCache { } private static InetAddress getAddress(NetworkInterface networkInterface) throws SocketException { - if (networkInterface.isLoopback() || networkInterface.isUp()) { return null; } - Enumeration interfaceAddresses = networkInterface.getInetAddresses(); while (interfaceAddresses.hasMoreElements()) { - InetAddress address = interfaceAddresses.nextElement(); if (isHostAddress(address)) { return address; } } - return null; } private static boolean isHostAddress(InetAddress address) { - return !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress() - && !address.isMulticastAddress(); + return !address.isLoopbackAddress() && !address.isAnyLocalAddress() && !address.isLinkLocalAddress() && !address.isMulticastAddress(); + } + + /** + * Returns an address (host name and IP address) of the local system. + * + * @return local host address or null if it could not be read for some reason + */ + public synchronized Optional get() { + long current = System.currentTimeMillis(); + if (current - cachedAddress.lastUpdated < interval) { + return Optional.ofNullable(cachedAddress.address); + } + InetAddress address = readAddress.get(); // register the attempt even if null, i.e. failed to get a meaningful address + cachedAddress = new CacheEntry(current, address); + return Optional.ofNullable(address); } private static class CacheEntry { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java index 73544e1d9f..354aaa24df 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/context/InstanceId.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.context; import java.util.UUID; /** - * Holds a unique ID of the logging entity. Is useful to distinguish between different nodes of the same application. If - * it can be assumed, that the node can be re-started, then the unique ID must be retained on the disk. + * Holds a unique ID of the logging entity. Is useful to distinguish between different nodes of the same application. If it can be assumed, that the + * node can be re-started, then the unique ID must be retained on the disk. * * @author evitaliy * @since 04 Mar 2018 @@ -32,7 +31,9 @@ public class InstanceId { static { // for some reason Java Preferences API + // https://docs.oracle.com/javase/8/docs/technotes/guides/preferences/overview.html + // didn't work in a Docker container, so for now just generate an ID every time INSTANCE_ID = UUID.randomUUID().toString(); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java index aa4657f83e..15471258b3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/logback/EventTypeDiscriminator.java @@ -4,16 +4,15 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.logback; import ch.qos.logback.classic.Level; @@ -23,8 +22,7 @@ import org.openecomp.sdc.logging.slf4j.Markers; import org.slf4j.Marker; /** - * Can be used with {@link ch.qos.logback.classic.sift.SiftingAppender} to route events of different types to - * separate log files. For example, + * Can be used with {@link ch.qos.logback.classic.sift.SiftingAppender} to route events of different types to separate log files. For example, * *
            *     <configuration>
          @@ -60,30 +58,25 @@ import org.slf4j.Marker;
           public class EventTypeDiscriminator extends AbstractDiscriminator {
           
               private static final String KEY = "eventType";
          -
               private static final String AUDIT = "Audit";
               private static final String METRICS = "Metrics";
               private static final String ERROR = "Error";
               private static final String DEBUG = "Debug";
               private static final String DEFAULT = DEBUG;
          -
               private static final int MIN_ERROR_LEVEL = Level.WARN_INT;
               private static final int MAX_ERROR_LEVEL = Level.ERROR_INT;
               private static final int DEFAULT_LEVEL = Level.DEBUG_INT;
           
               @Override
               public String getDiscriminatingValue(ILoggingEvent event) {
          -
                   Level level = event.getLevel();
                   final int levelInt = level == null ? DEFAULT_LEVEL : level.toInt();
                   if ((levelInt > MIN_ERROR_LEVEL - 1) && (levelInt < MAX_ERROR_LEVEL + 1)) {
                       return ERROR;
                   }
          -
                   if (levelInt == Level.DEBUG_INT) {
                       return DEBUG;
                   }
          -
                   /*
                    * After DEBUG, ERROR, and WARNING have been filtered out,
                    * only TRACE and INFO are left. TRACE is less than DEBUG
          @@ -91,22 +84,17 @@ public class EventTypeDiscriminator extends AbstractDiscriminator
                    * custom routing like AUDIT and METRICS
                    */
                   if (levelInt == Level.INFO_INT) {
          -
                       final Marker marker = event.getMarker();
                       if (marker != null) {
          -
          -                if (marker.contains(Markers.ENTRY) ||  marker.contains(Markers.EXIT)){
          +                if (marker.contains(Markers.ENTRY) || marker.contains(Markers.EXIT)) {
                               return AUDIT;
                           }
          -
                           if (marker.contains(Markers.METRICS)) {
                               return METRICS;
                           }
                       }
          -
                       return ERROR;
                   }
          -
                   return DEFAULT;
               }
           
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java
          index c08952a84d..26cb095fd5 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/AuditField.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import org.onap.logging.ref.slf4j.ONAPLogConstants;
          @@ -25,7 +24,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
            * @since 25 Mar 2018
            */
           enum AuditField implements MDCField {
          -
          +    // @formatter:off
               BEGIN_TIMESTAMP(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP),
               END_TIMESTAMP("EndTimestamp"),
               ELAPSED_TIME("ElapsedTime"),
          @@ -34,6 +33,7 @@ enum AuditField implements MDCField {
               RESPONSE_DESCRIPTION(ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION),
               CLIENT_IP_ADDRESS(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS),
               INVOCATION_ID(ONAPLogConstants.MDCs.INVOCATION_ID);
          +    // @formatter:on
           
               private final String key;
           
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java
          index 25784fefcd..c086d6d47d 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Context.java
          @@ -13,14 +13,13 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.util.Map;
           
           /**
          - * Does not store a state other than initial context values. Objects of this class may be reused by multiple threads,
          - * therefore they must be stateless to prevent inadvertent exchange of context values between threads.
          + * Does not store a state other than initial context values. Objects of this class may be reused by multiple threads, therefore they must be stateless
          + * to prevent inadvertent exchange of context values between threads.
            *
            * @author evitaliy
            * @since 08 Jan 2018
          @@ -34,8 +33,8 @@ final class Context {
               }
           
               /**
          -     * Pushes the initial context onto current thread, and returns the existing context. The result cannot be stored as
          -     * local state (see the class comments), and must be kept in a local variable to work properly.
          +     * Pushes the initial context onto current thread, and returns the existing context. The result cannot be stored as local state (see the class
          +     * comments), and must be kept in a local variable to work properly.
                *
                * @return previous context values
                */
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java
          index 87aa0e3a32..619426b883 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextField.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import org.onap.logging.ref.slf4j.ONAPLogConstants;
          @@ -25,13 +24,14 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
            * @since 23 Mar 2018
            */
           enum ContextField implements MDCField {
          -
          +    // @formatter:off
               REQUEST_ID(ONAPLogConstants.MDCs.REQUEST_ID),
               SERVICE_NAME(ONAPLogConstants.MDCs.SERVICE_NAME),
               PARTNER_NAME(ONAPLogConstants.MDCs.PARTNER_NAME),
               INSTANCE_ID(ONAPLogConstants.MDCs.INSTANCE_UUID),
               SERVER(ONAPLogConstants.MDCs.SERVER_FQDN),
               SERVER_IP_ADDRESS("ServerIpAddress");
          +    // @formatter:on
           
               private final String key;
           
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java
          index f9a7144b22..e62ceb6f91 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/ContextProvider.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.util.Map;
          @@ -25,5 +24,6 @@ import java.util.Map;
            * @since 23 Mar 2018
            */
           interface ContextProvider {
          +
               Map values();
           }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java
          index f6e933d57b..109671bf25 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/GlobalContextProvider.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.net.InetAddress;
          @@ -35,16 +34,13 @@ class GlobalContextProvider implements ContextProvider {
           
               @Override
               public Map values() {
          -
                   Map values = new EnumMap<>(ContextField.class);
                   values.put(ContextField.INSTANCE_ID, InstanceId.get());
          -
                   Optional hostAddress = HOST_ADDRESS_CACHE.get();
                   hostAddress.ifPresent(address -> {
                       values.put(ContextField.SERVER, address.getHostName());
                       values.put(ContextField.SERVER_IP_ADDRESS, address.getHostAddress());
                   });
          -
                   return values;
               }
           }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java
          index 84aa256d95..bf10fc2598 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCCallableWrapper.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.util.Map;
          @@ -28,7 +27,6 @@ import java.util.concurrent.Callable;
           class MDCCallableWrapper implements Callable {
           
               private final Context context = new Context();
          -
               private final Callable task;
           
               MDCCallableWrapper(Callable task) {
          @@ -37,9 +35,7 @@ class MDCCallableWrapper implements Callable {
           
               @Override
               public V call() throws Exception {
          -
                   Map oldContext = context.replace();
          -
                   try {
                       return task.call();
                   } finally {
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java
          index 026d3fa99b..23544f844b 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCDelegate.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.util.EnumMap;
          @@ -21,8 +20,7 @@ import java.util.Map;
           import org.slf4j.MDC;
           
           /**
          - * Because we don't know which information should be carried over from MDC, and which shouldn't, copy just the keys that
          - * the logging service uses.
          + * Because we don't know which information should be carried over from MDC, and which shouldn't, copy just the keys that the logging service uses.
            *
            * @author evitaliy
            * @since 23 Mar 2018
          @@ -37,7 +35,6 @@ class MDCDelegate {
                * Get a copy of logging MDC fields.
                */
               static Map copy() {
          -
                   Map copy = new EnumMap<>(ContextField.class);
                   for (ContextField k : ContextField.values()) {
                       String v = MDC.get(k.asKey());
          @@ -45,7 +42,6 @@ class MDCDelegate {
                           copy.put(k, v);
                       }
                   }
          -
                   return copy;
               }
           
          @@ -60,22 +56,18 @@ class MDCDelegate {
                * Reads selected fields from MDC.
                */
               static Map get(ContextField... fields) {
          -
                   Map values = new EnumMap<>(ContextField.class);
          -
                   for (ContextField key : fields) {
                       values.put(key, MDC.get(key.asKey()));
                   }
          -
                   return values;
               }
           
               /**
          -     * Entirely replaces the logging MDC context with the content of the argument. Logging keys that are not present in
          -     * the input map will be cleared from MDC.
          +     * Entirely replaces the logging MDC context with the content of the argument. Logging keys that are not present in the input map will be cleared
          +     * from MDC.
                */
               static void replace(Map values) {
          -
                   for (ContextField key : ContextField.values()) {
                       updateKey(key, values.get(key));
                   }
          @@ -85,27 +77,23 @@ class MDCDelegate {
                * Push data by multiple data providers on MDC.
                */
               static void put(ContextProvider... dataProviders) {
          -
                   clear();
          -
                   for (ContextProvider provider : dataProviders) {
                       push(provider.values());
                   }
               }
           
               /**
          -     * Updates the logging MDC context with the content of the argument. Logging keys that are not present in the input
          -     * map will remain "as is", keys with null values will be cleared from MDC.
          +     * Updates the logging MDC context with the content of the argument. Logging keys that are not present in the input map will remain "as is", keys
          +     * with null values will be cleared from MDC.
                */
               private static void push(Map values) {
          -
                   for (Map.Entry entry : values.entrySet()) {
                       updateKey(entry.getKey(), entry.getValue());
                   }
               }
           
               private static void updateKey(ContextField key, String value) {
          -
                   if (value != null) {
                       MDC.put(key.asKey(), value);
                   } else {
          @@ -114,7 +102,6 @@ class MDCDelegate {
               }
           
               static void clear() {
          -
                   for (ContextField field : ContextField.values()) {
                       MDC.remove(field.asKey());
                   }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java
          index 1096face85..518f911337 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCField.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           /**
          @@ -25,5 +24,4 @@ package org.openecomp.sdc.logging.slf4j;
           interface MDCField {
           
               String asKey();
          -
           }
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java
          index 9d93246181..dba96af7af 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MDCRunnableWrapper.java
          @@ -13,7 +13,6 @@
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import java.util.Map;
          @@ -27,7 +26,6 @@ import java.util.Map;
           class MDCRunnableWrapper implements Runnable {
           
               private final Context context = new Context();
          -
               private final Runnable task;
           
               MDCRunnableWrapper(Runnable task) {
          @@ -36,9 +34,7 @@ class MDCRunnableWrapper implements Runnable {
           
               @Override
               public void run() {
          -
                   Map oldContext = context.replace();
          -
                   try {
                       task.run();
                   } finally {
          diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java
          index 3d9bbcfa53..2225f60a1a 100644
          --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java
          +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/Markers.java
          @@ -4,16 +4,15 @@
            * Licensed under the Apache License, Version 2.0 (the "License");
            * you may not use this file except in compliance with the License.
            * You may obtain a copy of the License at
          - * 
          + *
            *      http://www.apache.org/licenses/LICENSE-2.0
          - * 
          + *
            * Unless required by applicable law or agreed to in writing, software
            * distributed under the License is distributed on an "AS IS" BASIS,
            * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
            * See the License for the specific language governing permissions and
            * limitations under the License.
            */
          -
           package org.openecomp.sdc.logging.slf4j;
           
           import org.onap.logging.ref.slf4j.ONAPLogConstants;
          @@ -36,15 +35,13 @@ import org.slf4j.MarkerFactory;
            * 
          * * @author EVITALIY - * @since 13/09/2016. - * * @see Marker + * @since 13/09/2016. */ public class Markers { public static final Marker ENTRY = MarkerFactory.getMarker(ONAPLogConstants.Markers.ENTRY.getName()); public static final Marker EXIT = MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName()); - public static final Marker METRICS = MarkerFactory.getMarker("METRICS"); private Markers() { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java index c4e8e143af..2845e71ffc 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/MetricsField.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -25,7 +24,7 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants; * @since 26 Mar 2018 */ public enum MetricsField implements MDCField { - + // @formatter:off BEGIN_TIMESTAMP(ONAPLogConstants.MDCs.INVOKE_TIMESTAMP), END_TIMESTAMP("EndTimestamp"), ELAPSED_TIME("ElapsedTime"), @@ -35,6 +34,7 @@ public enum MetricsField implements MDCField { CLIENT_IP_ADDRESS(ONAPLogConstants.MDCs.CLIENT_IP_ADDRESS), TARGET_VIRTUAL_ENTITY("TargetVirtualEntity"), TARGET_ENTITY(ONAPLogConstants.MDCs.TARGET_ENTITY); + // @formatter:on private final String key; @@ -45,5 +45,4 @@ public enum MetricsField implements MDCField { public String asKey() { return key; } - } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java index 70e3dd6479..38f691f9ed 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/RequestContextProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.EnumMap; @@ -39,21 +38,16 @@ class RequestContextProvider implements ContextProvider { } static ContextData to(Map values) { - return ContextData.builder() - .requestId(values.get(ContextField.REQUEST_ID)) - .serviceName(values.get(ContextField.SERVICE_NAME)) - .partnerName(values.get(ContextField.PARTNER_NAME)).build(); + return ContextData.builder().requestId(values.get(ContextField.REQUEST_ID)).serviceName(values.get(ContextField.SERVICE_NAME)) + .partnerName(values.get(ContextField.PARTNER_NAME)).build(); } @Override public Map values() { - Map values = new EnumMap<>(ContextField.class); - putIfNotNull(values, ContextField.REQUEST_ID, data.getRequestId()); putIfNotNull(values, ContextField.SERVICE_NAME, data.getServiceName()); putIfNotNull(values, ContextField.PARTNER_NAME, data.getPartnerName()); - return values; } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java index 54026098c1..80ca807f2b 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggerWrapper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.text.SimpleDateFormat; @@ -34,7 +33,6 @@ class SLF4JLoggerWrapper implements Logger { //The specified format presents time in UTC formatted per ISO 8601, as required by ONAP logging guidelines private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - private final org.slf4j.Logger logger; // May cause http://www.slf4j.org/codes.html#loggerNameMismatch @@ -50,6 +48,16 @@ class SLF4JLoggerWrapper implements Logger { this(LoggerFactory.getLogger(className)); } + private static void unsafePutOnMdc(MDCField field, String value) { + MDC.put(field.asKey(), value); + } + + private static void safePutOnMdc(MDCField field, String value) { + if (value != null) { + unsafePutOnMdc(field, value); + } + } + @Override public String getName() { return logger.getName(); @@ -67,11 +75,9 @@ class SLF4JLoggerWrapper implements Logger { @Override public void metrics(MetricsData data) { - if (data == null) { return; // not going to fail because of null } - try { putMetricsOnMdc(data); logger.info(Markers.METRICS, ""); @@ -81,7 +87,6 @@ class SLF4JLoggerWrapper implements Logger { } private void putMetricsOnMdc(MetricsData metrics) { - SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN); unsafePutOnMdc(MetricsField.BEGIN_TIMESTAMP, dateFormat.format(metrics.getStartTime())); unsafePutOnMdc(MetricsField.END_TIMESTAMP, dateFormat.format(metrics.getEndTime())); @@ -91,7 +96,6 @@ class SLF4JLoggerWrapper implements Logger { safePutOnMdc(MetricsField.CLIENT_IP_ADDRESS, metrics.getClientIpAddress()); safePutOnMdc(MetricsField.TARGET_ENTITY, metrics.getTargetEntity()); safePutOnMdc(MetricsField.TARGET_VIRTUAL_ENTITY, metrics.getTargetVirtualEntity()); - if (metrics.getStatusCode() != null) { unsafePutOnMdc(MetricsField.STATUS_CODE, metrics.getStatusCode().name()); } @@ -103,16 +107,6 @@ class SLF4JLoggerWrapper implements Logger { } } - private static void unsafePutOnMdc(MDCField field, String value) { - MDC.put(field.asKey(), value); - } - - private static void safePutOnMdc(MDCField field, String value) { - if (value != null) { - unsafePutOnMdc(field, value); - } - } - @Override public boolean isAuditEnabled() { return logger.isInfoEnabled(Markers.EXIT); @@ -120,11 +114,9 @@ class SLF4JLoggerWrapper implements Logger { @Override public void auditEntry(AuditData data) { - if (data == null) { return; // not failing if null } - try { putAuditOnMdc(data); logger.info(Markers.ENTRY, ""); @@ -133,14 +125,11 @@ class SLF4JLoggerWrapper implements Logger { } } - @Override public void auditExit(AuditData data) { - if (data == null) { return; // not failing if null } - try { putAuditOnMdc(data); logger.info(Markers.EXIT, ""); @@ -150,7 +139,6 @@ class SLF4JLoggerWrapper implements Logger { } private void putAuditOnMdc(AuditData audit) { - SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_PATTERN); unsafePutOnMdc(AuditField.BEGIN_TIMESTAMP, dateFormat.format(audit.getStartTime())); unsafePutOnMdc(AuditField.END_TIMESTAMP, dateFormat.format(audit.getEndTime())); @@ -159,7 +147,6 @@ class SLF4JLoggerWrapper implements Logger { safePutOnMdc(AuditField.RESPONSE_DESCRIPTION, audit.getResponseDescription()); safePutOnMdc(AuditField.CLIENT_IP_ADDRESS, audit.getClientIpAddress()); unsafePutOnMdc(AuditField.INVOCATION_ID, UUID.randomUUID().toString()); - if (audit.getStatusCode() != null) { unsafePutOnMdc(AuditField.STATUS_CODE, audit.getStatusCode().name()); } diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java index 9d4d507ac5..a74f606bc0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/slf4j/SLF4JLoggingServiceProvider.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.slf4j; import java.util.Objects; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java index 393a061987..a4eb93beaa 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-spring/src/main/java/org/openecomp/sdc/logging/servlet/spring/LoggingInterceptor.java @@ -13,17 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.logging.servlet.spring; -import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.*; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.COMPLETE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus.ERROR; import static org.springframework.http.HttpStatus.Series.REDIRECTION; import static org.springframework.http.HttpStatus.Series.SUCCESSFUL; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.logging.ref.slf4j.ONAPLogConstants.ResponseStatus; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -42,8 +41,8 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; *

          IMPORTANT: For this interceptor to work, all exceptions must be properly handled before being returned to a * client. Any unexpected, automatically handled exception bypasses the interceptor and will not be logged.

          *

          The interceptor must be either registered in Spring configuration XML as a bean, or programmatically as described - * in - * Spring MVC Config: Interceptors.

          + * in Spring MVC Config: + * Interceptors.

          * * @author evitaliy * @since 02 Aug 2018 @@ -52,9 +51,7 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class LoggingInterceptor extends HandlerInterceptorAdapter { static final String LOGGING_TRACKER_KEY = "onap.logging.tracker"; - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingInterceptor.class); - private final HttpHeader partnerNameHeader; private final HttpHeader requestIdHeader; @@ -66,34 +63,26 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { Class resourceClass = getResourceType(handler); - Tracker tracker = new CombinedTracker( - new ContextTracker(partnerNameHeader, requestIdHeader), - new AuditTracker(resourceClass)); + Tracker tracker = new CombinedTracker(new ContextTracker(partnerNameHeader, requestIdHeader), new AuditTracker(resourceClass)); request.setAttribute(LOGGING_TRACKER_KEY, tracker); tracker.preRequest(request); return true; } @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, - Exception ex) { - + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { Tracker tracker = (Tracker) request.getAttribute(LOGGING_TRACKER_KEY); - if (tracker == null) { LOGGER.debug("No logging tracker received"); return; } - tracker.postRequest(new ServletResponseResult(response.getStatus())); } private Class getResourceType(Object handler) { - if (handler instanceof HandlerMethod) { return ((HandlerMethod) handler).getMethod().getDeclaringClass(); } - return LoggingInterceptor.class; } @@ -106,7 +95,6 @@ public class LoggingInterceptor extends HandlerInterceptorAdapter { } private StatusInfo init(int status) { - try { return new StatusInfo(HttpStatus.valueOf(status)); } catch (IllegalArgumentException e) { diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java index 3e5975dd13..033c4ee11c 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.dao; import org.openecomp.core.model.types.ServiceArtifact; import org.openecomp.sdc.versioning.dao.VersionableDao; -public interface EnrichedServiceModelDao extends VersionableDao,ServiceModelDao{ - - void storeExternalArtifact(ServiceArtifact serviceArtifact); +public interface EnrichedServiceModelDao extends VersionableDao, ServiceModelDao { - //List getExternalArtifacts(String vspId, Version version); + void storeExternalArtifact(ServiceArtifact serviceArtifact); + //List getExternalArtifacts(String vspId, Version version); - //List getServiceModelContentNames(); -} + //List getServiceModelContentNames(); +} diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDaoFactory.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDaoFactory.java index 9d18d6c9cf..5ff24263c8 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class EnrichedServiceModelDaoFactory - extends AbstractComponentFactory { +public abstract class EnrichedServiceModelDaoFactory extends AbstractComponentFactory { - public static EnrichedServiceModelDaoFactory getInstance() { - return AbstractFactory.getInstance(EnrichedServiceModelDaoFactory.class); - } + public static EnrichedServiceModelDaoFactory getInstance() { + return AbstractFactory.getInstance(EnrichedServiceModelDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceArtifactDaoInter.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceArtifactDaoInter.java index 30677b70a3..020c51cb77 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceArtifactDaoInter.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceArtifactDaoInter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,30 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.dao; +import java.util.Collection; import org.openecomp.core.model.types.ServiceArtifact; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ServiceArtifactDaoInter extends VersionableDao { - Collection list(String vspId, Version version); + Collection list(String vspId, Version version); - void create(ServiceArtifact entity); + void create(ServiceArtifact entity); - void update(ServiceArtifact entity); + void update(ServiceArtifact entity); - ServiceArtifact get(String vspId, Version version); + ServiceArtifact get(String vspId, Version version); - void delete(String vspId, Version version); + void delete(String vspId, Version version); - Object[] getKeys(String vspId, Version version); + Object[] getKeys(String vspId, Version version); - ServiceArtifact getArtifactInfo(String vspId, Version version, String name); + ServiceArtifact getArtifactInfo(String vspId, Version version, String name); - void deleteAll(String vspId, Version version); + void deleteAll(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDao.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDao.java index 0fb80b1835..7908711023 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.dao; import org.openecomp.sdc.versioning.dao.VersionableDao; @@ -25,17 +24,16 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ServiceModelDao extends VersionableDao { - M getServiceModel(String vspId, Version version); + M getServiceModel(String vspId, Version version); - void storeServiceModel(String vspId, Version version, M serviceModel); + void storeServiceModel(String vspId, Version version, M serviceModel); - E getServiceModelInfo(String vspId, Version version, String name); + E getServiceModelInfo(String vspId, Version version, String name); - void deleteAll(String vspId, Version version); + void deleteAll(String vspId, Version version); - /** - * This method gets used in healing, in order to replace the healed service model with the - * existing one without creating any conflicts - **/ - void overrideServiceModel(String vspId, Version version, M serviceModel); + /** + * This method gets used in healing, in order to replace the healed service model with the existing one without creating any conflicts + **/ + void overrideServiceModel(String vspId, Version version, M serviceModel); } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDaoFactory.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDaoFactory.java index 19f6cb5c8c..3567ba3ae7 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/ServiceModelDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ServiceModelDaoFactory extends AbstractComponentFactory { - public static ServiceModelDaoFactory getInstance() { - return AbstractFactory.getInstance(ServiceModelDaoFactory.class); - } + public static ServiceModelDaoFactory getInstance() { + return AbstractFactory.getInstance(ServiceModelDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/errors/RetrieveServiceTemplateFromDbErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/errors/RetrieveServiceTemplateFromDbErrorBuilder.java index 036acb2bf0..b9c4245640 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/errors/RetrieveServiceTemplateFromDbErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/errors/RetrieveServiceTemplateFromDbErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; public class RetrieveServiceTemplateFromDbErrorBuilder extends BaseErrorBuilder { - private static final String CANT_RETRIEVE_SERVICE_TEMPLATE = "Could not retrirve service " + - "template named %s. Reason - %s"; - private static final String CREATE_SERVICE_TEMPLATE = "CREATE_SERVICE_TEMPLATE"; - public RetrieveServiceTemplateFromDbErrorBuilder(String serviceTemplateName, - String reason){ - this.getErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId(CREATE_SERVICE_TEMPLATE) - .withMessage(String.format(CANT_RETRIEVE_SERVICE_TEMPLATE, serviceTemplateName, reason)); - } + private static final String CANT_RETRIEVE_SERVICE_TEMPLATE = "Could not retrirve service " + "template named %s. Reason - %s"; + private static final String CREATE_SERVICE_TEMPLATE = "CREATE_SERVICE_TEMPLATE"; + + public RetrieveServiceTemplateFromDbErrorBuilder(String serviceTemplateName, String reason) { + this.getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(CREATE_SERVICE_TEMPLATE) + .withMessage(String.format(CANT_RETRIEVE_SERVICE_TEMPLATE, serviceTemplateName, reason)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java index fbe0bb5362..d47ec10f2c 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java @@ -13,16 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.model.types; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import com.google.common.io.ByteStreams; -import org.openecomp.sdc.common.errors.SdcRuntimeException; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.IOException; import java.nio.ByteBuffer; +import org.openecomp.sdc.common.errors.SdcRuntimeException; +import org.openecomp.sdc.versioning.dao.types.Version; @Table(keyspace = "dox", name = "vsp_enriched_service_artifact") public class EnrichedServiceArtifactEntity implements ServiceElementEntity { @@ -36,15 +38,12 @@ public class EnrichedServiceArtifactEntity implements ServiceElementEntity { @PartitionKey @Column(name = "vsp_id") public String id; - @PartitionKey(value = 1) @Frozen public Version version; - @ClusteringColumn @Column(name = "name") public String name; - @Column(name = "content_data") public ByteBuffer contentData; @@ -66,13 +65,11 @@ public class EnrichedServiceArtifactEntity implements ServiceElementEntity { this.id = entity.getVspId(); this.version = entity.getVersion(); this.name = entity.getName(); - try { this.contentData = ByteBuffer.wrap(ByteStreams.toByteArray(entity.getContent())); } catch (IOException ioException) { throw new SdcRuntimeException(ioException); } - } @Override diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java index aa6abbed75..8301df73c7 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java @@ -13,16 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.model.types; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import com.google.common.io.ByteStreams; -import org.openecomp.sdc.common.errors.SdcRuntimeException; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.IOException; import java.nio.ByteBuffer; +import org.openecomp.sdc.common.errors.SdcRuntimeException; +import org.openecomp.sdc.versioning.dao.types.Version; @Table(keyspace = "dox", name = "vsp_enriched_service_template") public class EnrichedServiceTemplateEntity implements ServiceElementEntity { @@ -36,18 +38,14 @@ public class EnrichedServiceTemplateEntity implements ServiceElementEntity { @PartitionKey @Column(name = "vsp_id") public String id; - @PartitionKey(value = 1) @Frozen public Version version; - @ClusteringColumn @Column(name = "name") public String name; - @Column(name = "content_data") public ByteBuffer contentData; - @Column(name = "base_name") private String baseName; @@ -75,7 +73,6 @@ public class EnrichedServiceTemplateEntity implements ServiceElementEntity { } catch (IOException ioException) { throw new SdcRuntimeException(ioException); } - } public String getBaseName() { diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifact.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifact.java index 184704b094..bb6f4b5574 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.types; import lombok.NoArgsConstructor; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java index 0709371d94..bfab42f8ee 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java @@ -13,19 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.model.types; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import com.google.common.io.ByteStreams; -import org.openecomp.sdc.common.errors.SdcRuntimeException; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.IOException; import java.nio.ByteBuffer; +import org.openecomp.sdc.common.errors.SdcRuntimeException; +import org.openecomp.sdc.versioning.dao.types.Version; @Table(keyspace = "dox", name = "vsp_service_artifact") public class ServiceArtifactEntity implements ServiceElementEntity { + private static final String ENTITY_TYPE; static { @@ -35,15 +38,12 @@ public class ServiceArtifactEntity implements ServiceElementEntity { @PartitionKey @Column(name = "vsp_id") public String id; - @PartitionKey(value = 1) @Frozen public Version version; - @ClusteringColumn @Column(name = "name") public String name; - @Column(name = "content_data") public ByteBuffer contentData; @@ -65,13 +65,11 @@ public class ServiceArtifactEntity implements ServiceElementEntity { this.id = entity.getVspId(); this.version = entity.getVersion(); this.name = entity.getName(); - try { this.contentData = ByteBuffer.wrap(ByteStreams.toByteArray(entity.getContent())); } catch (IOException ioException) { throw new SdcRuntimeException(ioException); } - } @Override @@ -130,5 +128,4 @@ public class ServiceArtifactEntity implements ServiceElementEntity { serviceArtifact.setVspId(this.getId()); return serviceArtifact; } - } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElement.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElement.java index 817cfa9d44..f598c4b225 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElement.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElement.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.types; import java.io.ByteArrayInputStream; @@ -48,5 +47,4 @@ public class ServiceElement { } return new ByteArrayInputStream(contentData); } - } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElementEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElementEntity.java index 02249039f8..716e140fc8 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElementEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceElementEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.types; -import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - import java.nio.ByteBuffer; +import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public interface ServiceElementEntity extends VersionableEntity { - String getName(); - ByteBuffer getContentData(); + String getName(); + + ByteBuffer getContentData(); } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplate.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplate.java index 479502e8f9..14bdb0869f 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplate.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplate.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.model.types; import lombok.Getter; @@ -30,5 +29,4 @@ import lombok.Setter; public class ServiceTemplate extends ServiceElement { private String baseName; - } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java index 80f0cfb371..48b539ec5f 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java @@ -13,16 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.model.types; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import com.google.common.io.ByteStreams; -import org.openecomp.sdc.common.errors.SdcRuntimeException; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.IOException; import java.nio.ByteBuffer; +import org.openecomp.sdc.common.errors.SdcRuntimeException; +import org.openecomp.sdc.versioning.dao.types.Version; @Table(keyspace = "dox", name = "vsp_service_template") public class ServiceTemplateEntity implements ServiceElementEntity { @@ -36,18 +38,14 @@ public class ServiceTemplateEntity implements ServiceElementEntity { @PartitionKey @Column(name = "vsp_id") public String id; - @PartitionKey(value = 1) @Frozen public Version version; - @ClusteringColumn @Column(name = "name") public String name; - @Column(name = "content_data") public ByteBuffer contentData; - @Column(name = "base_name") private String baseName; @@ -75,7 +73,6 @@ public class ServiceTemplateEntity implements ServiceElementEntity { } catch (IOException ioException) { throw new SdcRuntimeException(ioException); } - } public String getBaseName() { diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoFactoryImpl.java index 98cb8724df..7ffd0b0c7b 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl; import org.openecomp.core.model.dao.EnrichedServiceModelDao; @@ -26,11 +25,12 @@ import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; import org.openecomp.sdc.model.impl.zusammen.EnrichedServiceModelDaoZusammenImpl; public class EnrichedServiceModelDaoFactoryImpl extends EnrichedServiceModelDaoFactory { - private static final EnrichedServiceModelDao INSTANCE = new EnrichedServiceModelDaoZusammenImpl( ZusammenAdaptorFactory - .getInstance().createInterface()); - @Override - public EnrichedServiceModelDao createInterface() { - return INSTANCE; - } + private static final EnrichedServiceModelDao INSTANCE = new EnrichedServiceModelDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public EnrichedServiceModelDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/ServiceModelDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/ServiceModelDaoFactoryImpl.java index 85508670aa..5134076a5f 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/ServiceModelDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/ServiceModelDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl; import org.openecomp.core.model.dao.ServiceModelDao; @@ -26,11 +25,11 @@ import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; import org.openecomp.sdc.model.impl.zusammen.ServiceModelDaoZusammenImpl; public class ServiceModelDaoFactoryImpl extends ServiceModelDaoFactory { - private static final ServiceModelDao INSTANCE = new ServiceModelDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ServiceModelDao createInterface() { - return INSTANCE; - } + private static final ServiceModelDao INSTANCE = new ServiceModelDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ServiceModelDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ElementType.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ElementType.java index 788bf79423..4f62a16642 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ElementType.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ElementType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl.zusammen; -public enum ElementType { - Servicetemplate,Artifact; - - -} +public enum ElementType {Servicetemplate, Artifact;} diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java index 938f104b1e..6f1492c163 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; @@ -35,41 +36,29 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; - public class EnrichedServiceModelDaoZusammenImpl extends ServiceModelDaoZusammenImpl implements EnrichedServiceModelDao { - private static final Logger logger = - LoggerFactory.getLogger(EnrichedServiceModelDaoZusammenImpl.class); - - public EnrichedServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - super(zusammenAdaptor); - this.elementType = ElementType.EnrichedServiceModel; - } - - @Override - public void storeExternalArtifact(ServiceArtifact serviceArtifact) { - ZusammenElement artifact = buildArtifactElement(serviceArtifact.getName(), - FileUtils.toByteArray(serviceArtifact.getContent()), Action.CREATE); - - ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.IGNORE); - artifacts.addSubElement(artifact); - - ZusammenElement enrichedServiceModel = buildStructuralElement(elementType, Action.IGNORE); - enrichedServiceModel.addSubElement(artifacts); - - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(enrichedServiceModel); + private static final Logger logger = LoggerFactory.getLogger(EnrichedServiceModelDaoZusammenImpl.class); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = - new ElementContext(serviceArtifact.getVspId(), serviceArtifact.getVersion().getId()); - zusammenAdaptor - .saveElement(context, elementContext, vspModel, "add service external artifact."); + public EnrichedServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + super(zusammenAdaptor); + this.elementType = ElementType.EnrichedServiceModel; + } - logger.info( - "Finished adding artifact to enriched service model for VendorSoftwareProduct id -> {}", - elementContext.getItemId().getValue()); - } + @Override + public void storeExternalArtifact(ServiceArtifact serviceArtifact) { + ZusammenElement artifact = buildArtifactElement(serviceArtifact.getName(), FileUtils.toByteArray(serviceArtifact.getContent()), + Action.CREATE); + ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.IGNORE); + artifacts.addSubElement(artifact); + ZusammenElement enrichedServiceModel = buildStructuralElement(elementType, Action.IGNORE); + enrichedServiceModel.addSubElement(artifacts); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(enrichedServiceModel); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(serviceArtifact.getVspId(), serviceArtifact.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "add service external artifact."); + logger.info("Finished adding artifact to enriched service model for VendorSoftwareProduct id -> {}", elementContext.getItemId().getValue()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java index 8ff78d6401..27ef113204 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +30,12 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil; @@ -45,267 +53,189 @@ import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; - -public class ServiceModelDaoZusammenImpl - implements ServiceModelDao { - private static final String BASE_PROPERTY = "base"; - private static final Logger logger = LoggerFactory.getLogger(ServiceModelDaoZusammenImpl.class); - - protected ZusammenAdaptor zusammenAdaptor; - protected ElementType elementType; +public class ServiceModelDaoZusammenImpl implements ServiceModelDao { - public ServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - this.elementType = ElementType.ServiceModel; - } + private static final String BASE_PROPERTY = "base"; + private static final Logger logger = LoggerFactory.getLogger(ServiceModelDaoZusammenImpl.class); + protected ZusammenAdaptor zusammenAdaptor; + protected ElementType elementType; - @Override - public void registerVersioning(String versionableEntityType) { - - } - - @Override - public ToscaServiceModel getServiceModel(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional serviceModel = getServiceModelElementInfo(context, elementContext); - if (!serviceModel.isPresent()) { - return null; + public ServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + this.elementType = ElementType.ServiceModel; } - Id serviceModelElementId = serviceModel.get().getId(); - Map serviceTemplates = - getTemplates(context, elementContext, serviceModelElementId); - if (serviceTemplates == null) { - return null; + @Override + public void registerVersioning(String versionableEntityType) { } - FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); - String entryDefinitionServiceTemplate = - serviceModel.get().getInfo().getProperty(BASE_PROPERTY); - - return new ToscaServiceModel(artifacts, serviceTemplates, entryDefinitionServiceTemplate); - } - - @Override - public void storeServiceModel(String vspId, Version version, ToscaServiceModel serviceModel) { - logger.info("Storing service model for VendorSoftwareProduct id -> {}", vspId); - - ZusammenElement templatesElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); - serviceModel.getServiceTemplates().forEach((key, value) -> templatesElement.addSubElement( - buildServiceTemplateElement(key, value, serviceModel.getEntryDefinitionServiceTemplate(), Action.CREATE))); - - ZusammenElement artifactsElement = buildStructuralElement(ElementType.Artifacts, Action.UPDATE); - if (Objects.nonNull(serviceModel.getArtifactFiles())) { - serviceModel.getArtifactFiles().getFiles().forEach( - (key, value) -> artifactsElement.addSubElement(buildArtifactElement(key, value, Action.CREATE))); + @Override + public ToscaServiceModel getServiceModel(String vspId, Version version) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional serviceModel = getServiceModelElementInfo(context, elementContext); + if (!serviceModel.isPresent()) { + return null; + } + Id serviceModelElementId = serviceModel.get().getId(); + Map serviceTemplates = getTemplates(context, elementContext, serviceModelElementId); + if (serviceTemplates == null) { + return null; + } + FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); + String entryDefinitionServiceTemplate = serviceModel.get().getInfo().getProperty(BASE_PROPERTY); + return new ToscaServiceModel(artifacts, serviceTemplates, entryDefinitionServiceTemplate); } - ZusammenElement serviceModelElement = buildServiceModelElement(serviceModel.getEntryDefinitionServiceTemplate()); - - serviceModelElement.addSubElement(templatesElement); - serviceModelElement.addSubElement(artifactsElement); - - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(serviceModelElement); - - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, vspModel, "Store service model"); - - logger - .info("Finished storing {} for VendorSoftwareProduct id -> {}", elementType.name(), vspId); - } - - @Override - public ServiceElement getServiceModelInfo(String vspId, Version version, String name) { - return null; - } - - @Override - public void deleteAll(String vspId, Version version) { - logger.info("Started deleting content of Templates and Artifacts of {} of vsp {} version {}", - elementType.name(), vspId, version.getId()); - - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional serviceModel = getServiceModelElementInfo(context, elementContext); - if (!serviceModel.isPresent()) { - logger.info("{} of vsp {} version {} does not exist - nothing to delete", elementType.name(), - vspId, version.getId()); - return; + @Override + public void storeServiceModel(String vspId, Version version, ToscaServiceModel serviceModel) { + logger.info("Storing service model for VendorSoftwareProduct id -> {}", vspId); + ZusammenElement templatesElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); + serviceModel.getServiceTemplates().forEach((key, value) -> templatesElement + .addSubElement(buildServiceTemplateElement(key, value, serviceModel.getEntryDefinitionServiceTemplate(), Action.CREATE))); + ZusammenElement artifactsElement = buildStructuralElement(ElementType.Artifacts, Action.UPDATE); + if (Objects.nonNull(serviceModel.getArtifactFiles())) { + serviceModel.getArtifactFiles().getFiles() + .forEach((key, value) -> artifactsElement.addSubElement(buildArtifactElement(key, value, Action.CREATE))); + } + ZusammenElement serviceModelElement = buildServiceModelElement(serviceModel.getEntryDefinitionServiceTemplate()); + serviceModelElement.addSubElement(templatesElement); + serviceModelElement.addSubElement(artifactsElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(serviceModelElement); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Store service model"); + logger.info("Finished storing {} for VendorSoftwareProduct id -> {}", elementType.name(), vspId); } - ZusammenElement serviceModelElement = buildElement(serviceModel.get().getId(), Action.IGNORE); - for (Id serviceModelSubElementId : - serviceModel.get().getSubElements().stream() - .map(ElementInfo::getId) - .collect(Collectors.toSet())) { - ElementInfo serviceModelSubElementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, serviceModelSubElementId) - .orElseThrow(() -> new IllegalStateException(String.format( - "Element %s declared as sub element of element %s (%s) does not exist", - serviceModelSubElementId.getValue(), - serviceModel.get().getId().getValue(), - elementType.name()))); - - if (ElementType.Templates.name().equals(serviceModelSubElementInfo.getInfo().getName()) - || ElementType.Artifacts.name().equals(serviceModelSubElementInfo.getInfo().getName())) { - ZusammenElement serviceModelSubElement = - buildElement(serviceModelSubElementId, Action.IGNORE); - serviceModelSubElement.setSubElements(serviceModelSubElementInfo.getSubElements().stream() - .map(elementInfo -> buildElement(elementInfo.getId(), Action.DELETE)) - .collect(Collectors.toSet())); - serviceModelElement.addSubElement(serviceModelSubElement); - } + @Override + public ServiceElement getServiceModelInfo(String vspId, Version version, String name) { + return null; } - zusammenAdaptor.saveElement(context, elementContext, serviceModelElement, - String.format("Delete content of Templates and Artifacts of %s", elementType.name())); - - logger.info("Finished deleting content of Templates and Artifacts of {} of vsp {} version {}", - elementType.name(), vspId, version.getId()); - } - - @Override - public void overrideServiceModel(String vspId, - Version version, - ToscaServiceModel serviceModel) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional origServiceModel = getServiceModelElementInfo(context, elementContext); - if (!origServiceModel.isPresent()) { - return; + @Override + public void deleteAll(String vspId, Version version) { + logger.info("Started deleting content of Templates and Artifacts of {} of vsp {} version {}", elementType.name(), vspId, version.getId()); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional serviceModel = getServiceModelElementInfo(context, elementContext); + if (!serviceModel.isPresent()) { + logger.info("{} of vsp {} version {} does not exist - nothing to delete", elementType.name(), vspId, version.getId()); + return; + } + ZusammenElement serviceModelElement = buildElement(serviceModel.get().getId(), Action.IGNORE); + for (Id serviceModelSubElementId : serviceModel.get().getSubElements().stream().map(ElementInfo::getId).collect(Collectors.toSet())) { + ElementInfo serviceModelSubElementInfo = zusammenAdaptor.getElementInfo(context, elementContext, serviceModelSubElementId).orElseThrow( + () -> new IllegalStateException(String + .format("Element %s declared as sub element of element %s (%s) does not exist", serviceModelSubElementId.getValue(), + serviceModel.get().getId().getValue(), elementType.name()))); + if (ElementType.Templates.name().equals(serviceModelSubElementInfo.getInfo().getName()) || ElementType.Artifacts.name() + .equals(serviceModelSubElementInfo.getInfo().getName())) { + ZusammenElement serviceModelSubElement = buildElement(serviceModelSubElementId, Action.IGNORE); + serviceModelSubElement.setSubElements( + serviceModelSubElementInfo.getSubElements().stream().map(elementInfo -> buildElement(elementInfo.getId(), Action.DELETE)) + .collect(Collectors.toSet())); + serviceModelElement.addSubElement(serviceModelSubElement); + } + } + zusammenAdaptor.saveElement(context, elementContext, serviceModelElement, + String.format("Delete content of Templates and Artifacts of %s", elementType.name())); + logger.info("Finished deleting content of Templates and Artifacts of {} of vsp {} version {}", elementType.name(), vspId, version.getId()); } - Id serviceModelElementId = origServiceModel.get().getId(); - - ZusammenElement serviceModelElement = buildServiceModelElement(serviceModel.getEntryDefinitionServiceTemplate()); - serviceModelElement.setElementId(serviceModelElementId); - - overrideServiceTemplates(serviceModelElementId, serviceModel, context, elementContext, serviceModelElement); - zusammenAdaptor.saveElement(context, elementContext, serviceModelElement, "Override service model"); - } - - - private void overrideServiceTemplates(Id serviceModelElementId, - ToscaServiceModel serviceModel, - SessionContext context, - ElementContext elementContext, - ZusammenElement serviceModelElement) { - Optional elementInfo = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, ElementType.Templates.name()); - if (!elementInfo.isPresent()) { - return; + @Override + public void overrideServiceModel(String vspId, Version version, ToscaServiceModel serviceModel) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional origServiceModel = getServiceModelElementInfo(context, elementContext); + if (!origServiceModel.isPresent()) { + return; + } + Id serviceModelElementId = origServiceModel.get().getId(); + ZusammenElement serviceModelElement = buildServiceModelElement(serviceModel.getEntryDefinitionServiceTemplate()); + serviceModelElement.setElementId(serviceModelElementId); + overrideServiceTemplates(serviceModelElementId, serviceModel, context, elementContext, serviceModelElement); + zusammenAdaptor.saveElement(context, elementContext, serviceModelElement, "Override service model"); } - ZusammenElement templateElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); - templateElement.setElementId(elementInfo.get().getId()); - serviceModel.getServiceTemplates().forEach((templateName, serviceTemplate) -> templateElement.addSubElement( - buildServiceTemplateElement(templateName, serviceTemplate, - serviceModel.getEntryDefinitionServiceTemplate(), Action.UPDATE))); - serviceModelElement.addSubElement(templateElement); - } - - private Optional getServiceModelElementInfo(SessionContext context, - ElementContext elementContext) { - Collection vspModelSubs = zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); - - return vspModelSubs.stream() - .filter(elementInfo -> elementInfo.getInfo() != null - && elementType.name().equals(elementInfo.getInfo().getName())) - .findFirst(); - } - private Map getTemplates(SessionContext context, - ElementContext elementContext, - Id serviceModelElementId) { - Optional templatesElementInfo = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, ElementType.Templates.name()); - - if (templatesElementInfo.isPresent()) { - Collection elements = zusammenAdaptor.listElementData(context, elementContext, - templatesElementInfo.get().getId()); - - return elements.stream().collect(Collectors.toMap( - element -> element.getInfo().getName(), - this::elementToServiceTemplate)); + private void overrideServiceTemplates(Id serviceModelElementId, ToscaServiceModel serviceModel, SessionContext context, + ElementContext elementContext, ZusammenElement serviceModelElement) { + Optional elementInfo = zusammenAdaptor + .getElementInfoByName(context, elementContext, serviceModelElementId, ElementType.Templates.name()); + if (!elementInfo.isPresent()) { + return; + } + ZusammenElement templateElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); + templateElement.setElementId(elementInfo.get().getId()); + serviceModel.getServiceTemplates().forEach((templateName, serviceTemplate) -> templateElement.addSubElement( + buildServiceTemplateElement(templateName, serviceTemplate, serviceModel.getEntryDefinitionServiceTemplate(), Action.UPDATE))); + serviceModelElement.addSubElement(templateElement); } - return null; - } - - private FileContentHandler getArtifacts(SessionContext context, ElementContext elementContext, - Id serviceModelElementId) { - Optional artifactsElement = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, ElementType.Artifacts.name()); - if (artifactsElement.isPresent()) { - - Collection elements = zusammenAdaptor.listElementData(context, elementContext, - artifactsElement.get().getId()); - FileContentHandler fileContentHandler = new FileContentHandler(); - elements.forEach(element -> fileContentHandler.addFile(element.getInfo().getName(), - element.getData())); - return fileContentHandler; + private Optional getServiceModelElementInfo(SessionContext context, ElementContext elementContext) { + Collection vspModelSubs = zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + return vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null && elementType.name().equals(elementInfo.getInfo().getName())).findFirst(); } - return null; - } - - private ZusammenElement buildServiceModelElement(String entryDefinitionServiceTemplate) { - ZusammenElement serviceModelElement = buildStructuralElement(elementType, Action.UPDATE); - serviceModelElement.getInfo().addProperty(BASE_PROPERTY, entryDefinitionServiceTemplate); - return serviceModelElement; - } + private Map getTemplates(SessionContext context, ElementContext elementContext, Id serviceModelElementId) { + Optional templatesElementInfo = zusammenAdaptor + .getElementInfoByName(context, elementContext, serviceModelElementId, ElementType.Templates.name()); + if (templatesElementInfo.isPresent()) { + Collection elements = zusammenAdaptor.listElementData(context, elementContext, templatesElementInfo.get().getId()); + return elements.stream().collect(Collectors.toMap(element -> element.getInfo().getName(), this::elementToServiceTemplate)); + } + return null; + } - private Element buildServiceTemplateElement(String name, ServiceTemplate serviceTemplate, - String entryDefinitionServiceTemplate, - Action action) { - ZusammenElement zusammenElement = buildElement(null, action); - Info info = new Info(); - info.setName(name); - info.setDescription(serviceTemplate.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.ServiceTemplate.name()); - info.addProperty(BASE_PROPERTY, entryDefinitionServiceTemplate); - String yaml = new ToscaExtensionYamlUtil().objectToYaml(serviceTemplate); - zusammenElement.setData(new ByteArrayInputStream(yaml.getBytes())); - zusammenElement.setInfo(info); - return zusammenElement; - } + private FileContentHandler getArtifacts(SessionContext context, ElementContext elementContext, Id serviceModelElementId) { + Optional artifactsElement = zusammenAdaptor + .getElementInfoByName(context, elementContext, serviceModelElementId, ElementType.Artifacts.name()); + if (artifactsElement.isPresent()) { + Collection elements = zusammenAdaptor.listElementData(context, elementContext, artifactsElement.get().getId()); + FileContentHandler fileContentHandler = new FileContentHandler(); + elements.forEach(element -> fileContentHandler.addFile(element.getInfo().getName(), element.getData())); + return fileContentHandler; + } + return null; + } - protected ZusammenElement buildArtifactElement(String name, byte[] artifact, Action action) { - ZusammenElement artifactElement = buildElement(null, action); - Info info = new Info(); - info.setName(name); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Artifact.name()); - artifactElement.setInfo(info); - artifactElement.setData(new ByteArrayInputStream(artifact)); + private ZusammenElement buildServiceModelElement(String entryDefinitionServiceTemplate) { + ZusammenElement serviceModelElement = buildStructuralElement(elementType, Action.UPDATE); + serviceModelElement.getInfo().addProperty(BASE_PROPERTY, entryDefinitionServiceTemplate); + return serviceModelElement; + } - return artifactElement; - } + private Element buildServiceTemplateElement(String name, ServiceTemplate serviceTemplate, String entryDefinitionServiceTemplate, Action action) { + ZusammenElement zusammenElement = buildElement(null, action); + Info info = new Info(); + info.setName(name); + info.setDescription(serviceTemplate.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.ServiceTemplate.name()); + info.addProperty(BASE_PROPERTY, entryDefinitionServiceTemplate); + String yaml = new ToscaExtensionYamlUtil().objectToYaml(serviceTemplate); + zusammenElement.setData(new ByteArrayInputStream(yaml.getBytes())); + zusammenElement.setInfo(info); + return zusammenElement; + } + protected ZusammenElement buildArtifactElement(String name, byte[] artifact, Action action) { + ZusammenElement artifactElement = buildElement(null, action); + Info info = new Info(); + info.setName(name); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Artifact.name()); + artifactElement.setInfo(info); + artifactElement.setData(new ByteArrayInputStream(artifact)); + return artifactElement; + } - private ServiceTemplate elementToServiceTemplate(Element element) { - try { - String yamlContent = IOUtils.toString(element.getData()); - return new ToscaExtensionYamlUtil(). - yamlToObject(yamlContent, ServiceTemplate.class); - } catch (Exception e) { - throw new CoreException( - new RetrieveServiceTemplateFromDbErrorBuilder( - element.getInfo().getName(), e.getMessage()).build()); + private ServiceTemplate elementToServiceTemplate(Element element) { + try { + String yamlContent = IOUtils.toString(element.getData()); + return new ToscaExtensionYamlUtil().yamlToObject(yamlContent, ServiceTemplate.class); + } catch (Exception e) { + throw new CoreException(new RetrieveServiceTemplateFromDbErrorBuilder(element.getInfo().getName(), e.getMessage()).build()); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/StructureElement.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/StructureElement.java index a0bbdfce8d..b894db9b93 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/StructureElement.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/StructureElement.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.model.impl.zusammen; -public enum StructureElement { - ServiceModel, - EnrichedServiceModel, - Artifacts, - Templates, - EntryDefinition, - -} +public enum StructureElement {ServiceModel, EnrichedServiceModel, Artifacts, Templates, EntryDefinition,} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java index fb8f3ce0ef..2ece29bdcb 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java @@ -26,5 +26,6 @@ import java.util.List; * @since July 09, 2017 */ public interface DestinationProvider { + List getSubscribers(); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java index f0bf7e8874..38603f8ac7 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.dao; +import java.util.UUID; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; -import java.util.UUID; - public interface LastNotificationDao extends BaseDao { - UUID getOwnerLastEventId(String ownerId); - - void persistOwnerLastEventId(String ownerId, UUID eventId); + UUID getOwnerLastEventId(String ownerId); + void persistOwnerLastEventId(String ownerId, UUID eventId); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java index 6542d70158..111cfa699d 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.dao; -import org.openecomp.core.dao.BaseDao; -import org.openecomp.sdc.notification.dao.types.NotificationEntity; -import org.openecomp.sdc.notification.dtos.NotificationsStatus; - import java.util.Collection; import java.util.List; import java.util.UUID; - +import org.openecomp.core.dao.BaseDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; public interface NotificationsDao extends BaseDao { @@ -43,7 +40,7 @@ public interface NotificationsDao extends BaseDao { NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn, UUID prevLastNotification); - void markNotificationAsRead(String ownerId, Collection eventIds); + void markNotificationAsRead(String ownerId, Collection eventIds); void createBatch(List notificationEntities); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java index 3daf165efc..d0c16e6e7c 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java @@ -17,15 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.dao; +import java.util.Set; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.notification.dao.types.SubscribersEntity; -import java.util.Set; - - public interface SubscribersDao extends BaseDao { void subscribe(String ownerId, String entityId); @@ -33,5 +30,4 @@ public interface SubscribersDao extends BaseDao { void unsubscribe(String ownerId, String entityId); Set getSubscribers(String entityId); - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java index 97aba63f1c..a09d687c5a 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java @@ -13,19 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.notification.dao.types; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.util.UUID; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; -import lombok.ToString; @Data @AllArgsConstructor @@ -34,11 +30,9 @@ import lombok.ToString; public class LastSeenNotificationEntity { public static final String ENTITY_TYPE = "Event Notification"; - @PartitionKey @Column(name = "owner_id") private String ownerId; - @Column(name = "event_id") private UUID lastEventId; } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java index b45a2a0c7d..a8d631512c 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java @@ -13,16 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.notification.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.util.UUID; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -34,24 +31,18 @@ import lombok.NoArgsConstructor; public class NotificationEntity { public static final String ENTITY_TYPE = "Event Notification"; - @PartitionKey @Column(name = "owner_id") private String ownerId; - @Column(name = "read") private boolean read; - @ClusteringColumn @Column(name = "event_id") private UUID eventId; - @Column(name = "event_type") private String eventType; - @Column(name = "event_attributes") private String eventAttributes; - @Column(name = "originator_id") private String originatorId; diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java index b1b80cd135..248c82974e 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java @@ -13,15 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.notification.dao.types; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.util.Set; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -35,7 +32,6 @@ public class SubscribersEntity { @PartitionKey @Column(name = "entity_id") private String entityId; - @Column(name = "subscribers") private Set subscribers; } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java index 7532ab9218..152b7b72e7 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java @@ -19,10 +19,9 @@ */ package org.openecomp.sdc.notification.dtos; -import org.openecomp.sdc.notification.dao.types.NotificationEntity; - import java.util.List; import java.util.UUID; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; /** * @author Avrahamg @@ -30,14 +29,13 @@ import java.util.UUID; */ public interface NotificationsStatus { - List getNotifications(); - - List getNewEntries(); + List getNotifications(); - UUID getLastScanned(); + List getNewEntries(); - UUID getEndOfPage(); + UUID getLastScanned(); - long getNumOfNotSeenNotifications(); + UUID getEndOfPage(); + long getNumOfNotSeenNotifications(); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java index cb3b8a4b07..7ac7bf81ec 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java @@ -24,12 +24,13 @@ package org.openecomp.sdc.notification.exceptons; * @since July 02, 2017 */ public class NotificationNotExistException extends Exception { - private String message; + private String message; - public NotificationNotExistException(String Message){ + public NotificationNotExistException(String Message) { this(Message, null); } + public NotificationNotExistException(String message, Throwable cause) { super(cause); this.message = message; diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java index 6e6f9f063a..26415de8a0 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.notification.dao.LastNotificationDao; - public abstract class LastNotificationDaoFactory extends AbstractComponentFactory { - public static LastNotificationDaoFactory getInstance() { - return AbstractFactory.getInstance(LastNotificationDaoFactory.class); - } - + public static LastNotificationDaoFactory getInstance() { + return AbstractFactory.getInstance(LastNotificationDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java index 134920635e..9286dc700f 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java @@ -25,10 +25,7 @@ import org.openecomp.sdc.notification.services.NotificationPropagationManager; public abstract class NotificationPropagationManagerFactory extends AbstractComponentFactory { - public static NotificationPropagationManagerFactory getInstance() { return AbstractFactory.getInstance(NotificationPropagationManagerFactory.class); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java index 341af7e296..82c7ba15b3 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.notification.dao.NotificationsDao; - public abstract class NotificationsDaoFactory extends AbstractComponentFactory { - public static NotificationsDaoFactory getInstance() { - return AbstractFactory.getInstance(NotificationsDaoFactory.class); - } - + public static NotificationsDaoFactory getInstance() { + return AbstractFactory.getInstance(NotificationsDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java index eab26188c1..2b94de31f6 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.notification.services.NotificationsService; - public abstract class NotificationsServiceFactory extends AbstractComponentFactory { - public static NotificationsServiceFactory getInstance() { - return AbstractFactory.getInstance(NotificationsServiceFactory.class); - } - + public static NotificationsServiceFactory getInstance() { + return AbstractFactory.getInstance(NotificationsServiceFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java index 7a20e985e3..0859f45db5 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java @@ -25,10 +25,7 @@ import org.openecomp.sdc.notification.services.PropagationService; public abstract class PropagationServiceFactory extends AbstractComponentFactory { - public static PropagationServiceFactory getInstance() { return AbstractFactory.getInstance(PropagationServiceFactory.class); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java index 33b62e2f5d..07cbd8cbd9 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.notification.dao.SubscribersDao; - public abstract class SubscribersDaoFactory extends AbstractComponentFactory { public static SubscribersDaoFactory getInstance() { return AbstractFactory.getInstance(SubscribersDaoFactory.class); } - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java index 3e789c22a7..26b045f27a 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.notification.services.SubscriptionService; - public abstract class SubscriptionServiceFactory extends AbstractComponentFactory { public static SubscriptionServiceFactory getInstance() { return AbstractFactory.getInstance(SubscriptionServiceFactory.class); } - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java index 9912990084..6fa9e52dc0 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java @@ -26,6 +26,8 @@ import org.openecomp.sdc.notification.dtos.Event; * @since July 09, 2017 */ public interface NotificationPropagationManager { - void notifySubscribers(Event event, String ... excludedSubscribers); + + void notifySubscribers(Event event, String... excludedSubscribers); + void directNotification(Event event, String destinationId); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java index 9990f6dc2e..aca8eacde3 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java @@ -19,32 +19,30 @@ */ package org.openecomp.sdc.notification.services; +import java.util.List; +import java.util.UUID; import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; import org.openecomp.sdc.notification.dao.types.NotificationEntity; import org.openecomp.sdc.notification.dtos.NotificationsStatus; import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; -import java.util.List; -import java.util.UUID; - /** * @author Avrahamg * @since June 22, 2017 */ public interface NotificationsService { - LastSeenNotificationEntity getLastNotification(String ownerId); + LastSeenNotificationEntity getLastNotification(String ownerId); - NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage); + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage); - void updateLastSeenNotification(String ownerId, UUID eventId); + void updateLastSeenNotification(String ownerId, UUID eventId); - void markAsRead(String ownerId, String notificationId) throws NotificationNotExistException; + void markAsRead(String ownerId, String notificationId) throws NotificationNotExistException; List getNotificationsByOwnerId(String ownerId, int limit); List getNewNotificationsByOwnerId(String ownerId, UUID eventId); List getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit); - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java index a0b1721796..35aa5c6924 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java @@ -26,6 +26,7 @@ import java.util.Set; * @since July 09, 2017 */ public interface SubscriptionService { + void subscribe(String ownerId, String entityId); void unsubscribe(String ownerId, String entityId); diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java index b2a0a9ad03..0a5bca6cf8 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.destinationprovider.impl; -import org.apache.commons.lang3.ArrayUtils; -import org.openecomp.sdc.destinationprovider.DestinationProvider; -import org.openecomp.sdc.notification.services.SubscriptionService; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; +import org.apache.commons.lang3.ArrayUtils; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.services.SubscriptionService; /** * @author avrahamg @@ -39,8 +37,7 @@ public class MulticastDestination implements DestinationProvider { private SubscriptionService subscriptionService; private String[] excludedSubscribers; - public MulticastDestination(String entityId, SubscriptionService subscriptionService, - String... excludedSubscribers) { + public MulticastDestination(String entityId, SubscriptionService subscriptionService, String... excludedSubscribers) { this.entityId = entityId; this.excludedSubscribers = excludedSubscribers; this.subscriptionService = subscriptionService; diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java index 2f4cc795e2..8485efdcef 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.destinationprovider.impl; -import org.openecomp.sdc.destinationprovider.DestinationProvider; - import java.util.Collections; import java.util.List; +import org.openecomp.sdc.destinationprovider.DestinationProvider; /** * @author avrahamg diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java index 0bfd6a314d..fa4481b881 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.dao.impl; import com.datastax.driver.core.ResultSet; @@ -26,62 +25,57 @@ import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.Collection; +import java.util.UUID; import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.notification.dao.LastNotificationDao; import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; -import java.util.Collection; -import java.util.UUID; - - public class LastNotificationDaoCassandraImpl extends CassandraBaseDao implements LastNotificationDao { - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(LastSeenNotificationEntity.class); - private static final LastNotificationAccessor accessor = - noSqlDb.getMappingManager().createAccessor(LastNotificationAccessor.class); - - @Override - protected Mapper getMapper() { - return mapper; - } - - @Override - protected Object[] getKeys(LastSeenNotificationEntity entity) { - return new Object[]{entity.getOwnerId()}; - } - - @Override - public Collection list(LastSeenNotificationEntity entity) { - return accessor.list(entity.getOwnerId()).all(); - } - - @Override - public UUID getOwnerLastEventId(String ownerId) { - ResultSet ownerLastEventId = accessor.getOwnerLastEventId(ownerId); - Row one = ownerLastEventId.one(); - return one != null ? one.getUUID("event_id") : null; - } - - @Override - public void persistOwnerLastEventId(String ownerId, UUID eventId) { - accessor.updateOwnerLastEventId(eventId, ownerId); - } - - @Accessor - interface LastNotificationAccessor { - - @Query("select * from last_notification where owner_id=?") - Result list(String ownerId); - - @Query("select event_id from last_notification where owner_id=?") - ResultSet getOwnerLastEventId(String ownerId); - - @Query("update last_notification set event_id=? where owner_id=?") - ResultSet updateOwnerLastEventId(UUID eventId, String ownerId); - } - + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper mapper = noSqlDb.getMappingManager().mapper(LastSeenNotificationEntity.class); + private static final LastNotificationAccessor accessor = noSqlDb.getMappingManager().createAccessor(LastNotificationAccessor.class); + + @Override + protected Mapper getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(LastSeenNotificationEntity entity) { + return new Object[]{entity.getOwnerId()}; + } + + @Override + public Collection list(LastSeenNotificationEntity entity) { + return accessor.list(entity.getOwnerId()).all(); + } + + @Override + public UUID getOwnerLastEventId(String ownerId) { + ResultSet ownerLastEventId = accessor.getOwnerLastEventId(ownerId); + Row one = ownerLastEventId.one(); + return one != null ? one.getUUID("event_id") : null; + } + + @Override + public void persistOwnerLastEventId(String ownerId, UUID eventId) { + accessor.updateOwnerLastEventId(eventId, ownerId); + } + + @Accessor + interface LastNotificationAccessor { + + @Query("select * from last_notification where owner_id=?") + Result list(String ownerId); + + @Query("select event_id from last_notification where owner_id=?") + ResultSet getOwnerLastEventId(String ownerId); + + @Query("update last_notification set event_id=? where owner_id=?") + ResultSet updateOwnerLastEventId(UUID eventId, String ownerId); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java index 6796ea11d2..daa8eaf1ea 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java @@ -17,9 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.dao.impl; +import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; + import com.datastax.driver.core.BatchStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Statement; @@ -28,6 +29,13 @@ import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; @@ -35,23 +43,14 @@ import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.notification.dao.NotificationsDao; import org.openecomp.sdc.notification.dao.types.NotificationEntity; import org.openecomp.sdc.notification.dtos.NotificationsStatus; - -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; - //import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; -//import java.util.Optional; -public class NotificationsDaoCassandraImpl extends CassandraBaseDao - implements NotificationsDao { +//import java.util.Optional; +public class NotificationsDaoCassandraImpl extends CassandraBaseDao implements NotificationsDao { private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(NotificationEntity.class); - private static final NotificationsAccessor accessor = - noSqlDb.getMappingManager().createAccessor(NotificationsAccessor.class); + private static final Mapper mapper = noSqlDb.getMappingManager().mapper(NotificationEntity.class); + private static final NotificationsAccessor accessor = noSqlDb.getMappingManager().createAccessor(NotificationsAccessor.class); @Override protected Mapper getMapper() { @@ -75,8 +74,7 @@ public class NotificationsDaoCassandraImpl extends CassandraBaseDao getNewNotificationsByOwnerId(String ownerId, UUID eventId) { - return getNewNotificationsByOwnerId(ownerId, eventId, - DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS); + return getNewNotificationsByOwnerId(ownerId, eventId, DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS); } @Override @@ -94,16 +92,17 @@ public class NotificationsDaoCassandraImpl extends CassandraBaseDao entities = accessor.getNotifications(ownerId, numOfRecordsToReturn).all(); + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + List entities = accessor.getNotifications(ownerId, numOfRecordsToReturn).all(); if (CollectionUtils.isNotEmpty(entities)) { long lastSeen = UUIDs.unixTimestamp(lastScannedEventId); populateNewNotifications(notificationsStatus, entities, lastSeen); UUID firstScannedEventId = entities.get(0).getEventId(); - notificationsStatus.setLastScanned(firstScannedEventId); - notificationsStatus.setNumOfNotSeenNotifications(accessor.getNewNotificationsCount(ownerId, lastScannedEventId, firstScannedEventId).one().getLong(0)); + notificationsStatus.setLastScanned(firstScannedEventId); + notificationsStatus + .setNumOfNotSeenNotifications(accessor.getNewNotificationsCount(ownerId, lastScannedEventId, firstScannedEventId).one().getLong(0)); } - return notificationsStatus; + return notificationsStatus; } private void populateNewNotifications(NotificationsStatusImpl notificationsStatus, List entities, long lastSeen) { @@ -117,66 +116,64 @@ public class NotificationsDaoCassandraImpl extends CassandraBaseDao entities = accessor.getPrevNotifications(ownerId, prevLastScannedEventId, numOfRecordsToReturn).all(); + public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn, + UUID prevLastScannedEventId) { + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + List entities = accessor.getPrevNotifications(ownerId, prevLastScannedEventId, numOfRecordsToReturn).all(); if (CollectionUtils.isNotEmpty(entities)) { - long lastSeen = UUIDs.unixTimestamp(lastSeenNotification); + long lastSeen = UUIDs.unixTimestamp(lastSeenNotification); populateNewNotifications(notificationsStatus, entities, lastSeen); } - return notificationsStatus; + return notificationsStatus; } -/* - @Override - public NotificationsStatus getNotificationsStatus(String ownerId, - LastSeenNotificationEntity lastSeenNotification, - int numOfRecordsToReturn) { - - List notificationEntities = - fetchNewNotifications(lastSeenNotification, numOfRecordsToReturn); - NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); - if (CollectionUtils.isEmpty(notificationEntities)) { - return notificationsStatus; - } - - notificationEntities.forEach(notification -> { - if (isNewNotification(lastSeenNotification, notification)) { - notificationsStatus.addNewNotificationUUID(notification.getEventId()); + /* + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, + LastSeenNotificationEntity lastSeenNotification, + int numOfRecordsToReturn) { + + List notificationEntities = + fetchNewNotifications(lastSeenNotification, numOfRecordsToReturn); + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + if (CollectionUtils.isEmpty(notificationEntities)) { + return notificationsStatus; } - notificationsStatus.addNotification(notification); - }); - Optional latestNotification = notificationEntities.stream().findFirst(); - latestNotification.ifPresent(e -> notificationsStatus.setLastScanned(e.getEventId())); - return notificationsStatus; - } + notificationEntities.forEach(notification -> { + if (isNewNotification(lastSeenNotification, notification)) { + notificationsStatus.addNewNotificationUUID(notification.getEventId()); + } + notificationsStatus.addNotification(notification); + }); - private List fetchNewNotifications( - LastSeenNotificationEntity lastSeenNotification, int numOfRecordsToReturn) { - String ownerId = lastSeenNotification.getOwnerId(); - UUID lastEventId = lastSeenNotification.getLastEventId(); - List newNotificationsByOwnerId = - getNewNotificationsByOwnerId(ownerId, lastEventId); - newNotificationsByOwnerId = fetchMoreIfNeeded(ownerId, newNotificationsByOwnerId, - numOfRecordsToReturn, lastEventId); - return newNotificationsByOwnerId; - } + Optional latestNotification = notificationEntities.stream().findFirst(); + latestNotification.ifPresent(e -> notificationsStatus.setLastScanned(e.getEventId())); + return notificationsStatus; + } - private boolean isNewNotification(LastSeenNotificationEntity lastSeenNotification, - NotificationEntity notification) { - return Objects.isNull(lastSeenNotification.getLastEventId()) || - UUIDs.unixTimestamp(notification.getEventId()) > - UUIDs.unixTimestamp(lastSeenNotification.getLastEventId()); - } -*/ + private List fetchNewNotifications( + LastSeenNotificationEntity lastSeenNotification, int numOfRecordsToReturn) { + String ownerId = lastSeenNotification.getOwnerId(); + UUID lastEventId = lastSeenNotification.getLastEventId(); + List newNotificationsByOwnerId = + getNewNotificationsByOwnerId(ownerId, lastEventId); + newNotificationsByOwnerId = fetchMoreIfNeeded(ownerId, newNotificationsByOwnerId, + numOfRecordsToReturn, lastEventId); + return newNotificationsByOwnerId; + } + private boolean isNewNotification(LastSeenNotificationEntity lastSeenNotification, + NotificationEntity notification) { + return Objects.isNull(lastSeenNotification.getLastEventId()) || + UUIDs.unixTimestamp(notification.getEventId()) > + UUIDs.unixTimestamp(lastSeenNotification.getLastEventId()); + } + */ @Override public void createBatch(List notificationEntities) { BatchStatement batch = new BatchStatement(); - List statements = notificationEntities.stream() - .map(mapper::saveQuery) - .collect(Collectors.toList()); + List statements = notificationEntities.stream().map(mapper::saveQuery).collect(Collectors.toList()); batch.addAll(statements); getSession().execute(batch); } @@ -253,7 +250,6 @@ public class NotificationsDaoCassandraImpl extends CassandraBaseDao fetchMoreIfNeeded(String ownerId, List notificationEntities, @@ -278,5 +274,4 @@ public class NotificationsDaoCassandraImpl extends CassandraBaseDao implements - SubscribersDao { +public class SubscribersDaoCassandraImpl extends CassandraBaseDao implements SubscribersDao { private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(SubscribersEntity.class); - private static final SubscribersAccessor accessor = - noSqlDb.getMappingManager().createAccessor(SubscribersAccessor.class); - + private static final Mapper mapper = noSqlDb.getMappingManager().mapper(SubscribersEntity.class); + private static final SubscribersAccessor accessor = noSqlDb.getMappingManager().createAccessor(SubscribersAccessor.class); @Override protected Object[] getKeys(SubscribersEntity entity) { @@ -100,5 +94,4 @@ public class SubscribersDaoCassandraImpl extends CassandraBaseDao ownerId, String entityId); } - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java index c57cf5b654..8626186787 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.dao.LastNotificationDao; @@ -28,12 +27,12 @@ import org.openecomp.sdc.notification.factories.LastNotificationDaoFactory; * @author itzikpa * @since June 23, 2017 */ - public class LastNotificationDaoFactoryImpl extends LastNotificationDaoFactory { - private static final LastNotificationDao INSTANCE = new LastNotificationDaoCassandraImpl(); - @Override - public LastNotificationDao createInterface() { - return INSTANCE; - } + private static final LastNotificationDao INSTANCE = new LastNotificationDaoCassandraImpl(); + + @Override + public LastNotificationDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java index 7b5ca8055a..c3c606f1d6 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory; @@ -26,11 +25,10 @@ import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; import org.openecomp.sdc.notification.services.NotificationPropagationManager; import org.openecomp.sdc.notification.services.impl.NotificationPropagationManagerImpl; -public class NotificationPropagationManagerFactoryImpl extends - NotificationPropagationManagerFactory { +public class NotificationPropagationManagerFactoryImpl extends NotificationPropagationManagerFactory { + private static final NotificationPropagationManager INSTANCE = new NotificationPropagationManagerImpl( - PropagationServiceFactory.getInstance().createInterface(), SubscriptionServiceFactory - .getInstance().createInterface()); + PropagationServiceFactory.getInstance().createInterface(), SubscriptionServiceFactory.getInstance().createInterface()); @Override public NotificationPropagationManager createInterface() { diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java index 5277dd7c08..d4b4e771a2 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.dao.NotificationsDao; @@ -29,10 +28,11 @@ import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; * @since June 20, 2017 */ public class NotificationsDaoFactoryImpl extends NotificationsDaoFactory { - private static final NotificationsDao INSTANCE = new NotificationsDaoCassandraImpl(); - @Override - public NotificationsDao createInterface() { - return INSTANCE; - } + private static final NotificationsDao INSTANCE = new NotificationsDaoCassandraImpl(); + + @Override + public NotificationsDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java index 30d2b859cf..23d1b2e6ac 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.factories.LastNotificationDaoFactory; @@ -31,12 +30,12 @@ import org.openecomp.sdc.notification.services.impl.NotificationsServiceImpl; * @since June 20, 2017 */ public class NotificationsServiceFactoryImpl extends NotificationsServiceFactory { - private static final NotificationsService INSTANCE = new NotificationsServiceImpl( - LastNotificationDaoFactory.getInstance().createInterface(), NotificationsDaoFactory - .getInstance().createInterface()); - @Override - public NotificationsService createInterface() { - return INSTANCE; - } + private static final NotificationsService INSTANCE = new NotificationsServiceImpl(LastNotificationDaoFactory.getInstance().createInterface(), + NotificationsDaoFactory.getInstance().createInterface()); + + @Override + public NotificationsService createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java index f6b41226a9..47fe559b56 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; @@ -26,8 +25,8 @@ import org.openecomp.sdc.notification.services.PropagationService; import org.openecomp.sdc.notification.services.impl.PropagationServiceImpl; public class PropagationServiceFactoryImpl extends PropagationServiceFactory { - private static final PropagationService INSTANCE = new PropagationServiceImpl( - NotificationsDaoFactory.getInstance().createInterface()); + + private static final PropagationService INSTANCE = new PropagationServiceImpl(NotificationsDaoFactory.getInstance().createInterface()); @Override public PropagationService createInterface() { diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java index ca5ca2df36..a45b2c5a33 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.dao.SubscribersDao; import org.openecomp.sdc.notification.dao.impl.SubscribersDaoCassandraImpl; import org.openecomp.sdc.notification.factories.SubscribersDaoFactory; - public class SubscribersDaoFactoryImpl extends SubscribersDaoFactory { + private static final SubscribersDao INSTANCE = new SubscribersDaoCassandraImpl(); @Override diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java index 1f872499b1..18499a93de 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.factories.impl; import org.openecomp.sdc.notification.factories.SubscribersDaoFactory; @@ -25,10 +24,9 @@ import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; import org.openecomp.sdc.notification.services.SubscriptionService; import org.openecomp.sdc.notification.services.impl.SubscriptionServiceImpl; - public class SubscriptionServiceFactoryImpl extends SubscriptionServiceFactory { - private static final SubscriptionService INSTANCE = new SubscriptionServiceImpl - (SubscribersDaoFactory.getInstance().createInterface()); + + private static final SubscriptionService INSTANCE = new SubscriptionServiceImpl(SubscribersDaoFactory.getInstance().createInterface()); @Override public SubscriptionService createInterface() { diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java index 9795c7bd1a..d817f1798c 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.services.impl; import org.openecomp.sdc.destinationprovider.impl.MulticastDestination; @@ -36,16 +35,14 @@ public class NotificationPropagationManagerImpl implements NotificationPropagati private PropagationService propagationService; private SubscriptionService subscriptionService; - public NotificationPropagationManagerImpl(PropagationService propagationService, - SubscriptionService subscriptionService) { + public NotificationPropagationManagerImpl(PropagationService propagationService, SubscriptionService subscriptionService) { this.propagationService = propagationService; this.subscriptionService = subscriptionService; } @Override - public void notifySubscribers(Event event, String ... excludedSubscribers) { - propagationService.notify(event, new MulticastDestination(event.getEntityId(), - subscriptionService, excludedSubscribers)); + public void notifySubscribers(Event event, String... excludedSubscribers) { + propagationService.notify(event, new MulticastDestination(event.getEntityId(), subscriptionService, excludedSubscribers)); } @Override diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java index d3558d1904..0b5161ff63 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.services.impl; +import java.util.List; +import java.util.Objects; +import java.util.UUID; import org.openecomp.sdc.notification.dao.LastNotificationDao; import org.openecomp.sdc.notification.dao.NotificationsDao; import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; @@ -28,10 +30,6 @@ import org.openecomp.sdc.notification.dtos.NotificationsStatus; import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; import org.openecomp.sdc.notification.services.NotificationsService; -import java.util.List; -import java.util.Objects; -import java.util.UUID; - /** * @author Avrahamg * @since June 26, 2017 @@ -41,54 +39,46 @@ public class NotificationsServiceImpl implements NotificationsService { private LastNotificationDao lastNotificationDao; private NotificationsDao notificationsDao; - public NotificationsServiceImpl(LastNotificationDao lastNotificationDao, - NotificationsDao notificationsDao) { + public NotificationsServiceImpl(LastNotificationDao lastNotificationDao, NotificationsDao notificationsDao) { this.lastNotificationDao = lastNotificationDao; this.notificationsDao = notificationsDao; } @Override public LastSeenNotificationEntity getLastNotification(String ownerId) { - return new LastSeenNotificationEntity(ownerId, - lastNotificationDao.getOwnerLastEventId(ownerId)); + return new LastSeenNotificationEntity(ownerId, lastNotificationDao.getOwnerLastEventId(ownerId)); } @Override - public void updateLastSeenNotification(String ownerId, UUID eventId) - { + public void updateLastSeenNotification(String ownerId, UUID eventId) { lastNotificationDao.persistOwnerLastEventId(ownerId, eventId); } @Override public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage) { - if (Objects.isNull(lastDelivered)) { - LastSeenNotificationEntity entity = getLastNotification(ownerId); - if (Objects.nonNull(entity)) { - lastDelivered = entity.getLastEventId(); - } - if (Objects.isNull(lastDelivered)) { - lastDelivered = UUID.fromString("00000000-0000-1000-8080-808080808080"); // Lowest time UUID value - } - } - if (Objects.isNull(endOfPage)) { - // First page - return notificationsDao.getNotificationsStatus(ownerId, lastDelivered, numOfRecordsToReturn); - } - else { - // Next page + if (Objects.isNull(lastDelivered)) { + LastSeenNotificationEntity entity = getLastNotification(ownerId); + if (Objects.nonNull(entity)) { + lastDelivered = entity.getLastEventId(); + } + if (Objects.isNull(lastDelivered)) { + lastDelivered = UUID.fromString("00000000-0000-1000-8080-808080808080"); // Lowest time UUID value + } + } + if (Objects.isNull(endOfPage)) { + // First page + return notificationsDao.getNotificationsStatus(ownerId, lastDelivered, numOfRecordsToReturn); + } else { + // Next page return notificationsDao.getNotificationsStatus(ownerId, lastDelivered, numOfRecordsToReturn, endOfPage); - } + } } @Override - public void markAsRead(String ownerId, String notificationId) throws - NotificationNotExistException { - NotificationEntity notificationEntity = - notificationsDao.get(new NotificationEntity(ownerId, UUID.fromString(notificationId))); + public void markAsRead(String ownerId, String notificationId) throws NotificationNotExistException { + NotificationEntity notificationEntity = notificationsDao.get(new NotificationEntity(ownerId, UUID.fromString(notificationId))); if (Objects.isNull(notificationEntity)) { - throw new NotificationNotExistException( - "Notification '" + notificationId + "' is not related to ownerId" + - " '" + ownerId + "'"); + throw new NotificationNotExistException("Notification '" + notificationId + "' is not related to ownerId" + " '" + ownerId + "'"); } notificationEntity.setRead(true); notificationsDao.update(notificationEntity); @@ -96,17 +86,16 @@ public class NotificationsServiceImpl implements NotificationsService { @Override public List getNotificationsByOwnerId(String ownerId, int limit) { - return notificationsDao.getNotificationsByOwnerId(ownerId, limit); + return notificationsDao.getNotificationsByOwnerId(ownerId, limit); } @Override public List getNewNotificationsByOwnerId(String ownerId, UUID eventId) { - return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId); + return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId); } @Override public List getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit) { - return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId, limit); + return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId, limit); } - } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java index 99d35b3726..de6880c46c 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java @@ -17,10 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.services.impl; +import static java.util.Objects.requireNonNull; + import com.datastax.driver.core.utils.UUIDs; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.destinationprovider.DestinationProvider; @@ -29,13 +34,6 @@ import org.openecomp.sdc.notification.dao.types.NotificationEntity; import org.openecomp.sdc.notification.dtos.Event; import org.openecomp.sdc.notification.services.PropagationService; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -import static java.util.Objects.requireNonNull; - public class PropagationServiceImpl implements PropagationService { private NotificationsDao notificationsDao; @@ -44,7 +42,6 @@ public class PropagationServiceImpl implements PropagationService { this.notificationsDao = notificationsDao; } - @Override public void notify(Event event, DestinationProvider destinationProvider) { requireNonNull(event.getEventType()); @@ -53,26 +50,21 @@ public class PropagationServiceImpl implements PropagationService { if (CollectionUtils.isEmpty(subscribers)) { return; } - List notificationEntities = subscribers.stream().map( - subscriber -> { - UUID eventId = UUIDs.timeBased(); - return createNotificationEntity(event.getEventType(), subscriber, - event.getOriginatorId(), event.getAttributes(), eventId); - }).collect(Collectors.toList()); - if(CollectionUtils.isNotEmpty(notificationEntities)) { + List notificationEntities = subscribers.stream().map(subscriber -> { + UUID eventId = UUIDs.timeBased(); + return createNotificationEntity(event.getEventType(), subscriber, event.getOriginatorId(), event.getAttributes(), eventId); + }).collect(Collectors.toList()); + if (CollectionUtils.isNotEmpty(notificationEntities)) { notificationsDao.createBatch(notificationEntities); } } - private NotificationEntity createNotificationEntity(String eventType, String subscriber, - String originatorId, - Map attributes, + private NotificationEntity createNotificationEntity(String eventType, String subscriber, String originatorId, Map attributes, UUID eventId) { - NotificationEntity notificationEntity = - new NotificationEntity(subscriber, eventId, eventType, originatorId); + NotificationEntity notificationEntity = new NotificationEntity(subscriber, eventId, eventType, originatorId); if (attributes != null && !attributes.isEmpty()) { notificationEntity.setEventAttributes(JsonUtil.object2Json(attributes)); } return notificationEntity; } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java index 2a12463fae..dbbbf43177 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.services.impl; +import java.util.Set; import org.openecomp.sdc.notification.dao.SubscribersDao; import org.openecomp.sdc.notification.services.SubscriptionService; -import java.util.Set; - public class SubscriptionServiceImpl implements SubscriptionService { private SubscribersDao subscribersDao; @@ -47,4 +45,4 @@ public class SubscriptionServiceImpl implements SubscriptionService { public Set getSubscribers(String entityId) { return subscribersDao.getSubscribers(entityId); } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java index 1e424631f7..7f21dee9a2 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java @@ -17,10 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.websocket; import com.google.gson.Gson; +import java.io.IOException; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.notification.types.NotificationsStatusDto; @@ -31,100 +35,81 @@ import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; -import java.io.IOException; -import java.util.Objects; -import java.util.Optional; -import java.util.UUID; -import java.util.function.Consumer; - public class NotificationWebsocketHandler extends TextWebSocketHandler { - private static final String USER_ID_HEADER_PARAM = "USER_ID"; - private static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; - private static final String COOKIE = "Cookie"; - private static Logger LOGGER = LoggerFactory.getLogger(NotificationWebsocketHandler.class); - private NotificationWorker worker; + private static final String USER_ID_HEADER_PARAM = "USER_ID"; + private static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; + private static final String COOKIE = "Cookie"; + private static Logger LOGGER = LoggerFactory.getLogger(NotificationWebsocketHandler.class); + private NotificationWorker worker; - public NotificationWebsocketHandler(NotificationWorker worker) { - super(); - this.worker = Objects.requireNonNull(worker, "NotificationWorker object is not initialized."); - } + public NotificationWebsocketHandler(NotificationWorker worker) { + super(); + this.worker = Objects.requireNonNull(worker, "NotificationWorker object is not initialized."); + } - @Override + @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); - - String ownerId = getOwnerId(session); - if (ownerId == null) { - return; - } - UUID lastDelivered = getLastEventId(session); - - Consumer notesProcessor = (notes) -> notifyReceiver(session, notes); - - worker.register(ownerId, lastDelivered, notesProcessor); + String ownerId = getOwnerId(session); + if (ownerId == null) { + return; + } + UUID lastDelivered = getLastEventId(session); + Consumer notesProcessor = (notes) -> notifyReceiver(session, notes); + worker.register(ownerId, lastDelivered, notesProcessor); } - @Override + @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { - String ownerId = getOwnerId(session); - if (ownerId != null) { - worker.unregister(ownerId); - } - super.afterConnectionClosed(session, status); + String ownerId = getOwnerId(session); + if (ownerId != null) { + worker.unregister(ownerId); + } + super.afterConnectionClosed(session, status); } - private void notifyReceiver(WebSocketSession session, NotificationsStatusDto notificationsStatusDto) { - - try { - session.sendMessage(new TextMessage(new Gson().toJson(notificationsStatusDto))); - } catch (IOException e) { - LOGGER.error("IO Exception during Receiver notification.", e); - } - } + private void notifyReceiver(WebSocketSession session, NotificationsStatusDto notificationsStatusDto) { + try { + session.sendMessage(new TextMessage(new Gson().toJson(notificationsStatusDto))); + } catch (IOException e) { + LOGGER.error("IO Exception during Receiver notification.", e); + } + } private String getOwnerId(WebSocketSession session) { - HttpHeaders handshakeHeaders = session.getHandshakeHeaders(); if (handshakeHeaders.containsKey(COOKIE)) { - String[] cookies = handshakeHeaders.get(COOKIE).get(0).split("; "); - Optional cookie = extractValue(cookies, USER_ID_HEADER_PARAM); - if (cookie.isPresent()) { - return cookie.get(); - } - } - - LOGGER.error("No " + USER_ID_HEADER_PARAM + " specified in the session cookies."); - return null; + String[] cookies = handshakeHeaders.get(COOKIE).get(0).split("; "); + Optional cookie = extractValue(cookies, USER_ID_HEADER_PARAM); + if (cookie.isPresent()) { + return cookie.get(); + } + } + LOGGER.error("No " + USER_ID_HEADER_PARAM + " specified in the session cookies."); + return null; } private UUID getLastEventId(WebSocketSession session) { - String uriQuery = session.getUri().getQuery(); if (uriQuery != null) { - String[] queries = uriQuery.split("; "); Optional paramValue = extractValue(queries, LAST_DELIVERED_QUERY_PARAM); if (paramValue.isPresent()) { return UUID.fromString(paramValue.get()); } } - LOGGER.warn("No " + LAST_DELIVERED_QUERY_PARAM + " specified in the request URI."); return null; } - private Optional extractValue(String[] pairs, String name) { - - for (String nameValuePair : pairs) { - + private Optional extractValue(String[] pairs, String name) { + for (String nameValuePair : pairs) { String[] value = nameValuePair.split("="); if (value[0].equals(name)) { return Optional.of(value[1]); } } - - return Optional.empty(); - } - + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java index c016a4797f..e597de0f20 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java @@ -17,96 +17,76 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.config; -import org.onap.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.BiConsumer; +import org.onap.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; public class ConfigurationManager { private static final String CONFIGURATION_YAML_FILE = "onboarding_configuration.yaml"; private static final String NOTIFICATIONS_CONFIG = "notifications"; - - private LinkedHashMap notificationsConfiguration; private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class); private static final ConfigurationManager SINGLETON = new ConfigurationManager(); - - public static ConfigurationManager getInstance() { - return SINGLETON; - } + private LinkedHashMap notificationsConfiguration; private ConfigurationManager() { initConfiguration(); } - private void initConfiguration() { + public static ConfigurationManager getInstance() { + return SINGLETON; + } + private void initConfiguration() { YamlUtil yamlUtil = new YamlUtil(); readConfigurationFromStream(yamlUtil, (filename, stream) -> { - if (stream == null) { LOGGER.warn("Configuration not found: " + filename + ". Using defaults"); return; } - Map> configurationMap = yamlUtil.yamlToMap(stream); if (configurationMap == null) { LOGGER.warn("Configuration cannot be parsed: " + filename + ". Using defaults"); return; } - notificationsConfiguration = configurationMap.get(NOTIFICATIONS_CONFIG); if (notificationsConfiguration == null) { - LOGGER.error(NOTIFICATIONS_CONFIG + - " is missing in configuration file '" + filename + "'. Using defaults"); + LOGGER.error(NOTIFICATIONS_CONFIG + " is missing in configuration file '" + filename + "'. Using defaults"); } }); } - private void readConfigurationFromStream(YamlUtil yamlUtil, - BiConsumer reader) { - + private void readConfigurationFromStream(YamlUtil yamlUtil, BiConsumer reader) { String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE); - try { - if (configurationYamlFile == null) { - - try (InputStream inputStream = - yamlUtil.loadYamlFileIs("/" + CONFIGURATION_YAML_FILE)) { + try (InputStream inputStream = yamlUtil.loadYamlFileIs("/" + CONFIGURATION_YAML_FILE)) { reader.accept(CONFIGURATION_YAML_FILE, inputStream); } - } else { - try (InputStream inputStream = new FileInputStream(configurationYamlFile)) { reader.accept(configurationYamlFile, inputStream); } } - } catch (IOException e) { LOGGER.error("Failed to read configuration", e); } } public T getConfigValue(String name, T defaultValue) { - Object value = notificationsConfiguration.get(name); - try { return value == null ? defaultValue : (T) value; } catch (ClassCastException e) { - LOGGER.warn(String.format("Failed to read configuration property '%s' as requested type. Using default '%s'", - name, defaultValue), e); + LOGGER.warn(String.format("Failed to read configuration property '%s' as requested type. Using default '%s'", name, defaultValue), e); return defaultValue; } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java index a48b16add6..9e92a2b983 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.types; import java.util.Map; diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java index 7aca3fd63d..c4522c4e04 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.types; import java.util.ArrayList; diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java index 75b9f5c786..8dd64c348b 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.workers; -import org.openecomp.sdc.notification.types.NotificationsStatusDto; - import java.util.UUID; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; public interface NewNotificationsReader { - NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit); + + NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java index 4ce87427aa..e357fda982 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java @@ -17,28 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.workers; -import org.openecomp.sdc.notification.types.NotificationsStatusDto; - import java.util.UUID; import java.util.function.Consumer; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; - +import org.openecomp.sdc.notification.types.NotificationsStatusDto; @Getter @Setter @AllArgsConstructor public class NotificationReceiver { - private String ownerId = null; - private UUID lastEventId = null; - private Consumer notesProcessor = null; + private String ownerId = null; + private UUID lastEventId = null; + private Consumer notesProcessor = null; - NotificationReceiver(String ownerId, Consumer notesProcessor) { - this(ownerId, null, notesProcessor); - } + NotificationReceiver(String ownerId, Consumer notesProcessor) { + this(ownerId, null, notesProcessor); + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java index dce8edb356..c69c4ca524 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java @@ -17,103 +17,91 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.workers; -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.notification.config.ConfigurationManager; -import org.openecomp.sdc.notification.types.NotificationsStatusDto; - import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.notification.config.ConfigurationManager; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; public class NotificationWorker { - private static final int DEFAULT_POLLING_INTERVAL = 2000; - private static final String POLLING_INTERVAL = "pollingIntervalMsec"; - private static final int DEFAULT_SELECTION_LIMIT = 10; - private static final String SELECTION_SIZE = "selectionSize"; - - private static boolean stopRunning = false; - - private int selectionLimit = DEFAULT_SELECTION_LIMIT; - private int pollingSleepInterval = DEFAULT_POLLING_INTERVAL; - - private static final Logger LOGGER = LoggerFactory.getLogger(NotificationWorker.class); - - private static Map activeUsers = new ConcurrentHashMap<>(); - private NewNotificationsReader news = null; - - public NotificationWorker(NewNotificationsReader news) { - ConfigurationManager cm = ConfigurationManager.getInstance(); - pollingSleepInterval = cm.getConfigValue(POLLING_INTERVAL, DEFAULT_POLLING_INTERVAL); - selectionLimit = cm.getConfigValue(SELECTION_SIZE, DEFAULT_SELECTION_LIMIT); - - Objects.requireNonNull(news, "NotificationNews object is not initialized."); - this.news = news; - - NotificationWorker.Poller p = new Poller(); - Thread thread = new Thread(p); - thread.start(); - } - - public Map getActiveUsers() { - return activeUsers; - } - - public class Poller extends Thread { - @Override - public void run() { - try { - while (!stopRunning) { - pollNotifications(); - Thread.sleep(pollingSleepInterval); - } - } - catch (InterruptedException e) { - LOGGER.error("Interrupted Exception during Notification poller launch.", e); - Thread.currentThread().interrupt(); - } - } - - private void pollNotifications() { - - Map currUsers = new HashMap<>(); - currUsers.putAll(getActiveUsers()); - - for (NotificationReceiver receiver : currUsers.values()) { - String ownerId = receiver.getOwnerId(); - UUID eventId = receiver.getLastEventId(); - NotificationsStatusDto status = news.getNewNotifications(ownerId, eventId, selectionLimit); - if(Objects.nonNull(status) && CollectionUtils.isNotEmpty(status.getNotifications())) { - receiver.setLastEventId(status.getLastScanned()); - receiver.getNotesProcessor().accept(status); - } - } - } - - } - - public void register(String ownerId, UUID lastDelivered, Consumer notesProcessor) { - NotificationReceiver receiver = new NotificationReceiver(ownerId, lastDelivered, notesProcessor); - activeUsers.put(ownerId, receiver); - LOGGER.debug("User {} is registered with eventId: {}", ownerId, receiver.getLastEventId()); - } - - public void unregister(String ownerId) { - activeUsers.remove(ownerId); - LOGGER.debug("User {} is unregistered.", ownerId); - } - - public void stopPolling() { - LOGGER.debug("Stop notification polling."); - stopRunning = true; - } - + private static final int DEFAULT_POLLING_INTERVAL = 2000; + private static final String POLLING_INTERVAL = "pollingIntervalMsec"; + private static final int DEFAULT_SELECTION_LIMIT = 10; + private static final String SELECTION_SIZE = "selectionSize"; + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationWorker.class); + private static boolean stopRunning = false; + private static Map activeUsers = new ConcurrentHashMap<>(); + private int selectionLimit = DEFAULT_SELECTION_LIMIT; + private int pollingSleepInterval = DEFAULT_POLLING_INTERVAL; + private NewNotificationsReader news = null; + + public NotificationWorker(NewNotificationsReader news) { + ConfigurationManager cm = ConfigurationManager.getInstance(); + pollingSleepInterval = cm.getConfigValue(POLLING_INTERVAL, DEFAULT_POLLING_INTERVAL); + selectionLimit = cm.getConfigValue(SELECTION_SIZE, DEFAULT_SELECTION_LIMIT); + Objects.requireNonNull(news, "NotificationNews object is not initialized."); + this.news = news; + NotificationWorker.Poller p = new Poller(); + Thread thread = new Thread(p); + thread.start(); + } + + public Map getActiveUsers() { + return activeUsers; + } + + public void register(String ownerId, UUID lastDelivered, Consumer notesProcessor) { + NotificationReceiver receiver = new NotificationReceiver(ownerId, lastDelivered, notesProcessor); + activeUsers.put(ownerId, receiver); + LOGGER.debug("User {} is registered with eventId: {}", ownerId, receiver.getLastEventId()); + } + + public void unregister(String ownerId) { + activeUsers.remove(ownerId); + LOGGER.debug("User {} is unregistered.", ownerId); + } + + public void stopPolling() { + LOGGER.debug("Stop notification polling."); + stopRunning = true; + } + + public class Poller extends Thread { + + @Override + public void run() { + try { + while (!stopRunning) { + pollNotifications(); + Thread.sleep(pollingSleepInterval); + } + } catch (InterruptedException e) { + LOGGER.error("Interrupted Exception during Notification poller launch.", e); + Thread.currentThread().interrupt(); + } + } + + private void pollNotifications() { + Map currUsers = new HashMap<>(); + currUsers.putAll(getActiveUsers()); + for (NotificationReceiver receiver : currUsers.values()) { + String ownerId = receiver.getOwnerId(); + UUID eventId = receiver.getLastEventId(); + NotificationsStatusDto status = news.getNewNotifications(ownerId, eventId, selectionLimit); + if (Objects.nonNull(status) && CollectionUtils.isNotEmpty(status.getNotifications())) { + receiver.setLastEventId(status.getLastScanned()); + receiver.getNotesProcessor().accept(status); + } + } + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java index 86a3030bd3..7f2390b38a 100644 --- a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java @@ -17,25 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.notification.workers.impl; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.InputStreamReader; +import java.util.UUID; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; -import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.notification.config.ConfigurationManager; import org.openecomp.sdc.notification.types.NotificationsStatusDto; import org.openecomp.sdc.notification.workers.NewNotificationsReader; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import java.io.InputStreamReader; -import java.util.UUID; - public class NewNotificationsReaderRestImpl implements NewNotificationsReader { private static final String USER_ID_HEADER_PARAM = "USER_ID"; @@ -47,12 +45,10 @@ public class NewNotificationsReaderRestImpl implements NewNotificationsReader { private static final int DEFAULT_BE_PORT = 8080; private static final String URL = "http://%s:%d/onboarding-api/v1.0/notifications/worker?"; private static final ObjectMapper mapper = new ObjectMapper(); - + private static final Logger LOGGER = LoggerFactory.getLogger(NewNotificationsReaderRestImpl.class); private static String beHost; private static int bePort; - private static final Logger LOGGER = LoggerFactory.getLogger(NewNotificationsReaderRestImpl.class); - public NewNotificationsReaderRestImpl() { ConfigurationManager cm = ConfigurationManager.getInstance(); bePort = cm.getConfigValue(BE_PORT, DEFAULT_BE_PORT); @@ -62,17 +58,14 @@ public class NewNotificationsReaderRestImpl implements NewNotificationsReader { public NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit) { HttpClient client = HttpClientBuilder.create().build(); String url = String.format(URL, beHost, bePort); - url = url + LIMIT_QUERY_PARAM + "=" + limit; if (eventId != null) { url = url + "&" + LAST_DELIVERED_QUERY_PARAM + "=" + eventId; } - HttpGet request = new HttpGet(url); request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); request.addHeader(USER_ID_HEADER_PARAM, ownerId); - try { HttpResponse response = client.execute(request); return mapper.readValue(new InputStreamReader(response.getEntity().getContent()), NotificationsStatusDto.class); diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/ComputeFlavor.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/ComputeFlavor.java index f0d5472fd9..693344b50d 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/ComputeFlavor.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/ComputeFlavor.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import lombok.EqualsAndHashCode; @@ -38,5 +37,4 @@ public class ComputeFlavor { private int num_cpus; private String disk_size; private String mem_size; - } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/DeploymentFlavorModel.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/DeploymentFlavorModel.java index ae7952e897..ede0a131e4 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/DeploymentFlavorModel.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/DeploymentFlavorModel.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import lombok.EqualsAndHashCode; @@ -39,6 +38,4 @@ public class DeploymentFlavorModel { private VendorInfo vendor_info; private ComputeFlavor compute_flavor; private LicenseFlavor license_flavor; - } - diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/LicenseFlavor.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/LicenseFlavor.java index 0f7e5e80fb..98593d934b 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/LicenseFlavor.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/LicenseFlavor.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import lombok.EqualsAndHashCode; @@ -36,5 +35,4 @@ import lombok.ToString; public class LicenseFlavor { private String feature_group_uuid; - } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/MultiFlavorVfcImage.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/MultiFlavorVfcImage.java index 3c64231321..5f7948f255 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/MultiFlavorVfcImage.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/MultiFlavorVfcImage.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import lombok.EqualsAndHashCode; @@ -39,5 +38,4 @@ public class MultiFlavorVfcImage { private String file_hash; private String file_hash_type; private String software_version; - } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VendorInfo.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VendorInfo.java index 1837841948..7f56f521ad 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VendorInfo.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VendorInfo.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import lombok.EqualsAndHashCode; @@ -37,5 +36,4 @@ public class VendorInfo { private String manufacturer_reference_number; private String vendor_model; - } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VspModelInfo.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VspModelInfo.java index 05f43ce76b..bb302bbbe4 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VspModelInfo.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/datatypes/tosca/VspModelInfo.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.generator.datatypes.tosca; import java.util.List; @@ -47,5 +46,4 @@ public class VspModelInfo { private Map> multiFlavorVfcImages; //Map of component and ports (NICs) private Map> nics; - } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/util/GeneratorConstants.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/util/GeneratorConstants.java index 3917ebe5ba..03e72255bd 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/util/GeneratorConstants.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-api/src/main/java/org/openecomp/sdc/generator/util/GeneratorConstants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.generator.util; public final class GeneratorConstants { + public static final String ALLOWED_FLAVORS_PROPERTY = "allowed_flavors"; public static final String IMAGES_PROPERTY = "images"; public static final String RELEASE_VENDOR = "releaseVendor"; @@ -30,14 +30,13 @@ public final class GeneratorConstants { public static final String PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX = "_wan"; public static final String PORT_NODE_TEMPLATE_ID_SUFFIX = "_port"; public static final String TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX = "ServiceTemplate.yaml"; - //Manual VSP propeties public static final String NUM_CPUS = "num_cpus"; public static final String DISK_SIZE = "disk_size"; public static final String MEM_SIZE = "mem_size"; - public static final String NUM_CPUS_PROP_DESC_PREFIX = "Number of cpu for "; - public static final String DISK_SIZE_PROP_DESC_PREFIX = "Disk size for "; - public static final String MEM_SIZE_PROP_DESC_PREFIX = "Memory size for "; + public static final String NUM_CPUS_PROP_DESC_PREFIX = "Number of cpu for "; + public static final String DISK_SIZE_PROP_DESC_PREFIX = "Disk size for "; + public static final String MEM_SIZE_PROP_DESC_PREFIX = "Memory size for "; // prevent utility class instantiation private GeneratorConstants() { diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java index 5a18155f03..8fd2d090db 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.generator.core.services; import java.util.ArrayList; @@ -53,344 +52,298 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; */ public class ManualVspToscaGenerationService { - //Map of the abstract node template id and substitution node type - private Map abstractSubstitutionIdTypes = new HashMap<>(); - //Map of service template name and service template for the generated service templates - private Map generatedServiceTemplates = new HashMap<>(); - + //Map of the abstract node template id and substitution node type + private Map abstractSubstitutionIdTypes = new HashMap<>(); + //Map of service template name and service template for the generated service templates + private Map generatedServiceTemplates = new HashMap<>(); + + /** + * Create manual vsp tosca service model tosca service model. + * + * @param vspModelInfo the vsp model info + * @return the tosca service model + */ + public ToscaServiceModel createManualVspToscaServiceModel(VspModelInfo vspModelInfo) { + ToscaServiceModel toscaServiceModel = new ToscaServiceModel(); + Map serviceTemplates = new HashMap<>(GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL)); + toscaServiceModel.setServiceTemplates(serviceTemplates); + toscaServiceModel + .setEntryDefinitionServiceTemplate(Constants.MAIN_TEMPLATE_NAME + GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX); + createToscaFromVspData(vspModelInfo, toscaServiceModel); + for (Map.Entry serviceTemplateEntry : generatedServiceTemplates.entrySet()) { + ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplateEntry.getValue()); + } + return toscaServiceModel; + } - /** - * Create manual vsp tosca service model tosca service model. - * - * @param vspModelInfo the vsp model info - * @return the tosca service model - */ - public ToscaServiceModel createManualVspToscaServiceModel(VspModelInfo vspModelInfo) { - ToscaServiceModel toscaServiceModel = new ToscaServiceModel(); - Map serviceTemplates = new HashMap<>(GlobalTypesGenerator - .getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL)); - toscaServiceModel.setServiceTemplates(serviceTemplates); - toscaServiceModel.setEntryDefinitionServiceTemplate(Constants.MAIN_TEMPLATE_NAME - + GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX); - createToscaFromVspData(vspModelInfo, toscaServiceModel); - for (Map.Entry serviceTemplateEntry : - generatedServiceTemplates.entrySet()) { - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplateEntry - .getValue()); + private void createToscaFromVspData(VspModelInfo vspModelInfo, ToscaServiceModel toscaServiceModel) { + //Only one component supported + Optional componentName = getComponentNameFromVspModel(vspModelInfo); + if (componentName.isPresent()) { + //Create main service template + ServiceTemplate mainServiceTemplate = createMainServiceTemplate(vspModelInfo); + generatedServiceTemplates.put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); + //Create substitution service template + for (Map.Entry entry : abstractSubstitutionIdTypes.entrySet()) { + ServiceTemplate substitutionServiceTemplate = createSubstitutionServiceTemplate(componentName.get(), entry.getValue(), vspModelInfo, + toscaServiceModel); + generatedServiceTemplates.put(componentName.get(), substitutionServiceTemplate); + } + } } - return toscaServiceModel; - } - private void createToscaFromVspData(VspModelInfo vspModelInfo, - ToscaServiceModel toscaServiceModel) { - //Only one component supported - Optional componentName = getComponentNameFromVspModel(vspModelInfo); - if (componentName.isPresent()) { - //Create main service template - ServiceTemplate mainServiceTemplate = createMainServiceTemplate(vspModelInfo); - generatedServiceTemplates.put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); - //Create substitution service template - for (Map.Entry entry : abstractSubstitutionIdTypes.entrySet()) { - ServiceTemplate substitutionServiceTemplate = - createSubstitutionServiceTemplate(componentName.get(), entry.getValue(), vspModelInfo, - toscaServiceModel); - generatedServiceTemplates.put(componentName.get(), substitutionServiceTemplate); - } + private Optional getComponentNameFromVspModel(VspModelInfo vspModelInfo) { + String componentName = null; + if (MapUtils.isNotEmpty(vspModelInfo.getComponents())) { + //supported for single component only + componentName = vspModelInfo.getComponents().entrySet().iterator().next().getValue(); + } + return Optional.ofNullable(componentName); } - } + private ServiceTemplate createMainServiceTemplate(VspModelInfo vspModelInfo) { + ServiceTemplate mainServiceTemplate = createInitMainServiceTemplate(vspModelInfo.getReleaseVendor()); + Map components = vspModelInfo.getComponents(); + if (MapUtils.isNotEmpty(components)) { + //Currently since only one component is supported we can fetch the component in this manner. + + // May be need to revisited for supporting multiple components + String componentId = components.entrySet().iterator().next().getKey(); + createVnfConfigurationNodeTemplate(mainServiceTemplate, vspModelInfo); + createVnfNodeTemplate(mainServiceTemplate, vspModelInfo, componentId); + } + return mainServiceTemplate; + } - private Optional getComponentNameFromVspModel(VspModelInfo vspModelInfo) { - String componentName = null; - if (MapUtils.isNotEmpty(vspModelInfo.getComponents())) { - //supported for single component only - componentName = vspModelInfo.getComponents().entrySet().iterator().next().getValue(); + private void createVnfConfigurationNodeTemplate(ServiceTemplate mainServiceTemplate, VspModelInfo vspModelInfo) { + Optional componentName = getComponentNameFromVspModel(vspModelInfo); + if (componentName.isPresent()) { + NodeTemplate vnfConfigurationNodeTemplate = new NodeTemplate(); + vnfConfigurationNodeTemplate.setType(ToscaNodeType.VNF_CONFIG_NODE_TYPE); + if (Objects.nonNull(vspModelInfo.getAllowedFlavors())) { + Map properties = new LinkedHashMap<>(); + properties.put(GeneratorConstants.ALLOWED_FLAVORS_PROPERTY, vspModelInfo.getAllowedFlavors()); + vnfConfigurationNodeTemplate.setProperties(properties); + } + String nodeTemplateId = componentName.get() + GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; + DataModelUtil.addNodeTemplate(mainServiceTemplate, nodeTemplateId, vnfConfigurationNodeTemplate); + } } - return Optional.ofNullable(componentName); - } - private ServiceTemplate createMainServiceTemplate(VspModelInfo vspModelInfo) { - ServiceTemplate mainServiceTemplate = createInitMainServiceTemplate(vspModelInfo - .getReleaseVendor()); - Map components = vspModelInfo.getComponents(); - if (MapUtils.isNotEmpty(components)) { - //Currently since only one component is supported we can fetch the component in this manner. - // May be need to revisited for supporting multiple components - String componentId = components.entrySet().iterator().next().getKey(); - createVnfConfigurationNodeTemplate(mainServiceTemplate, vspModelInfo); - createVnfNodeTemplate(mainServiceTemplate, vspModelInfo, componentId); + private void createVnfNodeTemplate(ServiceTemplate mainServiceTemplate, VspModelInfo vspModelInfo, String componentId) { + Optional componentName = getComponentNameFromVspModel(vspModelInfo); + if (componentName.isPresent()) { + NodeTemplate vnfNodeTemplate = new NodeTemplate(); + vnfNodeTemplate.setType(ToscaNodeType.MULTIDEPLOYMENTFLAVOR_NODE_TYPE); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + vnfNodeTemplate.setDirectives(directiveList); + vnfNodeTemplate.setProperties(getVnfNodeTemplateProperties(vspModelInfo, componentId)); + DataModelUtil.addSubstitutionFilteringProperty(getSubstitutionServiceTemplateFileName(componentName.get()), vnfNodeTemplate, 1); + //Enable below if we need "abstract_" as prefix like we have in Unified model + + //String nodeTemplateId = + + // Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + componentName + "VNF_NODE_TEMPLATE_ID_SUFFIX"; + String nodeTemplateId = componentName.get() + GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; + DataModelUtil.addNodeTemplate(mainServiceTemplate, nodeTemplateId, vnfNodeTemplate); + abstractSubstitutionIdTypes.put(componentName.get(), ToscaNodeType.MULTIDEPLOYMENTFLAVOR_NODE_TYPE); + } } - return mainServiceTemplate; - } - private void createVnfConfigurationNodeTemplate(ServiceTemplate mainServiceTemplate, - VspModelInfo vspModelInfo) { - Optional componentName = getComponentNameFromVspModel(vspModelInfo); - if (componentName.isPresent()) { - NodeTemplate vnfConfigurationNodeTemplate = new NodeTemplate(); - vnfConfigurationNodeTemplate.setType(ToscaNodeType.VNF_CONFIG_NODE_TYPE); - if (Objects.nonNull(vspModelInfo.getAllowedFlavors())) { + private Map getVnfNodeTemplateProperties(VspModelInfo vspModelInfo, String componentId) { Map properties = new LinkedHashMap<>(); - properties.put(GeneratorConstants.ALLOWED_FLAVORS_PROPERTY, vspModelInfo.getAllowedFlavors()); - vnfConfigurationNodeTemplate.setProperties(properties); - } - String nodeTemplateId = componentName.get() + GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; - DataModelUtil.addNodeTemplate(mainServiceTemplate, nodeTemplateId, - vnfConfigurationNodeTemplate); + if (MapUtils.isNotEmpty(vspModelInfo.getMultiFlavorVfcImages())) { + List componentImages = vspModelInfo.getMultiFlavorVfcImages().get(componentId); + if (Objects.nonNull(componentImages)) { + Map vfcImages = new HashMap<>(); + componentImages.stream() + .forEach(multiFlavorVfcImage -> vfcImages.put(multiFlavorVfcImage.getSoftware_version(), multiFlavorVfcImage)); + properties.put(GeneratorConstants.IMAGES_PROPERTY, vfcImages); + } + } + return properties; } - } - private void createVnfNodeTemplate(ServiceTemplate mainServiceTemplate, - VspModelInfo vspModelInfo, String componentId) { - Optional componentName = getComponentNameFromVspModel(vspModelInfo); - if (componentName.isPresent()) { - NodeTemplate vnfNodeTemplate = new NodeTemplate(); - vnfNodeTemplate.setType(ToscaNodeType.MULTIDEPLOYMENTFLAVOR_NODE_TYPE); - List directiveList = new ArrayList<>(); - directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); - vnfNodeTemplate.setDirectives(directiveList); - vnfNodeTemplate.setProperties(getVnfNodeTemplateProperties(vspModelInfo, componentId)); - DataModelUtil - .addSubstitutionFilteringProperty(getSubstitutionServiceTemplateFileName(componentName - .get()), vnfNodeTemplate, 1); - //Enable below if we need "abstract_" as prefix like we have in Unified model - //String nodeTemplateId = - // Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + componentName + "VNF_NODE_TEMPLATE_ID_SUFFIX"; - String nodeTemplateId = componentName.get() + GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; - DataModelUtil.addNodeTemplate(mainServiceTemplate, nodeTemplateId, - vnfNodeTemplate); - abstractSubstitutionIdTypes.put(componentName.get(), ToscaNodeType - .MULTIDEPLOYMENTFLAVOR_NODE_TYPE); + private String getSubstitutionServiceTemplateFileName(String componentName) { + return componentName + GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; } - } - private Map getVnfNodeTemplateProperties(VspModelInfo vspModelInfo, - String componentId) { - Map properties = new LinkedHashMap<>(); - if (MapUtils.isNotEmpty(vspModelInfo.getMultiFlavorVfcImages())) { - List componentImages = - vspModelInfo.getMultiFlavorVfcImages().get(componentId); - if (Objects.nonNull(componentImages)) { - Map vfcImages = new HashMap<>(); - componentImages.stream() - .forEach(multiFlavorVfcImage -> - vfcImages.put(multiFlavorVfcImage.getSoftware_version(), multiFlavorVfcImage)); - properties.put(GeneratorConstants.IMAGES_PROPERTY, vfcImages); - } + private ServiceTemplate createInitMainServiceTemplate(String releaseVendor) { + ServiceTemplate mainServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); + if (Objects.nonNull(releaseVendor)) { + templateMetadata.put(GeneratorConstants.RELEASE_VENDOR, releaseVendor); + } + mainServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + mainServiceTemplate.setMetadata(templateMetadata); + mainServiceTemplate.setTopology_template(new TopologyTemplate()); + mainServiceTemplate.setImports(getImports()); + return mainServiceTemplate; } - return properties; - } - - private String getSubstitutionServiceTemplateFileName(String componentName) { - return componentName + GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; - } - private ServiceTemplate createInitMainServiceTemplate(String releaseVendor) { - ServiceTemplate mainServiceTemplate = new ServiceTemplate(); - Map templateMetadata = new HashMap<>(); - templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); - if (Objects.nonNull(releaseVendor)) { - templateMetadata.put(GeneratorConstants.RELEASE_VENDOR, releaseVendor); + private List> getImports() { + Map globalSubstitutionTypeImportMap = new HashMap<>(); + Import globalSubstitutionTypeImport = new Import(); + globalSubstitutionTypeImport.setFile(ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + globalSubstitutionTypeImportMap.put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionTypeImport); + List> manualVspGlobalTypesImportList = GlobalTypesGenerator.getManualVspGlobalTypesImportList(); + manualVspGlobalTypesImportList.add(globalSubstitutionTypeImportMap); + return manualVspGlobalTypesImportList; } - mainServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - mainServiceTemplate.setMetadata(templateMetadata); - mainServiceTemplate.setTopology_template(new TopologyTemplate()); - mainServiceTemplate.setImports(getImports()); - return mainServiceTemplate; - } - - private List> getImports() { - Map globalSubstitutionTypeImportMap = new HashMap<>(); - Import globalSubstitutionTypeImport = new Import(); - globalSubstitutionTypeImport.setFile(ToscaUtil.getServiceTemplateFileName(Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); - globalSubstitutionTypeImportMap.put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - globalSubstitutionTypeImport); - List> manualVspGlobalTypesImportList = GlobalTypesGenerator - .getManualVspGlobalTypesImportList(); - manualVspGlobalTypesImportList.add(globalSubstitutionTypeImportMap); - return manualVspGlobalTypesImportList; - } - - private ServiceTemplate createSubstitutionServiceTemplate(String serviceTemplateName, - String substitutionNodeTypeId, - VspModelInfo vspModelInfo, - ToscaServiceModel toscaServiceModel) { - ServiceTemplate substitutionServiceTemplate = - createInitSubstitutionServiceTemplate(serviceTemplateName); - createSubstitutionServiceTemplateComponents(substitutionServiceTemplate, vspModelInfo); - createSubstitutionServiceTemplateNics(substitutionServiceTemplate, vspModelInfo); - handleSubstitutionMapping(substitutionServiceTemplate, toscaServiceModel, - substitutionNodeTypeId, serviceTemplateName); - return substitutionServiceTemplate; - } - private void createSubstitutionServiceTemplateComponents(ServiceTemplate - substitutionServiceTemplate, - VspModelInfo vspModelInfo) { - Map components = vspModelInfo.getComponents(); - if (MapUtils.isNotEmpty(components)) { - for (String componentName : components.values()) { - String localNodeTypeId = - createComponentDefinitionNodeTemplate(substitutionServiceTemplate, componentName); - createLocalNodeType(substitutionServiceTemplate, localNodeTypeId); - } + private ServiceTemplate createSubstitutionServiceTemplate(String serviceTemplateName, String substitutionNodeTypeId, VspModelInfo vspModelInfo, + ToscaServiceModel toscaServiceModel) { + ServiceTemplate substitutionServiceTemplate = createInitSubstitutionServiceTemplate(serviceTemplateName); + createSubstitutionServiceTemplateComponents(substitutionServiceTemplate, vspModelInfo); + createSubstitutionServiceTemplateNics(substitutionServiceTemplate, vspModelInfo); + handleSubstitutionMapping(substitutionServiceTemplate, toscaServiceModel, substitutionNodeTypeId, serviceTemplateName); + return substitutionServiceTemplate; } - } - private void createSubstitutionServiceTemplateNics(ServiceTemplate substitutionServiceTemplate, - VspModelInfo vspModelInfo) { - Map> nics = vspModelInfo.getNics(); - if (MapUtils.isNotEmpty(nics)) { - for (Map.Entry> entry : nics.entrySet()) { - String componentId = entry.getKey(); - String componentNodeTemplateId = getSubstitutionComponentNodeTemplateId( - vspModelInfo.getComponents().get(componentId)); - List nicList = entry.getValue(); - if (CollectionUtils.isNotEmpty(nicList)) { - for (Nic nic : nicList) { - NodeTemplate nicNodeTemplate = new NodeTemplate(); - nicNodeTemplate.setType(ToscaNodeType.NETWORK_PORT); - DataModelUtil.addBindingReqFromPortToCompute(componentNodeTemplateId, nicNodeTemplate); - DataModelUtil.addNodeTemplate(substitutionServiceTemplate, - getNicNodeTemplateId(nic.getName(), nic.getNetworkType()), nicNodeTemplate); - } + private void createSubstitutionServiceTemplateComponents(ServiceTemplate substitutionServiceTemplate, VspModelInfo vspModelInfo) { + Map components = vspModelInfo.getComponents(); + if (MapUtils.isNotEmpty(components)) { + for (String componentName : components.values()) { + String localNodeTypeId = createComponentDefinitionNodeTemplate(substitutionServiceTemplate, componentName); + createLocalNodeType(substitutionServiceTemplate, localNodeTypeId); + } } - } } - } - private String getSubstitutionComponentNodeTemplateId(String componentName) { - //TODO: Confirm if anything else is needed here - return componentName; - } - - private String getNicNodeTemplateId(String nicName, NetworkType nicNetworkType) { - StringBuilder builder = new StringBuilder(); - builder.append(nicName); - if (nicNetworkType == NetworkType.External) { - builder.append(GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX); - } else if (nicNetworkType == NetworkType.Internal) { - builder.append(GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX); + private void createSubstitutionServiceTemplateNics(ServiceTemplate substitutionServiceTemplate, VspModelInfo vspModelInfo) { + Map> nics = vspModelInfo.getNics(); + if (MapUtils.isNotEmpty(nics)) { + for (Map.Entry> entry : nics.entrySet()) { + String componentId = entry.getKey(); + String componentNodeTemplateId = getSubstitutionComponentNodeTemplateId(vspModelInfo.getComponents().get(componentId)); + List nicList = entry.getValue(); + if (CollectionUtils.isNotEmpty(nicList)) { + for (Nic nic : nicList) { + NodeTemplate nicNodeTemplate = new NodeTemplate(); + nicNodeTemplate.setType(ToscaNodeType.NETWORK_PORT); + DataModelUtil.addBindingReqFromPortToCompute(componentNodeTemplateId, nicNodeTemplate); + DataModelUtil + .addNodeTemplate(substitutionServiceTemplate, getNicNodeTemplateId(nic.getName(), nic.getNetworkType()), nicNodeTemplate); + } + } + } + } } - builder.append(GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX); - return builder.toString(); - } - private String createComponentDefinitionNodeTemplate(ServiceTemplate substitutionServiceTemplate, - String componentName) { - NodeTemplate nodeTemplate = new NodeTemplate(); - String localNodeTypeId = getLocalNodeTypeId(componentName); - nodeTemplate.setType(localNodeTypeId); - DataModelUtil.addNodeTemplate(substitutionServiceTemplate, componentName, nodeTemplate); - return localNodeTypeId; - } - - private void createLocalNodeType(ServiceTemplate substitutionServiceTemplate, - String localNodeTypeId) { - NodeType localNodeType = new NodeType(); - localNodeType.setDerived_from(ToscaNodeType.COMPUTE); - DataModelUtil.addNodeType(substitutionServiceTemplate, localNodeTypeId, localNodeType ); - } + private String getSubstitutionComponentNodeTemplateId(String componentName) { + //TODO: Confirm if anything else is needed here + return componentName; + } - private String getLocalNodeTypeId(String componentName) { - return ToscaNodeType.VFC_NODE_TYPE_PREFIX + componentName; - } + private String getNicNodeTemplateId(String nicName, NetworkType nicNetworkType) { + StringBuilder builder = new StringBuilder(); + builder.append(nicName); + if (nicNetworkType == NetworkType.External) { + builder.append(GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX); + } else if (nicNetworkType == NetworkType.Internal) { + builder.append(GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX); + } + builder.append(GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX); + return builder.toString(); + } - private ServiceTemplate createInitSubstitutionServiceTemplate(String serviceTemplateName) { - ServiceTemplate substitutionServiceTemplate = new ServiceTemplate(); - Map templateMetadata = new HashMap<>(); - substitutionServiceTemplate.setTosca_definitions_version(ToscaConstants - .TOSCA_DEFINITIONS_VERSION); - templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, serviceTemplateName); - substitutionServiceTemplate.setMetadata(templateMetadata); - substitutionServiceTemplate.setTopology_template(new TopologyTemplate()); - substitutionServiceTemplate.setImports(getImports()); - return substitutionServiceTemplate; - } + private String createComponentDefinitionNodeTemplate(ServiceTemplate substitutionServiceTemplate, String componentName) { + NodeTemplate nodeTemplate = new NodeTemplate(); + String localNodeTypeId = getLocalNodeTypeId(componentName); + nodeTemplate.setType(localNodeTypeId); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, componentName, nodeTemplate); + return localNodeTypeId; + } - private void handleSubstitutionMapping(ServiceTemplate substitutionServiceTemplate, - ToscaServiceModel toscaServiceModel, - String substitutionNodeTypeId, - String componentName) { - ServiceTemplate globalSubstitutionServiceTemplate = fetchGlobalSubstitutionServiceTemplate(); - NodeType substitutionNodeType = - createGlobalSubstitutionNodeType(substitutionServiceTemplate, componentName); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, - substitutionNodeType); - Map>> substitutionMapping = - GeneratorUtils.getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, - substitutionServiceTemplate, toscaServiceModel); - if (Objects.nonNull(substitutionMapping)) { - //add substitution mapping after capability and requirement expose calculation - substitutionServiceTemplate.getTopology_template().setSubstitution_mappings( - DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeId, - substitutionNodeType, substitutionMapping)); + private void createLocalNodeType(ServiceTemplate substitutionServiceTemplate, String localNodeTypeId) { + NodeType localNodeType = new NodeType(); + localNodeType.setDerived_from(ToscaNodeType.COMPUTE); + DataModelUtil.addNodeType(substitutionServiceTemplate, localNodeTypeId, localNodeType); } - } - //*************** CREATE GLOBAL SUBSTITUTION SERVICE TEMPLATE ********************** + private String getLocalNodeTypeId(String componentName) { + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + componentName; + } - private ServiceTemplate createInitGlobalSubstitutionServiceTemplate() { - ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate(); - Map templateMetadata = new HashMap<>(); - globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants - .TOSCA_DEFINITIONS_VERSION); - templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, - Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - globalSubstitutionServiceTemplate.setMetadata(templateMetadata); - globalSubstitutionServiceTemplate.setImports(getImports()); - return globalSubstitutionServiceTemplate; - } + private ServiceTemplate createInitSubstitutionServiceTemplate(String serviceTemplateName) { + ServiceTemplate substitutionServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + substitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, serviceTemplateName); + substitutionServiceTemplate.setMetadata(templateMetadata); + substitutionServiceTemplate.setTopology_template(new TopologyTemplate()); + substitutionServiceTemplate.setImports(getImports()); + return substitutionServiceTemplate; + } - private NodeType createGlobalSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, - String componentName) { - NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() - .createInitSubstitutionNodeType(substitutionServiceTemplate, - ToscaNodeType.MULTIFLAVOR_VFC_NODE_TYPE); - substitutionNodeType.setProperties( - getManualVspSubstitutionNodeTypeProperties(componentName)); - return substitutionNodeType; - } + private void handleSubstitutionMapping(ServiceTemplate substitutionServiceTemplate, ToscaServiceModel toscaServiceModel, + String substitutionNodeTypeId, String componentName) { + ServiceTemplate globalSubstitutionServiceTemplate = fetchGlobalSubstitutionServiceTemplate(); + NodeType substitutionNodeType = createGlobalSubstitutionNodeType(substitutionServiceTemplate, componentName); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, substitutionNodeType); + Map>> substitutionMapping = GeneratorUtils + .getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, substitutionServiceTemplate, toscaServiceModel); + if (Objects.nonNull(substitutionMapping)) { + //add substitution mapping after capability and requirement expose calculation + substitutionServiceTemplate.getTopology_template().setSubstitution_mappings( + DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeId, substitutionNodeType, substitutionMapping)); + } + } - private Map getManualVspSubstitutionNodeTypeProperties(String componentName) { - //Create num_cpus property - PropertyDefinition numCpus = new PropertyDefinition(); - numCpus.setType(PropertyType.INTEGER.getDisplayName()); - numCpus.setDescription(GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX + componentName); - numCpus.setRequired(true); - //Create disk_size property - PropertyDefinition diskSize = new PropertyDefinition(); - diskSize.setType(PropertyType.SCALAR_UNIT_SIZE.getDisplayName()); - diskSize.setDescription(GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX + componentName); - diskSize.setRequired(true); - //Create mem_size property - PropertyDefinition memSize = new PropertyDefinition(); - memSize.setType(PropertyType.SCALAR_UNIT_SIZE.getDisplayName()); - memSize.setDescription(GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX + componentName); - memSize.setRequired(true); + //*************** CREATE GLOBAL SUBSTITUTION SERVICE TEMPLATE ********************** + private ServiceTemplate createInitGlobalSubstitutionServiceTemplate() { + ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + globalSubstitutionServiceTemplate.setMetadata(templateMetadata); + globalSubstitutionServiceTemplate.setImports(getImports()); + return globalSubstitutionServiceTemplate; + } - Map manualVspProperties = new LinkedHashMap<>(); - manualVspProperties.put(GeneratorConstants.NUM_CPUS, numCpus); - manualVspProperties.put(GeneratorConstants.DISK_SIZE, diskSize); - manualVspProperties.put(GeneratorConstants.MEM_SIZE, memSize); + private NodeType createGlobalSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, String componentName) { + NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() + .createInitSubstitutionNodeType(substitutionServiceTemplate, ToscaNodeType.MULTIFLAVOR_VFC_NODE_TYPE); + substitutionNodeType.setProperties(getManualVspSubstitutionNodeTypeProperties(componentName)); + return substitutionNodeType; + } - return manualVspProperties; - } + private Map getManualVspSubstitutionNodeTypeProperties(String componentName) { + //Create num_cpus property + PropertyDefinition numCpus = new PropertyDefinition(); + numCpus.setType(PropertyType.INTEGER.getDisplayName()); + numCpus.setDescription(GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX + componentName); + numCpus.setRequired(true); + //Create disk_size property + PropertyDefinition diskSize = new PropertyDefinition(); + diskSize.setType(PropertyType.SCALAR_UNIT_SIZE.getDisplayName()); + diskSize.setDescription(GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX + componentName); + diskSize.setRequired(true); + //Create mem_size property + PropertyDefinition memSize = new PropertyDefinition(); + memSize.setType(PropertyType.SCALAR_UNIT_SIZE.getDisplayName()); + memSize.setDescription(GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX + componentName); + memSize.setRequired(true); + Map manualVspProperties = new LinkedHashMap<>(); + manualVspProperties.put(GeneratorConstants.NUM_CPUS, numCpus); + manualVspProperties.put(GeneratorConstants.DISK_SIZE, diskSize); + manualVspProperties.put(GeneratorConstants.MEM_SIZE, memSize); + return manualVspProperties; + } - /** - * Fetch global substitution service template service template. - * - * @return the global substitution service template - */ - private ServiceTemplate fetchGlobalSubstitutionServiceTemplate() { - ServiceTemplate globalSubstitutionServiceTemplate = - generatedServiceTemplates.get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - if (Objects.isNull(globalSubstitutionServiceTemplate)) { - globalSubstitutionServiceTemplate = createInitGlobalSubstitutionServiceTemplate(); - generatedServiceTemplates.put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - globalSubstitutionServiceTemplate); + /** + * Fetch global substitution service template service template. + * + * @return the global substitution service template + */ + private ServiceTemplate fetchGlobalSubstitutionServiceTemplate() { + ServiceTemplate globalSubstitutionServiceTemplate = generatedServiceTemplates.get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + if (Objects.isNull(globalSubstitutionServiceTemplate)) { + globalSubstitutionServiceTemplate = createInitGlobalSubstitutionServiceTemplate(); + generatedServiceTemplates.put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); + } + return globalSubstitutionServiceTemplate; } - return globalSubstitutionServiceTemplate; - } } diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java index a1460a8163..285ac2dbc4 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.generator.core.utils; -import org.onap.sdc.tosca.datatypes.model.*; +import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -29,22 +42,17 @@ import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; -import java.util.*; - -import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; - /** * The type Generator utils. */ public class GeneratorUtils { - private GeneratorUtils() { - // prevent instantiation - } - //TODO : Read from configuration private static final List SUPPORTED_CAPABILITIES = Arrays.asList("host", "os", "endpoint", "scalable"); private static final List SUPPORTED_REQUIREMENTS = Collections.singletonList("link"); + private GeneratorUtils() { + // prevent instantiation + } /** * Add service template to tosca service model. @@ -52,9 +60,7 @@ public class GeneratorUtils { * @param toscaServiceModel the tosca service model * @param serviceTemplate the service template */ - public static void addServiceTemplateToToscaServiceModel(ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate) { - + public static void addServiceTemplateToToscaServiceModel(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate) { String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); Map serviceTemplates = toscaServiceModel.getServiceTemplates(); if (!serviceTemplates.containsKey(serviceTemplateFileName)) { @@ -72,11 +78,9 @@ public class GeneratorUtils { * @return the substitution node type exposed connection points */ public static Map>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType, - ServiceTemplate substitutionServiceTemplate, - ToscaServiceModel toscaServiceModel) { - - Map nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); + ServiceTemplate substitutionServiceTemplate, + ToscaServiceModel toscaServiceModel) { + Map nodeTemplates = substitutionServiceTemplate.getTopology_template().getNode_templates(); String nodeTemplateId; NodeTemplate nodeTemplate; String nodeType; @@ -84,7 +88,6 @@ public class GeneratorUtils { if (nodeTemplates == null) { return substitutionMapping; } - try { Map> capabilitySubstitutionMapping = new HashMap<>(); Map> requirementSubstitutionMapping = new HashMap<>(); @@ -96,54 +99,41 @@ public class GeneratorUtils { Map> fullFilledRequirementsDefinition = new HashMap<>(); Map nodeTypeCapabilitiesDefinition = new HashMap<>(); Map exposedCapabilitiesDefinition; - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); for (Map.Entry entry : nodeTemplates.entrySet()) { nodeTemplateId = entry.getKey(); nodeTemplate = entry.getValue(); nodeType = nodeTemplate.getType(); NodeType flatNodeType = (NodeType) toscaAnalyzerService - .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType, - substitutionServiceTemplate, toscaServiceModel) - .getFlatEntity(); + .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeType, substitutionServiceTemplate, toscaServiceModel).getFlatEntity(); // get requirements - nodeTypeRequirementsDefinition = - getNodeTypeRequirements(flatNodeType, nodeTemplateId, substitutionServiceTemplate, - requirementSubstitutionMapping); + nodeTypeRequirementsDefinition = getNodeTypeRequirements(flatNodeType, nodeTemplateId, substitutionServiceTemplate, + requirementSubstitutionMapping); nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate); fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment); //set substitution node type requirements exposedRequirementsDefinition = toscaAnalyzerService - .calculateExposedRequirements(nodeTypeRequirementsDefinition, - nodeTemplateRequirementsAssignment); - - + .calculateExposedRequirements(nodeTypeRequirementsDefinition, nodeTemplateRequirementsAssignment); //Filter unsupported requirements Iterator> iterator = exposedRequirementsDefinition.iterator(); while (iterator.hasNext()) { Map requirementDefinitionMap = iterator.next(); - for (Map.Entry requirementDefinitionEntry : requirementDefinitionMap - .entrySet()) { + for (Map.Entry requirementDefinitionEntry : requirementDefinitionMap.entrySet()) { String requirementKey = requirementDefinitionEntry.getKey(); if (!SUPPORTED_REQUIREMENTS.contains(requirementKey)) { iterator.remove(); } } } - addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, - nodeTemplateId); + addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, nodeTemplateId); //get capabilities - addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, - nodeType, nodeTemplateId, substitutionServiceTemplate, toscaServiceModel); + addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType, nodeTemplateId, + substitutionServiceTemplate, toscaServiceModel); } - exposedCapabilitiesDefinition = toscaAnalyzerService - .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, - fullFilledRequirementsDefinition); - + .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, fullFilledRequirementsDefinition); //Filter unsupported capabilities - Iterator> iterator = - exposedCapabilitiesDefinition.entrySet().iterator(); + Iterator> iterator = exposedCapabilitiesDefinition.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry capabilityDefinitionEntry = iterator.next(); //Expected Capability is of the format _ @@ -152,7 +142,6 @@ public class GeneratorUtils { iterator.remove(); } } - DataModelUtil.setNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition); } catch (Exception ex) { return null; @@ -169,21 +158,19 @@ public class GeneratorUtils { * @param requirementSubstitutionMapping the requirement substitution mapping * @return the node type requirements */ - public static List> getNodeTypeRequirements(NodeType flatNodeType, - String templateName, - ServiceTemplate serviceTemplate, - Map> requirementSubstitutionMapping) { + public static List> getNodeTypeRequirements(NodeType flatNodeType, String templateName, + ServiceTemplate serviceTemplate, + Map> requirementSubstitutionMapping) { List> requirementList = new ArrayList<>(); List requirementMapping; if (flatNodeType.getRequirements() != null) { for (Map requirementMap : flatNodeType.getRequirements()) { for (Map.Entry requirementNodeEntry : requirementMap.entrySet()) { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), - RequirementDefinition.class); + RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), RequirementDefinition.class); if (requirementNodeEntryValue.getOccurrences() == null) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } Map requirementDef = new HashMap<>(); requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue); @@ -191,10 +178,9 @@ public class GeneratorUtils { requirementMapping = new ArrayList<>(); requirementMapping.add(templateName); requirementMapping.add(requirementNodeEntry.getKey()); - requirementSubstitutionMapping - .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping); + requirementSubstitutionMapping.put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping); if (requirementNodeEntryValue.getNode() == null) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } } } @@ -203,18 +189,15 @@ public class GeneratorUtils { } private static void addNodeTypeCapabilitiesToSubMapping(Map nodeTypeCapabilitiesDefinition, - Map> capabilitySubstitutionMapping, - String type, String templateName, - ServiceTemplate substitutionServiceTemplate, - ToscaServiceModel toscaServiceModel) { + Map> capabilitySubstitutionMapping, String type, String templateName, + ServiceTemplate substitutionServiceTemplate, ToscaServiceModel toscaServiceModel) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - NodeType flatNodeType = (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, type, - substitutionServiceTemplate, toscaServiceModel).getFlatEntity(); + NodeType flatNodeType = (NodeType) toscaAnalyzerService + .getFlatEntity(ToscaElementTypes.NODE_TYPE, type, substitutionServiceTemplate, toscaServiceModel).getFlatEntity(); String capabilityKey; List capabilityMapping; if (flatNodeType.getCapabilities() != null) { - for (Map.Entry capabilityNodeEntry : flatNodeType.getCapabilities() - .entrySet()) { + for (Map.Entry capabilityNodeEntry : flatNodeType.getCapabilities().entrySet()) { capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName; nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone()); capabilityMapping = new ArrayList<>(); @@ -224,5 +207,4 @@ public class GeneratorUtils { } } } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java index f00017a229..614ea6ffdc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/api/HeatToToscaTranslator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.translator.api; - -import org.openecomp.core.translator.datatypes.TranslatorOutput; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.io.InputStream; import java.util.List; import java.util.Map; - - - +import org.openecomp.core.translator.datatypes.TranslatorOutput; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public interface HeatToToscaTranslator { - void addManifest(String name, byte[] content); - - void addFile(String name, byte[] content); + void addManifest(String name, byte[] content); - void addFile(String name, InputStream content); + void addFile(String name, byte[] content); - // return Map, key - file name which has error - // value - the error code - Map> validate(); + void addFile(String name, InputStream content); + // return Map, key - file name which has error - TranslatorOutput translate(); + // value - the error code + Map> validate(); - void addExternalArtifacts(String name, byte[] content); + TranslatorOutput translate(); - void addExternalArtifacts(String name, InputStream content); + void addExternalArtifacts(String name, byte[] content); + void addExternalArtifacts(String name, InputStream content); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java index c9169446ef..bceb963f50 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/datatypes/TranslatorOutput.java @@ -13,21 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.translator.datatypes; +import java.util.List; +import java.util.Map; import lombok.Data; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import java.util.List; -import java.util.Map; - - @Data public class TranslatorOutput { - private Map> errorMessages; - private ToscaServiceModel toscaServiceModel; - private ToscaServiceModel nonUnifiedToscaServiceModel; + private Map> errorMessages; + private ToscaServiceModel toscaServiceModel; + private ToscaServiceModel nonUnifiedToscaServiceModel; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java index ebc497374d..6d3e9f80c5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-api/src/main/java/org/openecomp/core/translator/factory/HeatToToscaTranslatorFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.translator.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.translator.api.HeatToToscaTranslator; +public abstract class HeatToToscaTranslatorFactory extends AbstractComponentFactory { - -public abstract class HeatToToscaTranslatorFactory - extends AbstractComponentFactory { - - public static HeatToToscaTranslatorFactory getInstance() { - return getInstance(HeatToToscaTranslatorFactory.class); - } + public static HeatToToscaTranslatorFactory getInstance() { + return getInstance(HeatToToscaTranslatorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java index 38bfc99c54..1ca3579c85 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; public class AttachedPropertyVal { - private Object propertyValue; - private ReferenceType referenceType; - - /** - * Instantiates a new Attached resource id. - * - * @param propertyValue the property value - * @param referenceType the reference type - */ - public AttachedPropertyVal(Object propertyValue, ReferenceType referenceType) { - this.referenceType = referenceType; - this.propertyValue = propertyValue; - } - - public Object getPropertyValue() { - return propertyValue; - } - - public ReferenceType getReferenceType() { - return referenceType; - } - - public boolean isGetResource() { - return referenceType == ReferenceType.GET_RESOURCE; - } - - public boolean isGetParam() { - return referenceType == ReferenceType.GET_PARAM; - } - - public boolean isGetAttr() { - return referenceType == ReferenceType.GET_ATTR; - } + + private Object propertyValue; + private ReferenceType referenceType; + + /** + * Instantiates a new Attached resource id. + * + * @param propertyValue the property value + * @param referenceType the reference type + */ + public AttachedPropertyVal(Object propertyValue, ReferenceType referenceType) { + this.referenceType = referenceType; + this.propertyValue = propertyValue; + } + + public Object getPropertyValue() { + return propertyValue; + } + + public ReferenceType getReferenceType() { + return referenceType; + } + + public boolean isGetResource() { + return referenceType == ReferenceType.GET_RESOURCE; + } + + public boolean isGetParam() { + return referenceType == ReferenceType.GET_PARAM; + } + + public boolean isGetAttr() { + return referenceType == ReferenceType.GET_ATTR; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java index 16baf4e84b..55a40dfc7e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,48 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; public class AttachedResourceId { - private Object translatedId; - private Object entityId; - private ReferenceType resourceReferenceType; - /** - * Instantiates a new Attached resource id. - * - * @param translatedId the translated id - * @param entityId the entity id - * @param resourceReferenceType the resource reference type - */ - public AttachedResourceId(Object translatedId, Object entityId, - ReferenceType resourceReferenceType) { - this.translatedId = translatedId; - this.resourceReferenceType = resourceReferenceType; - this.entityId = entityId; - } + private Object translatedId; + private Object entityId; + private ReferenceType resourceReferenceType; + + /** + * Instantiates a new Attached resource id. + * + * @param translatedId the translated id + * @param entityId the entity id + * @param resourceReferenceType the resource reference type + */ + public AttachedResourceId(Object translatedId, Object entityId, ReferenceType resourceReferenceType) { + this.translatedId = translatedId; + this.resourceReferenceType = resourceReferenceType; + this.entityId = entityId; + } - public Object getEntityId() { - return entityId; - } + public Object getEntityId() { + return entityId; + } - public Object getTranslatedId() { - return translatedId; - } + public Object getTranslatedId() { + return translatedId; + } - public ReferenceType getResourceReferenceType() { - return resourceReferenceType; - } + public ReferenceType getResourceReferenceType() { + return resourceReferenceType; + } - public boolean isGetResource() { - return resourceReferenceType == ReferenceType.GET_RESOURCE; - } + public boolean isGetResource() { + return resourceReferenceType == ReferenceType.GET_RESOURCE; + } - public boolean isGetParam() { - return resourceReferenceType == ReferenceType.GET_PARAM; - } + public boolean isGetParam() { + return resourceReferenceType == ReferenceType.GET_PARAM; + } - public boolean isGetAttr() { - return resourceReferenceType == ReferenceType.GET_ATTR; - } + public boolean isGetAttr() { + return resourceReferenceType == ReferenceType.GET_ATTR; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java index 06d96bc3c1..fd0d733a65 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,67 +17,63 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; -import org.apache.commons.collections.CollectionUtils; - import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; +import org.apache.commons.collections.CollectionUtils; public class PropertyRegexMatcher { - private String propertyName; - private List regexPatterns; - private String stringToSearchForPropertyValue; - - /** - * Constractor for creating PropertyRegexMatcher. - * @param propertyName property name - * @param regexPatterns regex pattern - * @param stringToSearchForPropertyValue string for search in the property value manipulation - */ - public PropertyRegexMatcher(String propertyName, - List regexPatterns, - String stringToSearchForPropertyValue) { - this.propertyName = propertyName; - setRegex(regexPatterns); - this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; - } - public String getPropertyName() { - return propertyName; - } + private String propertyName; + private List regexPatterns; + private String stringToSearchForPropertyValue; - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } + /** + * Constractor for creating PropertyRegexMatcher. + * + * @param propertyName property name + * @param regexPatterns regex pattern + * @param stringToSearchForPropertyValue string for search in the property value manipulation + */ + public PropertyRegexMatcher(String propertyName, List regexPatterns, String stringToSearchForPropertyValue) { + this.propertyName = propertyName; + setRegex(regexPatterns); + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } - /** - * Sets regex. - * - * @param regexPatterns the regex patterns - */ - public void setRegex(List regexPatterns) { - if (CollectionUtils.isEmpty(this.regexPatterns)) { - this.regexPatterns = new ArrayList<>(); + public String getPropertyName() { + return propertyName; } - for (String regexPattern : regexPatterns) { - this.regexPatterns.add(Pattern.compile(regexPattern)); + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; } - } - public List getRegexPatterns() { - return regexPatterns; - } + /** + * Sets regex. + * + * @param regexPatterns the regex patterns + */ + public void setRegex(List regexPatterns) { + if (CollectionUtils.isEmpty(this.regexPatterns)) { + this.regexPatterns = new ArrayList<>(); + } + for (String regexPattern : regexPatterns) { + this.regexPatterns.add(Pattern.compile(regexPattern)); + } + } - public String getStringToSearchForPropertyValue() { - return stringToSearchForPropertyValue; - } + public List getRegexPatterns() { + return regexPatterns; + } - public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { - this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; - } + public String getStringToSearchForPropertyValue() { + return stringToSearchForPropertyValue; + } + public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java index 1f90db9cb3..b8ab508303 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca; -public enum ReferenceType { - GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER -} +public enum ReferenceType {GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java index 76ef37327e..836b2fedef 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -13,17 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca; - - import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; +import java.io.InputStream; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import org.apache.commons.collections.MapUtils; - import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -32,8 +38,6 @@ import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.onap.sdc.tosca.datatypes.model.NodeTemplate; -import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; @@ -41,8 +45,8 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationDataHandler; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedConsolidationDataHandler; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortConsolidationDataHandler; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceConsolidationDataHandler; import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; @@ -51,619 +55,519 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import java.io.InputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - public class TranslationContext { - private ManifestFile manifest; - - - private static final Map>> translationMapping; - private static final Map globalServiceTemplates; - private static final Map nameExtractorImplMap; - private static final List vfcGroupSubInterfaceExposedProperties; - private static final List enrichPortResourceProperties; - private static final ImplementationConfiguration vfcInstanceGroupConfiguration; - - private static Map supportedConsolidationComputeResources; - private static Map supportedConsolidationPortResources; - - private final FileContentHandler files = new FileContentHandler(); - private final Map manifestFiles = new HashMap<>(); - //Key - file name, value - file type - private final Set nestedHeatsFiles = new HashSet<>(); - private final FileContentHandler externalArtifacts = new FileContentHandler(); - // Key - heat file name,value - set of heat resource ids which were translated - private final Map> translatedResources = new HashMap<>(); - // Key - heat file name, value - translated Node template id - private final Map> heatStackGroupMembers = new HashMap<>(); - // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id - private final Map> translatedIds = new HashMap<>(); - // key - service template type, value - translated service templates - private final Map translatedServiceTemplates = new HashMap<>(); - //key - heat param name, value - shared resource data - private final Map heatSharedResourcesByParam = new HashMap<>(); - //key - translated substitute service template file name, value - source nested heat file name - private final Map nestedHeatFileName = new HashMap<>(); - //Key - heat file name,value - Map eith key - heat pseudo param name, - // value - translated tosca parameter name - private final Map> usedHeatPseudoParams = new HashMap<>(); - //Consolidation data gathered for Unified TOSCA model - private ConsolidationData consolidationData = new ConsolidationData(); - private Map unifiedSubstitutionData = new HashMap<>(); - private final Set unifiedHandledServiceTemplates = new HashSet<>(); - - private final Map>> requirementIdAppearanceInNodeTemplate = new HashMap<>(); - - private final Set serviceTemplatesWithoutNodeTemplateSection = new HashSet<>(); - - private final Set nodeTemplateIdsPointingToStWithoutNodeTemplates = new HashSet<>(); - - //Key - service template name, value - Map of key: node template id, value: properties with %index% - private final Map> indexVarProperties = new HashMap<>(); - - static { - Configuration config = ConfigurationManager.lookup(); - translationMapping = - config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY); - try { - globalServiceTemplates = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); - } catch (Exception exc) { - throw new RuntimeException("Failed to load GlobalTypes", exc); - } - nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, ImplementationConfiguration.class); - supportedConsolidationComputeResources = config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, ImplementationConfiguration.class); - supportedConsolidationPortResources = config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class); - enrichPortResourceProperties = config.getAsStringValues(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.ENRICH_PORT_RESOURCE_PROP); - vfcInstanceGroupConfiguration = getVfcInstanceGroupConfiguration(config); - vfcGroupSubInterfaceExposedProperties = config.getAsStringValues(ConfigConstants.UNIFIED_MODEL_NAMESPACE, - ConfigConstants.FULL_EXPOSED_PROPERTIES_KEY); - } - - - private static ImplementationConfiguration getVfcInstanceGroupConfiguration(Configuration config) { - Map supportedUnifiedModelProperties = - config.populateMap(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_MODEL_IMPL_KEY, - ImplementationConfiguration.class); - return MapUtils.isEmpty(supportedUnifiedModelProperties) ? null : supportedUnifiedModelProperties.get(ConfigConstants.VFC_INSTANCE_GROUP_KEY); - } - - public static boolean isVfcInstanceGroupingEnabled() { - return Objects.nonNull(vfcInstanceGroupConfiguration) && vfcInstanceGroupConfiguration.isEnable(); - } - - public static List getExposedVfcInstanceGroupingProperties() { - return vfcGroupSubInterfaceExposedProperties; - } - - public static List getEnrichPortResourceProperties() { - return enrichPortResourceProperties; - } - - public static Map getSupportedConsolidationComputeResources() { - return supportedConsolidationComputeResources; - } - - public static void setSupportedConsolidationComputeResources(Map supportedConsolidationComputeResources) { - TranslationContext.supportedConsolidationComputeResources = supportedConsolidationComputeResources; - } - - public static Map getSupportedConsolidationPortResources() { - return supportedConsolidationPortResources; - } - - public static void setSupportedConsolidationPortResources(Map supportedConsolidationPortResources) { - TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources; - } - - /** - * Get nameExtractor implemetation class instance. - * - * @param extractorImplKey configuration key for the implementation class - * @return implemetation class instance - */ - public static NameExtractor getNameExtractorImpl(String extractorImplKey) { - String nameExtractorImplClassName = nameExtractorImplMap.get(extractorImplKey).getImplementationClass(); - - return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class); - } - - public Map getUnifiedSubstitutionData() { - return unifiedSubstitutionData; - } - - public void setUnifiedSubstitutionData(Map unifiedSubstitutionData) { - this.unifiedSubstitutionData = unifiedSubstitutionData; - } - - public void addCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate); - } - - public Optional> getIndexVarProperties(String serviceTemplateName, String nodeTemplateId) { - ListMultimap serviceTemplateIndexVarProperties = this.indexVarProperties.get(serviceTemplateName); - if (Objects.nonNull(serviceTemplateIndexVarProperties)) { - return Optional.of(this.indexVarProperties.get(serviceTemplateName).get(nodeTemplateId)); - } - return Optional.empty(); - } - - public void addIndexVarProperties(String serviceTemplateName, String nodeTemplateId, List indexVarProperties) { - this.indexVarProperties.putIfAbsent(serviceTemplateName, ArrayListMultimap.create()); - this.indexVarProperties.get(serviceTemplateName).putAll(nodeTemplateId, indexVarProperties); - } - - public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId) { - return this.unifiedSubstitutionData.get(serviceTemplateName).getCleanedNodeTemplate(nodeTemplateId); - } - - public void addUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId, String unifiedNestedNodeTemplateId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId); - } - - public Optional getUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId) { - return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() : - this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId); - } - - public void addUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTypeId, String unifiedNestedNodeTypeId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId); - } - - public Optional getUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTemplateId) { - UnifiedSubstitutionData substitutionData = this.unifiedSubstitutionData.get(serviceTemplateName); - return substitutionData == null ? Optional.empty() : - substitutionData.getUnifiedNestedNodeTypeId(nestedNodeTemplateId); - } - - public ConsolidationData getConsolidationData() { - return consolidationData; - } - - public void setConsolidationData(ConsolidationData consolidationData) { - this.consolidationData = consolidationData; - } - - public Optional getConsolidationDataHandler(ConsolidationEntityType type) { - return consolidationData.getConsolidationDataHandler(type); - } - - public ComputeConsolidationDataHandler getComputeConsolidationDataHandler() { - return consolidationData.getComputeConsolidationDataHandler(); - } - - public PortConsolidationDataHandler getPortConsolidationDataHandler() { - return consolidationData.getPortConsolidationDataHandler(); - } - - public NestedConsolidationDataHandler getNestedConsolidationDataHandler() { - return consolidationData.getNestedConsolidationDataHandler(); - } - - public SubInterfaceConsolidationDataHandler getSubInterfaceConsolidationDataHandler() { - return consolidationData.getSubInterfaceConsolidationDataHandler(); - } - - public void addManifestFile(String fileName, FileData.Type fileType) { - this.manifestFiles.put(fileName, fileType); - } - - public Set getNestedHeatsFiles() { - return nestedHeatsFiles; - } - - public Map> getHeatStackGroupMembers() { - return heatStackGroupMembers; - } - - public FileContentHandler getFiles() { - return files; - } - - public void setFiles(Map files) { - this.files.setFiles(files); - } - - public InputStream getFileContentAsStream(final String fileName) { - return files.getFileContentAsStream(fileName); - } - - public void addFile(String name, byte[] content) { - files.addFile(name, content); - } - - public ManifestFile getManifest() { - return manifest; - } - - public void setManifest(ManifestFile manifest) { - this.manifest = manifest; - } - - public Map> getTranslatedResources() { - return translatedResources; - } - - public Map> getTranslatedIds() { - return translatedIds; - } - - public Set getAllTranslatedResourceIdsFromDiffNestedFiles(String - nestedHeatFileNameToSkip) { - Set allTranslatedResourceIds = new HashSet<>(); - - this.translatedIds.entrySet().stream().filter( - heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey() - .equals(nestedHeatFileNameToSkip)).forEach(heatFileNameToTranslatedIdsEntry -> - allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet()) - ); + private ManifestFile manifest; + private static final Map>> translationMapping; + private static final Map globalServiceTemplates; + private static final Map nameExtractorImplMap; + private static final List vfcGroupSubInterfaceExposedProperties; + private static final List enrichPortResourceProperties; + private static final ImplementationConfiguration vfcInstanceGroupConfiguration; + private static Map supportedConsolidationComputeResources; + private static Map supportedConsolidationPortResources; + private final FileContentHandler files = new FileContentHandler(); + private final Map manifestFiles = new HashMap<>(); + //Key - file name, value - file type + private final Set nestedHeatsFiles = new HashSet<>(); + private final FileContentHandler externalArtifacts = new FileContentHandler(); + // Key - heat file name,value - set of heat resource ids which were translated + private final Map> translatedResources = new HashMap<>(); + // Key - heat file name, value - translated Node template id + private final Map> heatStackGroupMembers = new HashMap<>(); + // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id + private final Map> translatedIds = new HashMap<>(); + // key - service template type, value - translated service templates + private final Map translatedServiceTemplates = new HashMap<>(); + //key - heat param name, value - shared resource data + private final Map heatSharedResourcesByParam = new HashMap<>(); + //key - translated substitute service template file name, value - source nested heat file name + private final Map nestedHeatFileName = new HashMap<>(); + //Key - heat file name,value - Map eith key - heat pseudo param name, + + // value - translated tosca parameter name + private final Map> usedHeatPseudoParams = new HashMap<>(); + //Consolidation data gathered for Unified TOSCA model + private ConsolidationData consolidationData = new ConsolidationData(); + private Map unifiedSubstitutionData = new HashMap<>(); + private final Set unifiedHandledServiceTemplates = new HashSet<>(); + private final Map>> requirementIdAppearanceInNodeTemplate = new HashMap<>(); + private final Set serviceTemplatesWithoutNodeTemplateSection = new HashSet<>(); + private final Set nodeTemplateIdsPointingToStWithoutNodeTemplates = new HashSet<>(); + //Key - service template name, value - Map of key: node template id, value: properties with %index% + private final Map> indexVarProperties = new HashMap<>(); + + static { + Configuration config = ConfigurationManager.lookup(); + translationMapping = config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY); + try { + globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); + } catch (Exception exc) { + throw new RuntimeException("Failed to load GlobalTypes", exc); + } + nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, + ImplementationConfiguration.class); + supportedConsolidationComputeResources = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, + ImplementationConfiguration.class); + supportedConsolidationPortResources = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, + ImplementationConfiguration.class); + enrichPortResourceProperties = config + .getAsStringValues(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.ENRICH_PORT_RESOURCE_PROP); + vfcInstanceGroupConfiguration = getVfcInstanceGroupConfiguration(config); + vfcGroupSubInterfaceExposedProperties = config + .getAsStringValues(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.FULL_EXPOSED_PROPERTIES_KEY); + } + + private static ImplementationConfiguration getVfcInstanceGroupConfiguration(Configuration config) { + Map supportedUnifiedModelProperties = config + .populateMap(ConfigConstants.UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_MODEL_IMPL_KEY, ImplementationConfiguration.class); + return MapUtils.isEmpty(supportedUnifiedModelProperties) ? null : supportedUnifiedModelProperties.get(ConfigConstants.VFC_INSTANCE_GROUP_KEY); + } + + public static boolean isVfcInstanceGroupingEnabled() { + return Objects.nonNull(vfcInstanceGroupConfiguration) && vfcInstanceGroupConfiguration.isEnable(); + } + + public static List getExposedVfcInstanceGroupingProperties() { + return vfcGroupSubInterfaceExposedProperties; + } + + public static List getEnrichPortResourceProperties() { + return enrichPortResourceProperties; + } + + public static Map getSupportedConsolidationComputeResources() { + return supportedConsolidationComputeResources; + } + + public static void setSupportedConsolidationComputeResources(Map supportedConsolidationComputeResources) { + TranslationContext.supportedConsolidationComputeResources = supportedConsolidationComputeResources; + } + + public static Map getSupportedConsolidationPortResources() { + return supportedConsolidationPortResources; + } + + public static void setSupportedConsolidationPortResources(Map supportedConsolidationPortResources) { + TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources; + } + + /** + * Get nameExtractor implemetation class instance. + * + * @param extractorImplKey configuration key for the implementation class + * @return implemetation class instance + */ + public static NameExtractor getNameExtractorImpl(String extractorImplKey) { + String nameExtractorImplClassName = nameExtractorImplMap.get(extractorImplKey).getImplementationClass(); + return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class); + } + + public Map getUnifiedSubstitutionData() { + return unifiedSubstitutionData; + } + + public void setUnifiedSubstitutionData(Map unifiedSubstitutionData) { + this.unifiedSubstitutionData = unifiedSubstitutionData; + } + + public void addCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, + NodeTemplate nodeTemplate) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate); + } + + public Optional> getIndexVarProperties(String serviceTemplateName, String nodeTemplateId) { + ListMultimap serviceTemplateIndexVarProperties = this.indexVarProperties.get(serviceTemplateName); + if (Objects.nonNull(serviceTemplateIndexVarProperties)) { + return Optional.of(this.indexVarProperties.get(serviceTemplateName).get(nodeTemplateId)); + } + return Optional.empty(); + } + + public void addIndexVarProperties(String serviceTemplateName, String nodeTemplateId, List indexVarProperties) { + this.indexVarProperties.putIfAbsent(serviceTemplateName, ArrayListMultimap.create()); + this.indexVarProperties.get(serviceTemplateName).putAll(nodeTemplateId, indexVarProperties); + } + + public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName, String nodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName).getCleanedNodeTemplate(nodeTemplateId); + } + + public void addUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId, String unifiedNestedNodeTemplateId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId); + } + + public Optional getUnifiedNestedNodeTemplateId(String serviceTemplateName, String nestedNodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() + : this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId); + } + + public void addUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTypeId, String unifiedNestedNodeTypeId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId); + } - return allTranslatedResourceIds; - } + public Optional getUnifiedNestedNodeTypeId(String serviceTemplateName, String nestedNodeTemplateId) { + UnifiedSubstitutionData substitutionData = this.unifiedSubstitutionData.get(serviceTemplateName); + return substitutionData == null ? Optional.empty() : substitutionData.getUnifiedNestedNodeTypeId(nestedNodeTemplateId); + } - // get tosca name from mapping configuration file - //element type - parameter/attribute - // element name - heat parameter/attribute name - //return value - tosca parameter/attribute name - public String getElementMapping(String resourceType, String elementType, String elementName) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return null; - } - if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { - return null; - } - return translationMapping.get(resourceType).get(elementType).get(elementName); - } - - public Map getElementMapping(String resourceType, String elementType) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return null; - } - return translationMapping.get(resourceType).get(elementType); - } + public ConsolidationData getConsolidationData() { + return consolidationData; + } - public Set getElementSet(String resourceType, String elementType) { - if (Objects.isNull(translationMapping.get(resourceType))) { - return new HashSet<>(); + public void setConsolidationData(ConsolidationData consolidationData) { + this.consolidationData = consolidationData; } - if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { - return new HashSet<>(); + + public Optional getConsolidationDataHandler(ConsolidationEntityType type) { + return consolidationData.getConsolidationDataHandler(type); } - return translationMapping.get(resourceType).get(elementType).keySet(); - } - public Map getTranslatedServiceTemplates() { - return translatedServiceTemplates; - } - - public ServiceTemplate getGlobalSubstitutionServiceTemplate() { - return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - } - - public FileContentHandler getExternalArtifacts() { - return externalArtifacts; - } - - public void addExternalArtifacts(String name, byte[] content) { - this.externalArtifacts.addFile(name, content); - } - - public Map getHeatSharedResourcesByParam() { - return heatSharedResourcesByParam; - } - - public void addHeatSharedResourcesByParam(String parameterName, String resourceId, - Resource resource) { - this.addHeatSharedResourcesByParam(parameterName, - new TranslatedHeatResource(resourceId, resource)); - } - - private void addHeatSharedResourcesByParam(String parameterName, - TranslatedHeatResource translatedHeatResource) { - this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); - } - - public Map getGlobalServiceTemplates() { - return globalServiceTemplates; - } - - public Map getNestedHeatFileName() { - return nestedHeatFileName; - } - - public void addNestedHeatFileName(String substituteServiceTempalteName, - String nestedHeatFileName) { - this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName); - } - - public Map> getUsedHeatPseudoParams() { - return usedHeatPseudoParams; - } - - public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String - translatedToscaParam) { - if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) { - this.usedHeatPseudoParams.put(heatFileName, new HashMap<>()); - } - this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam); - } - - public Set getTranslatedResourceIdsFromOtherFiles(String fileNameToIgnore){ - if(MapUtils.isEmpty(this.translatedResources)){ - return new HashSet<>(); - } - - Set translatedResourceIds = new HashSet<>(); - - this.translatedResources.entrySet().stream().filter(entry -> !entry.getKey().equals(fileNameToIgnore)) - .forEach(entry -> translatedResourceIds.addAll(entry.getValue())); - - return translatedResourceIds; - } - - /** - * Add the unified substitution data info in context. Contains a mapping of original node - * template id and the new node template id in the abstract substitute - * - * @param serviceTemplateFileName the service template file name - * @param originalNodeTemplateId the original node template id - * @param abstractNodeTemplateId the node template id in the abstract substitute - */ - public void addUnifiedSubstitutionData(String serviceTemplateFileName, - String originalNodeTemplateId, - String abstractNodeTemplateId) { - - Map nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData() - .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) - .getNodesRelatedAbstractNode(); - - if (nodeAbstractNodeTemplateIdMap == null) { - nodeAbstractNodeTemplateIdMap = new HashMap<>(); - } - - if(nodeAbstractNodeTemplateIdMap.containsKey(originalNodeTemplateId)){ - throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(originalNodeTemplateId).build()); - } - nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); - this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode( - nodeAbstractNodeTemplateIdMap); - } - - /** - * Add the unified substitution data info in context. Contains a mapping of original node - * template id and the new node template id in the abstract substitute - * - * @param serviceTemplateFileName the service template file name - * @param originalNodeTemplateId the original node template id - * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution - * service template - */ - public void addSubstitutionServiceTemplateUnifiedSubstitutionData( - String serviceTemplateFileName, - String originalNodeTemplateId, - String substitutionServiceTemplateNodeTemplateId) { - - Map nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this - .getUnifiedSubstitutionData() - .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) - .getNodesRelatedSubstitutionServiceTemplateNode(); - - if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) { - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>(); - } - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId, - substitutionServiceTemplateNodeTemplateId); - this.getUnifiedSubstitutionData().get(serviceTemplateFileName) - .setNodesRelatedSubstitutionServiceTemplateNode( - nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap); - } - - /** - * Get unified abstract node template which is mapped to the input node template id. - * - * @param serviceTemplate the service template - * @param nodeTemplateId the node template id - */ - public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate, - String nodeTemplateId) { - UnifiedSubstitutionData unifiedSubsData = - this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - return unifiedSubsData.getNodesRelatedAbstractNode().get(nodeTemplateId); - } - - /** - * Get unified node template in the substitution service template which is mapped to the - * original input node template id. - * - * @param serviceTemplate the service template - * @param nodeTemplateId the node template id - */ - public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate, - String nodeTemplateId) { - UnifiedSubstitutionData unifiedSubsData = - this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - return unifiedSubsData.getNodesRelatedSubstitutionServiceTemplateNode() - .get(nodeTemplateId); - } - - public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName, - String computeType) { - return this.unifiedSubstitutionData.get(serviceTemplateName) - .getHandledNestedComputeNodeTemplateIndex(computeType); - } - - public void updateHandledComputeType(String serviceTemplateName, - String handledComputeType, - String nestedServiceTemplateFileName) { - String globalSTName = - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - this.unifiedSubstitutionData.putIfAbsent( - globalSTName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(globalSTName) - .addHandledComputeType(handledComputeType); - this.unifiedSubstitutionData.get(globalSTName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); - - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); - } - - public void addHandledComputeTypeInServiceTemplate(String serviceTemplateName, - String handledComputeType){ - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addHandledComputeType(handledComputeType); - } - - public boolean isComputeTypeHandledInServiceTemplate(String serviceTemplateName, - String computeType) { - return !Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName)) - && this.unifiedSubstitutionData.get(serviceTemplateName) - .isComputeTypeHandledInServiceTemplate(computeType); - } - - public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName, - String nestedServiceTemplateFileName) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return false; - } - return this.unifiedSubstitutionData.get(serviceTemplateName) - .isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName); - } - - public Set getAllRelatedNestedNodeTypeIds() { - String globalName = "GlobalSubstitutionTypes"; - if (Objects.isNull(this.unifiedSubstitutionData) - || Objects.isNull(this.unifiedSubstitutionData.get(globalName))) { - return new HashSet<>(); - } - - return this.unifiedSubstitutionData.get(globalName).getAllRelatedNestedNodeTypeIds(); - } - - public boolean isUnifiedHandledServiceTemplate(ServiceTemplate serviceTemplate) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - return unifiedHandledServiceTemplates.contains(serviceTemplateFileName); - } - - - - public void addUnifiedHandledServiceTeamplte(ServiceTemplate serviceTemplate) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - this.unifiedHandledServiceTemplates.add(serviceTemplateFileName); - } - - public boolean isNestedNodeWasHandled(String serviceTemplateName, - String nestedNodeTemplateId) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return false; - } - return this.unifiedSubstitutionData.get(serviceTemplateName) - .isNestedNodeWasHandled(nestedNodeTemplateId); - } - - public void addNestedNodeAsHandled(String serviceTemplateName, - String nestedNodeTemplateId) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName) - .addHandledNestedNodes(nestedNodeTemplateId); - } - - public void updateUsedTimesForNestedComputeNodeType(String serviceTemplateName, - String computeType) { - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - - this.unifiedSubstitutionData.get(serviceTemplateName) - .updateUsedTimesForNestedComputeNodeType(computeType); - } - - public int getGlobalNodeTypeIndex(String serviceTemplateName, - String computeType) { - if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { - return 0; - } - return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex - (computeType); - } - - public void addNewPropertyIdToNodeTemplate(String serviceTemplateName, - String newPropertyId, - Object origPropertyValue){ - this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); - this.unifiedSubstitutionData.get(serviceTemplateName).addNewPropertyIdToNodeTemplate( - newPropertyId, origPropertyValue); - } - - public Optional getNewPropertyInputParamId(String serviceTemplateName, - String newPropertyId){ - if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ - return Optional.empty(); - } - - return this.unifiedSubstitutionData.get(serviceTemplateName).getNewPropertyInputParam - (newPropertyId); - } + public ComputeConsolidationDataHandler getComputeConsolidationDataHandler() { + return consolidationData.getComputeConsolidationDataHandler(); + } - public Map getAllNewPropertyInputParamIdsPerNodeTenplateId(String serviceTemplateName){ - if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ - return new HashMap<>(); + public PortConsolidationDataHandler getPortConsolidationDataHandler() { + return consolidationData.getPortConsolidationDataHandler(); } - return this.unifiedSubstitutionData.get(serviceTemplateName).getAllNewPropertyInputParamIds(); + public NestedConsolidationDataHandler getNestedConsolidationDataHandler() { + return consolidationData.getNestedConsolidationDataHandler(); + } - } + public SubInterfaceConsolidationDataHandler getSubInterfaceConsolidationDataHandler() { + return consolidationData.getSubInterfaceConsolidationDataHandler(); + } - public boolean isServiceTemplateWithoutNodeTemplatesSection(String serviceTemplateName){ - return Objects.nonNull(serviceTemplateName) - && serviceTemplatesWithoutNodeTemplateSection.contains(serviceTemplateName); - } + public void addManifestFile(String fileName, FileData.Type fileType) { + this.manifestFiles.put(fileName, fileType); + } - public void addServiceTemplateWithoutNodeTemplates(String serviceTemplateName){ - this.serviceTemplatesWithoutNodeTemplateSection.add(serviceTemplateName); - } + public Set getNestedHeatsFiles() { + return nestedHeatsFiles; + } - public void addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId){ - this.nodeTemplateIdsPointingToStWithoutNodeTemplates.add(nodeTemplateId); - } + public Map> getHeatStackGroupMembers() { + return heatStackGroupMembers; + } - public boolean isNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId){ - return Objects.nonNull(nodeTemplateId) - && nodeTemplateIdsPointingToStWithoutNodeTemplates.contains(nodeTemplateId); - } + public FileContentHandler getFiles() { + return files; + } - public void updateRequirementAssignmentIdIndex(String serviceTemplateName, - String nodeTemplateId, - String requirementId){ - requirementIdAppearanceInNodeTemplate.putIfAbsent(serviceTemplateName, new HashMap<>()); - requirementIdAppearanceInNodeTemplate - .get(serviceTemplateName).putIfAbsent(nodeTemplateId, new HashMap<>()); + public void setFiles(Map files) { + this.files.setFiles(files); + } + + public InputStream getFileContentAsStream(final String fileName) { + return files.getFileContentAsStream(fileName); + } + + public void addFile(String name, byte[] content) { + files.addFile(name, content); + } - Map requirementIdToAppearance = - requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).get(nodeTemplateId); + public ManifestFile getManifest() { + return manifest; + } + + public void setManifest(ManifestFile manifest) { + this.manifest = manifest; + } + + public Map> getTranslatedResources() { + return translatedResources; + } - if(requirementIdToAppearance.containsKey(requirementId)){ - requirementIdToAppearance - .put(requirementId, requirementIdToAppearance.get(requirementId) + 1); - } else { - requirementIdToAppearance.put(requirementId, 0); + public Map> getTranslatedIds() { + return translatedIds; } - } + public Set getAllTranslatedResourceIdsFromDiffNestedFiles(String nestedHeatFileNameToSkip) { + Set allTranslatedResourceIds = new HashSet<>(); + this.translatedIds.entrySet().stream() + .filter(heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey().equals(nestedHeatFileNameToSkip)) + .forEach(heatFileNameToTranslatedIdsEntry -> allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet())); + return allTranslatedResourceIds; + } + // get tosca name from mapping configuration file + + //element type - parameter/attribute + + // element name - heat parameter/attribute name + + //return value - tosca parameter/attribute name + public String getElementMapping(String resourceType, String elementType, String elementName) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType).get(elementName); + } + + public Map getElementMapping(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType); + } + + public Set getElementSet(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return new HashSet<>(); + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return new HashSet<>(); + } + return translationMapping.get(resourceType).get(elementType).keySet(); + } + + public Map getTranslatedServiceTemplates() { + return translatedServiceTemplates; + } + + public ServiceTemplate getGlobalSubstitutionServiceTemplate() { + return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + } + + public FileContentHandler getExternalArtifacts() { + return externalArtifacts; + } + + public void addExternalArtifacts(String name, byte[] content) { + this.externalArtifacts.addFile(name, content); + } + + public Map getHeatSharedResourcesByParam() { + return heatSharedResourcesByParam; + } + + public void addHeatSharedResourcesByParam(String parameterName, String resourceId, Resource resource) { + this.addHeatSharedResourcesByParam(parameterName, new TranslatedHeatResource(resourceId, resource)); + } + + private void addHeatSharedResourcesByParam(String parameterName, TranslatedHeatResource translatedHeatResource) { + this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); + } + + public Map getGlobalServiceTemplates() { + return globalServiceTemplates; + } + + public Map getNestedHeatFileName() { + return nestedHeatFileName; + } + + public void addNestedHeatFileName(String substituteServiceTempalteName, String nestedHeatFileName) { + this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName); + } + + public Map> getUsedHeatPseudoParams() { + return usedHeatPseudoParams; + } + + public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String translatedToscaParam) { + if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) { + this.usedHeatPseudoParams.put(heatFileName, new HashMap<>()); + } + this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam); + } + + public Set getTranslatedResourceIdsFromOtherFiles(String fileNameToIgnore) { + if (MapUtils.isEmpty(this.translatedResources)) { + return new HashSet<>(); + } + Set translatedResourceIds = new HashSet<>(); + this.translatedResources.entrySet().stream().filter(entry -> !entry.getKey().equals(fileNameToIgnore)) + .forEach(entry -> translatedResourceIds.addAll(entry.getValue())); + return translatedResourceIds; + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node template id and the new node template id in the abstract + * substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param abstractNodeTemplateId the node template id in the abstract substitute + */ + public void addUnifiedSubstitutionData(String serviceTemplateFileName, String originalNodeTemplateId, String abstractNodeTemplateId) { + Map nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()).getNodesRelatedAbstractNode(); + if (nodeAbstractNodeTemplateIdMap == null) { + nodeAbstractNodeTemplateIdMap = new HashMap<>(); + } + if (nodeAbstractNodeTemplateIdMap.containsKey(originalNodeTemplateId)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(originalNodeTemplateId).build()); + } + nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode(nodeAbstractNodeTemplateIdMap); + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node template id and the new node template id in the abstract + * substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution service template + */ + public void addSubstitutionServiceTemplateUnifiedSubstitutionData(String serviceTemplateFileName, String originalNodeTemplateId, + String substitutionServiceTemplateNodeTemplateId) { + Map nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this.getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()).getNodesRelatedSubstitutionServiceTemplateNode(); + if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) { + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>(); + } + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId, substitutionServiceTemplateNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName) + .setNodesRelatedSubstitutionServiceTemplateNode(nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap); + } + + /** + * Get unified abstract node template which is mapped to the input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate, String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubsData = this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubsData.getNodesRelatedAbstractNode().get(nodeTemplateId); + } + + /** + * Get unified node template in the substitution service template which is mapped to the original input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate, String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubsData = this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubsData.getNodesRelatedSubstitutionServiceTemplateNode().get(nodeTemplateId); + } + + public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName, String computeType) { + return this.unifiedSubstitutionData.get(serviceTemplateName).getHandledNestedComputeNodeTemplateIndex(computeType); + } + + public void updateHandledComputeType(String serviceTemplateName, String handledComputeType, String nestedServiceTemplateFileName) { + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + this.unifiedSubstitutionData.putIfAbsent(globalSTName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(globalSTName).addHandledComputeType(handledComputeType); + this.unifiedSubstitutionData.get(globalSTName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandlesNestedServiceTemplate(nestedServiceTemplateFileName); + } + + public void addHandledComputeTypeInServiceTemplate(String serviceTemplateName, String handledComputeType) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandledComputeType(handledComputeType); + } + + public boolean isComputeTypeHandledInServiceTemplate(String serviceTemplateName, String computeType) { + return !Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName)) && this.unifiedSubstitutionData.get(serviceTemplateName) + .isComputeTypeHandledInServiceTemplate(computeType); + } + + public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName, String nestedServiceTemplateFileName) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return false; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName); + } + + public Set getAllRelatedNestedNodeTypeIds() { + String globalName = "GlobalSubstitutionTypes"; + if (Objects.isNull(this.unifiedSubstitutionData) || Objects.isNull(this.unifiedSubstitutionData.get(globalName))) { + return new HashSet<>(); + } + return this.unifiedSubstitutionData.get(globalName).getAllRelatedNestedNodeTypeIds(); + } + + public boolean isUnifiedHandledServiceTemplate(ServiceTemplate serviceTemplate) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + return unifiedHandledServiceTemplates.contains(serviceTemplateFileName); + } + + public void addUnifiedHandledServiceTeamplte(ServiceTemplate serviceTemplate) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + this.unifiedHandledServiceTemplates.add(serviceTemplateFileName); + } + + public boolean isNestedNodeWasHandled(String serviceTemplateName, String nestedNodeTemplateId) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return false; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).isNestedNodeWasHandled(nestedNodeTemplateId); + } + + public void addNestedNodeAsHandled(String serviceTemplateName, String nestedNodeTemplateId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addHandledNestedNodes(nestedNodeTemplateId); + } + + public void updateUsedTimesForNestedComputeNodeType(String serviceTemplateName, String computeType) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).updateUsedTimesForNestedComputeNodeType(computeType); + } + + public int getGlobalNodeTypeIndex(String serviceTemplateName, String computeType) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return 0; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex(computeType); + } + + public void addNewPropertyIdToNodeTemplate(String serviceTemplateName, String newPropertyId, Object origPropertyValue) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addNewPropertyIdToNodeTemplate(newPropertyId, origPropertyValue); + } + + public Optional getNewPropertyInputParamId(String serviceTemplateName, String newPropertyId) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return Optional.empty(); + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getNewPropertyInputParam(newPropertyId); + } + + public Map getAllNewPropertyInputParamIdsPerNodeTenplateId(String serviceTemplateName) { + if (Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))) { + return new HashMap<>(); + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getAllNewPropertyInputParamIds(); + } + + public boolean isServiceTemplateWithoutNodeTemplatesSection(String serviceTemplateName) { + return Objects.nonNull(serviceTemplateName) && serviceTemplatesWithoutNodeTemplateSection.contains(serviceTemplateName); + } + + public void addServiceTemplateWithoutNodeTemplates(String serviceTemplateName) { + this.serviceTemplatesWithoutNodeTemplateSection.add(serviceTemplateName); + } + + public void addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId) { + this.nodeTemplateIdsPointingToStWithoutNodeTemplates.add(nodeTemplateId); + } + + public boolean isNodeTemplateIdPointsToStWithoutNodeTemplates(String nodeTemplateId) { + return Objects.nonNull(nodeTemplateId) && nodeTemplateIdsPointingToStWithoutNodeTemplates.contains(nodeTemplateId); + } + + public void updateRequirementAssignmentIdIndex(String serviceTemplateName, String nodeTemplateId, String requirementId) { + requirementIdAppearanceInNodeTemplate.putIfAbsent(serviceTemplateName, new HashMap<>()); + requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).putIfAbsent(nodeTemplateId, new HashMap<>()); + Map requirementIdToAppearance = requirementIdAppearanceInNodeTemplate.get(serviceTemplateName).get(nodeTemplateId); + if (requirementIdToAppearance.containsKey(requirementId)) { + requirementIdToAppearance.put(requirementId, requirementIdToAppearance.get(requirementId) + 1); + } else { + requirementIdToAppearance.put(requirementId, 0); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java index 99b3f502b4..1dbef6b992 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ContrailServiceInstanceTo.java @@ -13,22 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; public class ContrailServiceInstanceTo { + private final ServiceTemplate nestedSubstitutionServiceTemplate; private final NodeTemplate substitutedNodeTemplate; private final String heatStackGroupKey; private final boolean orderedInterfaces; private final String computeNodeTemplateId; - public ContrailServiceInstanceTo(ServiceTemplate nestedSubstitutionServiceTemplate, - NodeTemplate substitutedNodeTemplate, String heatStackGroupKey, - boolean orderedInterfaces, String computeNodeTemplateId) { + public ContrailServiceInstanceTo(ServiceTemplate nestedSubstitutionServiceTemplate, NodeTemplate substitutedNodeTemplate, + String heatStackGroupKey, boolean orderedInterfaces, String computeNodeTemplateId) { this.nestedSubstitutionServiceTemplate = nestedSubstitutionServiceTemplate; this.substitutedNodeTemplate = substitutedNodeTemplate; this.heatStackGroupKey = heatStackGroupKey; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java index b156078430..5f78e750ad 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/FileDataCollection.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,119 +17,116 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; - import java.util.ArrayList; import java.util.Collection; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; public class FileDataCollection { - Collection baseFiles; - Collection addOnFiles; - Collection nestedFiles; - Collection artifactFiles; - Collection HelmFiles; - - public Collection getBaseFile() { - return baseFiles; - } - - public Collection getHelmFile() { - return HelmFiles; - } - - public void setBaseFile(Collection baseFiles) { - this.baseFiles = baseFiles; - } - - public Collection getAddOnFiles() { - return addOnFiles; - } - - public void setAddOnFiles(Collection addOnFiles) { - this.addOnFiles = addOnFiles; - } - - public Collection getNestedFiles() { - return nestedFiles; - } - - public void setNestedFiles(Collection nestedFiles) { - this.nestedFiles = nestedFiles; - } - - public Collection getBaseFiles() { - return baseFiles; - } - - public void setBaseFiles(Collection baseFiles) { - this.baseFiles = baseFiles; - } - - public Collection getArtifactFiles() { - return artifactFiles; - } - - public void setArtifactFiles(Collection artifactFiles) { - this.artifactFiles = artifactFiles; - } - - /** - * Add add on files. - * - * @param addonFile the addon file - */ - public void addAddOnFiles(FileData addonFile) { - if (this.addOnFiles == null) { - this.addOnFiles = new ArrayList<>(); - } - this.addOnFiles.add(addonFile); - } - - /** - * Add nested files. - * - * @param nestedFile the nested file - */ - public void addNestedFiles(FileData nestedFile) { - if (this.nestedFiles == null) { - this.nestedFiles = new ArrayList<>(); - } - this.nestedFiles.add(nestedFile); - } - - /** - * Add base files. - * - * @param baseFile the base file - */ - public void addBaseFiles(FileData baseFile) { - if (this.baseFiles == null) { - this.baseFiles = new ArrayList<>(); - } - this.baseFiles.add(baseFile); - } - - public void addHelmFiles(FileData helmFile) { - if (this.HelmFiles == null) { - this.HelmFiles = new ArrayList<>(); - } - this.HelmFiles.add(helmFile); - } - - /** - * Add artifact files. - * - * @param artifactFile the artifact file - */ - public void addArtifactFiles(FileData artifactFile) { - if (this.artifactFiles == null) { - this.artifactFiles = new ArrayList<>(); - } - this.artifactFiles.add(artifactFile); - } + Collection baseFiles; + Collection addOnFiles; + Collection nestedFiles; + Collection artifactFiles; + Collection HelmFiles; + + public Collection getBaseFile() { + return baseFiles; + } + + public void setBaseFile(Collection baseFiles) { + this.baseFiles = baseFiles; + } + + public Collection getHelmFile() { + return HelmFiles; + } + + public Collection getAddOnFiles() { + return addOnFiles; + } + + public void setAddOnFiles(Collection addOnFiles) { + this.addOnFiles = addOnFiles; + } + + public Collection getNestedFiles() { + return nestedFiles; + } + + public void setNestedFiles(Collection nestedFiles) { + this.nestedFiles = nestedFiles; + } + + public Collection getBaseFiles() { + return baseFiles; + } + + public void setBaseFiles(Collection baseFiles) { + this.baseFiles = baseFiles; + } + + public Collection getArtifactFiles() { + return artifactFiles; + } + + public void setArtifactFiles(Collection artifactFiles) { + this.artifactFiles = artifactFiles; + } + + /** + * Add add on files. + * + * @param addonFile the addon file + */ + public void addAddOnFiles(FileData addonFile) { + if (this.addOnFiles == null) { + this.addOnFiles = new ArrayList<>(); + } + this.addOnFiles.add(addonFile); + } + + /** + * Add nested files. + * + * @param nestedFile the nested file + */ + public void addNestedFiles(FileData nestedFile) { + if (this.nestedFiles == null) { + this.nestedFiles = new ArrayList<>(); + } + this.nestedFiles.add(nestedFile); + } + + /** + * Add base files. + * + * @param baseFile the base file + */ + public void addBaseFiles(FileData baseFile) { + if (this.baseFiles == null) { + this.baseFiles = new ArrayList<>(); + } + this.baseFiles.add(baseFile); + } + + public void addHelmFiles(FileData helmFile) { + if (this.HelmFiles == null) { + this.HelmFiles = new ArrayList<>(); + } + this.HelmFiles.add(helmFile); + } + + /** + * Add artifact files. + * + * @param artifactFile the artifact file + */ + public void addArtifactFiles(FileData artifactFile) { + if (this.artifactFiles == null) { + this.artifactFiles = new ArrayList<>(); + } + this.artifactFiles.add(artifactFile); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java index 24eef115e2..5cfe9185d0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,55 +17,53 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - import org.openecomp.sdc.heat.datatypes.manifest.FileData; - public class ResourceFileDataAndIDs { - private String resourceId; - private String translatedResourceId; - private FileData fileData; - public ResourceFileDataAndIDs() { - } + private String resourceId; + private String translatedResourceId; + private FileData fileData; + + public ResourceFileDataAndIDs() { + } - /** - * Instantiates a new Resource file data and i ds. - * - * @param resourceId the resource id - * @param translatedResourceId the translated resource id - * @param fileData the file data - */ - public ResourceFileDataAndIDs(String resourceId, String translatedResourceId, FileData fileData) { - this.resourceId = resourceId; - this.translatedResourceId = translatedResourceId; - this.fileData = fileData; - } + /** + * Instantiates a new Resource file data and i ds. + * + * @param resourceId the resource id + * @param translatedResourceId the translated resource id + * @param fileData the file data + */ + public ResourceFileDataAndIDs(String resourceId, String translatedResourceId, FileData fileData) { + this.resourceId = resourceId; + this.translatedResourceId = translatedResourceId; + this.fileData = fileData; + } - public String getResourceId() { - return resourceId; - } + public String getResourceId() { + return resourceId; + } - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } - public String getTranslatedResourceId() { - return translatedResourceId; - } + public String getTranslatedResourceId() { + return translatedResourceId; + } - public void setTranslatedResourceId(String translatedResourceId) { - this.translatedResourceId = translatedResourceId; - } + public void setTranslatedResourceId(String translatedResourceId) { + this.translatedResourceId = translatedResourceId; + } - public FileData getFileData() { - return fileData; - } + public FileData getFileData() { + return fileData; + } - public void setFileData(FileData fileData) { - this.fileData = fileData; - } + public void setFileData(FileData fileData) { + this.fileData = fileData; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java index 617618c822..e754a43083 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,116 +17,108 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; - import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; public class TranslateTo { - private String heatFileName; - private ServiceTemplate serviceTemplate; - private HeatOrchestrationTemplate heatOrchestrationTemplate; - private Resource resource; - private String resourceId; - private String translatedId; - private TranslationContext context; - - public TranslateTo() { - } - - /** - * Instantiates a new Translate to. - * - * @param heatFileName the heat file name - * @param serviceTemplate the service template - * @param heatOrchestrationTemplate the heat orchestration template - * @param resource the resource - * @param resourceId the resource id - * @param translatedId the translated id - * @param context the context - */ - public TranslateTo(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, - String resourceId, String translatedId, TranslationContext context) { - this.heatFileName = heatFileName; - this.serviceTemplate = serviceTemplate; - this.heatOrchestrationTemplate = heatOrchestrationTemplate; - this.resource = resource; - this.resourceId = resourceId; - this.translatedId = translatedId; - this.context = context; - } - - public String getHeatFileName() { - return heatFileName; - } - - public void setHeatFileName(String heatFileName) { - this.heatFileName = heatFileName; - } - - public ServiceTemplate getServiceTemplate() { - return serviceTemplate; - } - - public void setServiceTemplate(ServiceTemplate serviceTemplate) { - this.serviceTemplate = serviceTemplate; - } - - public HeatOrchestrationTemplate getHeatOrchestrationTemplate() { - return heatOrchestrationTemplate; - } - - public void setHeatOrchestrationTemplate(HeatOrchestrationTemplate heatOrchestrationTemplate) { - this.heatOrchestrationTemplate = heatOrchestrationTemplate; - } - - public Resource getResource() { - return resource; - } - - public void setResource(Resource resource) { - this.resource = resource; - } - - public String getResourceId() { - return resourceId; - } - - public void setResourceId(String resourceId) { - this.resourceId = resourceId; - } - - public String getTranslatedId() { - return translatedId; - } - - public void setTranslatedId(String translatedId) { - this.translatedId = translatedId; - } - - public TranslationContext getContext() { - return context; - } - - public void setContext(TranslationContext context) { - this.context = context; - } - - @Override - public String toString() { - return "TranslateTo{" - + "heatFileName='" + heatFileName + '\'' - + ", serviceTemplate=" + serviceTemplate - + ", heatOrchestrationTemplate=" + heatOrchestrationTemplate - + ", resource=" + resource - + ", resourceId='" + resourceId + '\'' - + ", translatedId='" + translatedId + '\'' - + ", context=" + context - + '}'; - } + + private String heatFileName; + private ServiceTemplate serviceTemplate; + private HeatOrchestrationTemplate heatOrchestrationTemplate; + private Resource resource; + private String resourceId; + private String translatedId; + private TranslationContext context; + + public TranslateTo() { + } + + /** + * Instantiates a new Translate to. + * + * @param heatFileName the heat file name + * @param serviceTemplate the service template + * @param heatOrchestrationTemplate the heat orchestration template + * @param resource the resource + * @param resourceId the resource id + * @param translatedId the translated id + * @param context the context + */ + public TranslateTo(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, + String resourceId, String translatedId, TranslationContext context) { + this.heatFileName = heatFileName; + this.serviceTemplate = serviceTemplate; + this.heatOrchestrationTemplate = heatOrchestrationTemplate; + this.resource = resource; + this.resourceId = resourceId; + this.translatedId = translatedId; + this.context = context; + } + + public String getHeatFileName() { + return heatFileName; + } + + public void setHeatFileName(String heatFileName) { + this.heatFileName = heatFileName; + } + + public ServiceTemplate getServiceTemplate() { + return serviceTemplate; + } + + public void setServiceTemplate(ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } + + public HeatOrchestrationTemplate getHeatOrchestrationTemplate() { + return heatOrchestrationTemplate; + } + + public void setHeatOrchestrationTemplate(HeatOrchestrationTemplate heatOrchestrationTemplate) { + this.heatOrchestrationTemplate = heatOrchestrationTemplate; + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + public String getTranslatedId() { + return translatedId; + } + + public void setTranslatedId(String translatedId) { + this.translatedId = translatedId; + } + + public TranslationContext getContext() { + return context; + } + + public void setContext(TranslationContext context) { + this.context = context; + } + + @Override + public String toString() { + return "TranslateTo{" + "heatFileName='" + heatFileName + '\'' + ", serviceTemplate=" + serviceTemplate + ", heatOrchestrationTemplate=" + + heatOrchestrationTemplate + ", resource=" + resource + ", resourceId='" + resourceId + '\'' + ", translatedId='" + translatedId + '\'' + + ", context=" + context + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java index da46e56018..5be053cbef 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslatedHeatResource.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,33 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.openecomp.sdc.heat.datatypes.model.Resource; public class TranslatedHeatResource { - private String translatedId; - private Resource heatResource; - public TranslatedHeatResource(String translatedId, Resource heatResource) { - this.translatedId = translatedId; - this.heatResource = heatResource; - } + private String translatedId; + private Resource heatResource; + + public TranslatedHeatResource(String translatedId, Resource heatResource) { + this.translatedId = translatedId; + this.heatResource = heatResource; + } - public String getTranslatedId() { - return translatedId; - } + public String getTranslatedId() { + return translatedId; + } - public void setTranslatedId(String translatedId) { - this.translatedId = translatedId; - } + public void setTranslatedId(String translatedId) { + this.translatedId = translatedId; + } - public Resource getHeatResource() { - return heatResource; - } + public Resource getHeatResource() { + return heatResource; + } - public void setHeatResource(Resource heatResource) { - this.heatResource = heatResource; - } + public void setHeatResource(Resource heatResource) { + this.heatResource = heatResource; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java index 235e00fab4..79d00c3048 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java @@ -25,32 +25,31 @@ import org.onap.sdc.tosca.datatypes.model.NodeTemplate; * Created by Talio on 4/4/2017. */ public class NodeTemplateInformation { - UnifiedCompositionEntity unifiedCompositionEntity; - private NodeTemplate nodeTemplate; - - public NodeTemplateInformation(){} - - public NodeTemplateInformation( - UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - this.unifiedCompositionEntity = unifiedCompositionEntity; - this.nodeTemplate = nodeTemplate; - } - - public UnifiedCompositionEntity getUnifiedCompositionEntity() { - return unifiedCompositionEntity; - } - - public void setUnifiedCompositionEntity( - UnifiedCompositionEntity unifiedCompositionEntity) { - this.unifiedCompositionEntity = unifiedCompositionEntity; - } - - public NodeTemplate getNodeTemplate() { - return nodeTemplate; - } - - public void setNodeTemplate(NodeTemplate nodeTemplate) { - this.nodeTemplate = nodeTemplate; - } + + UnifiedCompositionEntity unifiedCompositionEntity; + private NodeTemplate nodeTemplate; + + public NodeTemplateInformation() { + } + + public NodeTemplateInformation(UnifiedCompositionEntity unifiedCompositionEntity, NodeTemplate nodeTemplate) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + this.nodeTemplate = nodeTemplate; + } + + public UnifiedCompositionEntity getUnifiedCompositionEntity() { + return unifiedCompositionEntity; + } + + public void setUnifiedCompositionEntity(UnifiedCompositionEntity unifiedCompositionEntity) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + } + + public NodeTemplate getNodeTemplate() { + return nodeTemplate; + } + + public void setNodeTemplate(NodeTemplate nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java index 08db3be2a9..9f14737dd9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java @@ -13,121 +13,112 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; +import java.util.ArrayList; +import java.util.List; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceTemplateConsolidationData; -import java.util.ArrayList; -import java.util.List; - /** * The type Unified composition data. */ public class UnifiedCompositionData { - /** - * The Compute template consolidation data. - */ - private ComputeTemplateConsolidationData computeTemplateConsolidationData; - /** - * The Port template consolidation data list. - */ - private List portTemplateConsolidationDataList; - private List subInterfaceTemplateConsolidationDataList; + /** + * The Compute template consolidation data. + */ + private ComputeTemplateConsolidationData computeTemplateConsolidationData; + /** + * The Port template consolidation data list. + */ + private List portTemplateConsolidationDataList; + private List subInterfaceTemplateConsolidationDataList; + private NestedTemplateConsolidationData nestedTemplateConsolidationData; - private NestedTemplateConsolidationData nestedTemplateConsolidationData; - - /** - * Gets compute template consolidation data. - * - * @return the compute template consolidation data - */ - public ComputeTemplateConsolidationData getComputeTemplateConsolidationData() { - return computeTemplateConsolidationData; - } + /** + * Gets compute template consolidation data. + * + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData() { + return computeTemplateConsolidationData; + } - /** - * Sets compute template consolidation data. - * - * @param computeTemplateConsolidationData the compute template consolidation data - */ - public void setComputeTemplateConsolidationData( - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - this.computeTemplateConsolidationData = computeTemplateConsolidationData; - } + /** + * Sets compute template consolidation data. + * + * @param computeTemplateConsolidationData the compute template consolidation data + */ + public void setComputeTemplateConsolidationData(ComputeTemplateConsolidationData computeTemplateConsolidationData) { + this.computeTemplateConsolidationData = computeTemplateConsolidationData; + } - /** - * Gets port template consolidation data list. - * - * @return the port template consolidation data list - */ - public List getPortTemplateConsolidationDataList() { - return portTemplateConsolidationDataList; - } + /** + * Gets port template consolidation data list. + * + * @return the port template consolidation data list + */ + public List getPortTemplateConsolidationDataList() { + return portTemplateConsolidationDataList; + } - /** - * Sets port template consolidation data list. - * - * @param portTemplateConsolidationDataList the port template consolidation data list - */ - public void setPortTemplateConsolidationDataList( - List portTemplateConsolidationDataList) { - this.portTemplateConsolidationDataList = portTemplateConsolidationDataList; - } + /** + * Sets port template consolidation data list. + * + * @param portTemplateConsolidationDataList the port template consolidation data list + */ + public void setPortTemplateConsolidationDataList(List portTemplateConsolidationDataList) { + this.portTemplateConsolidationDataList = portTemplateConsolidationDataList; + } - /** - * Add port consolidation data. - * - * @param portTemplateConsolidationData the port consolidation data - */ - public void addPortTemplateConsolidationData( - PortTemplateConsolidationData portTemplateConsolidationData) { - if (this.portTemplateConsolidationDataList == null) { - this.portTemplateConsolidationDataList = new ArrayList<>(); + /** + * Add port consolidation data. + * + * @param portTemplateConsolidationData the port consolidation data + */ + public void addPortTemplateConsolidationData(PortTemplateConsolidationData portTemplateConsolidationData) { + if (this.portTemplateConsolidationDataList == null) { + this.portTemplateConsolidationDataList = new ArrayList<>(); + } + this.portTemplateConsolidationDataList.add(portTemplateConsolidationData); } - this.portTemplateConsolidationDataList.add(portTemplateConsolidationData); - } - /** - * Gets sub interface template consolidation data list. - * - * @return the sub interface template consolidation data list - */ - public List getSubInterfaceTemplateConsolidationDataList() { - return subInterfaceTemplateConsolidationDataList; - } + /** + * Gets sub interface template consolidation data list. + * + * @return the sub interface template consolidation data list + */ + public List getSubInterfaceTemplateConsolidationDataList() { + return subInterfaceTemplateConsolidationDataList; + } - /** - * Sets sub interface template consolidation data list. - * - * @param subInterfaceTemplateConsolidationDataList the sub interface template consolidation data - * list - */ - public void setSubInterfaceTemplateConsolidationDataList( - List subInterfaceTemplateConsolidationDataList) { - this.subInterfaceTemplateConsolidationDataList = subInterfaceTemplateConsolidationDataList; - } + /** + * Sets sub interface template consolidation data list. + * + * @param subInterfaceTemplateConsolidationDataList the sub interface template consolidation data list + */ + public void setSubInterfaceTemplateConsolidationDataList(List subInterfaceTemplateConsolidationDataList) { + this.subInterfaceTemplateConsolidationDataList = subInterfaceTemplateConsolidationDataList; + } - /** - * Gets nested template consolidation data. - * - * @return the nested template consolidation data - */ - public NestedTemplateConsolidationData getNestedTemplateConsolidationData() { - return nestedTemplateConsolidationData; - } + /** + * Gets nested template consolidation data. + * + * @return the nested template consolidation data + */ + public NestedTemplateConsolidationData getNestedTemplateConsolidationData() { + return nestedTemplateConsolidationData; + } - /** - * Sets nested template consolidation data. - * - * @param nestedTemplateConsolidationData the nested template consolidation data - */ - public void setNestedTemplateConsolidationData( - NestedTemplateConsolidationData nestedTemplateConsolidationData) { - this.nestedTemplateConsolidationData = nestedTemplateConsolidationData; - } + /** + * Sets nested template consolidation data. + * + * @param nestedTemplateConsolidationData the nested template consolidation data + */ + public void setNestedTemplateConsolidationData(NestedTemplateConsolidationData nestedTemplateConsolidationData) { + this.nestedTemplateConsolidationData = nestedTemplateConsolidationData; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java index 58a9092616..0484d2f7be 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java @@ -13,23 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; public enum UnifiedCompositionEntity { - COMPUTE("Compute"), - PORT("Port"), - NESTED("Nested"), - SUB_INTERFACE("SubInterface"), - OTHER("Other"); - - private String displayName; + COMPUTE("Compute"), PORT("Port"), NESTED("Nested"), SUB_INTERFACE("SubInterface"), OTHER("Other"); + private String displayName; - UnifiedCompositionEntity(String displayName) { - this.displayName = displayName; - } + UnifiedCompositionEntity(String displayName) { + this.displayName = displayName; + } - public String getDisplayName() { - return displayName; - } + public String getDisplayName() { + return displayName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java index e8c9060ca5..44311041c8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java @@ -24,9 +24,7 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composit * @since March 02, 2017. */ public enum UnifiedCompositionMode { - SingleSubstitution, - ScalingInstances, - // todo - support B1 SingleSubstitution, but create diff types/services vm_type+ - CatalogInstance, - NestedSingleCompute; + SingleSubstitution, ScalingInstances, + // todo - support B1 SingleSubstitution, but create diff types/services vm_type+ + CatalogInstance, NestedSingleCompute; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java index dd9b69f786..3749c942b4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java @@ -26,186 +26,164 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; public class UnifiedSubstitutionData { - //Key - node template id, Value - related abstract node template id - private Map nodesRelatedAbstractNode = new HashMap<>(); - //Key - node template id, Value - related node template id in the substitution service template - private Map nodesRelatedSubstitutionServiceTemplateNode = new HashMap<>(); - private Map cleanedNodeTemplates = new HashMap<>(); - //Key - nested node template id, Value - related unified nested node template id - private Map nestedNodeTemplateRelatedUnifiedTranslatedId = new HashMap<>(); - //Key - nested node type id, Value - related unified nested node template id - private Map nestedNodeTypeRelatedUnifiedTranslatedId = new HashMap<>(); - //Key - handled compute type, Value - number of times it was handled - private Map handledComputeTypesInNestedSubstitutionTemplate = - new HashMap<>(); - //Key - nested compute type, Value - list of nested files that the compute type is present - private Map handledNestedComputeTypesNestedFiles = new HashMap<>(); - //Key - new property id, Value - orig property value - private Map newParameterIdsToPropertiesFromOrigNodeTemplate = new HashMap<>(); - //handled nested files - private Set handledNestedFiles = new HashSet<>(); - //handled nested nodes - private Set handledNestedNodes = new HashSet<>(); - - public Map getNodesRelatedAbstractNode() { - return nodesRelatedAbstractNode; - } - - public void setNodesRelatedAbstractNode( - Map nodesRelatedAbstractNode) { - this.nodesRelatedAbstractNode = nodesRelatedAbstractNode; - } - - public void addHandledNestedNodes(String handledNestedNodeId) { - this.handledNestedNodes.add(handledNestedNodeId); - } - - public Map getNodesRelatedSubstitutionServiceTemplateNode() { - return nodesRelatedSubstitutionServiceTemplateNode; - } - - public void setNodesRelatedSubstitutionServiceTemplateNode( - Map nodesRelatedSubstitutionServiceTemplateNode) { - this.nodesRelatedSubstitutionServiceTemplateNode = nodesRelatedSubstitutionServiceTemplateNode; - } - - public String getNodeRelatedAbstractNode(String origNodeId) { - return this.nodesRelatedAbstractNode.get(origNodeId); - } - - public Collection getAllRelatedAbstractNodeIds() { - return this.nodesRelatedAbstractNode.values(); - } - - public Collection getAllUnifiedNestedNodeTemplateIds() { - return this.nestedNodeTemplateRelatedUnifiedTranslatedId.values(); - } - - /** - * Add cleaned node template. - * - * @param nodeTemplateId the node template id - * @param unifiedCompositionEntity the unified composition entity - * @param nodeTemplate the node template - */ - public void addCleanedNodeTemplate(String nodeTemplateId, - UnifiedCompositionEntity unifiedCompositionEntity, - NodeTemplate nodeTemplate) { - NodeTemplateInformation nodeTemplateInformation = new NodeTemplateInformation( - unifiedCompositionEntity, nodeTemplate); - this.cleanedNodeTemplates.putIfAbsent(nodeTemplateId, nodeTemplateInformation); - } - - public NodeTemplate getCleanedNodeTemplate(String nodeTemplateId) { - return this.cleanedNodeTemplates.get(nodeTemplateId).getNodeTemplate().clone(); - } - - public UnifiedCompositionEntity getCleanedNodeTemplateCompositionEntity(String nodeTemplateId) { - return this.cleanedNodeTemplates.get(nodeTemplateId).getUnifiedCompositionEntity(); - } - - public void addUnifiedNestedNodeTemplateId(String nestedNodeTemplateId, - String unifiedNestedNodeRelatedId) { - this.nestedNodeTemplateRelatedUnifiedTranslatedId - .put(nestedNodeTemplateId, unifiedNestedNodeRelatedId); - } - - public Optional getUnifiedNestedNodeTemplateId(String nestedNodeTemplateId) { - return this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId) == null - ? Optional.empty() - : Optional.of(this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId)); - } - - public void addUnifiedNestedNodeTypeId(String nestedNodeTypeId, - String unifiedNestedNodeRelatedId) { - this.nestedNodeTypeRelatedUnifiedTranslatedId.put(nestedNodeTypeId, unifiedNestedNodeRelatedId); - } - - public Optional getUnifiedNestedNodeTypeId(String nestedNodeTypeId) { - return this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId) == null ? Optional - .empty() - : Optional.of(this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId)); - } - - public Set getAllRelatedNestedNodeTypeIds(){ - if(MapUtils.isEmpty(nestedNodeTypeRelatedUnifiedTranslatedId)){ - return new HashSet<>(); - } - return new HashSet<>(this.nestedNodeTypeRelatedUnifiedTranslatedId.values()); - } - - public void addHandledComputeType(String handledComputeType) { - - if (this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(handledComputeType)) { - Integer timesHandled = - this.handledComputeTypesInNestedSubstitutionTemplate.get(handledComputeType); - this.handledComputeTypesInNestedSubstitutionTemplate - .put(handledComputeType, timesHandled + 1); - } else { - //this.handledNestedFiles.add(nestedServiceTemplateFileName); - handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, 0); - } - } - - public boolean isComputeTypeHandledInServiceTemplate(String computeType) { - return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType); - } - - public int getHandledNestedComputeNodeTemplateIndex(String computeType) { - return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType) ? - this.handledComputeTypesInNestedSubstitutionTemplate.get(computeType) : 0; - } - - public void addHandlesNestedServiceTemplate(String nestedServiceTemplateFileName){ - this.handledNestedFiles.add(nestedServiceTemplateFileName); - } - - public boolean isNestedServiceTemplateWasHandled(String nestedServiceTemplateFileName) { - return this.handledNestedFiles.contains(nestedServiceTemplateFileName); - } - - public void updateUsedTimesForNestedComputeNodeType(String computeType) { - this.handledNestedComputeTypesNestedFiles.putIfAbsent(computeType, 0); - - Integer usedNumber = this.handledNestedComputeTypesNestedFiles.get(computeType); - this.handledNestedComputeTypesNestedFiles.put(computeType, usedNumber + 1); - - } - - public int getGlobalNodeTypeIndex(String computeType) { - return Objects.isNull(this.handledNestedComputeTypesNestedFiles.get(computeType)) - || this.handledNestedComputeTypesNestedFiles.get(computeType)== 0 ? 0 - : this.handledNestedComputeTypesNestedFiles.get(computeType); - } - - public boolean isNestedNodeWasHandled(String nestedNodeId) { - return this.handledNestedNodes.contains(nestedNodeId); - } - - - public Map getAllNewPropertyInputParamIds(){ - return this.newParameterIdsToPropertiesFromOrigNodeTemplate; - } - - public void addNewPropertyIdToNodeTemplate(String newPropertyId, - Object origPropertyValue){ - if(!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { - newParameterIdsToPropertiesFromOrigNodeTemplate.put(newPropertyId, origPropertyValue); + //Key - node template id, Value - related abstract node template id + private Map nodesRelatedAbstractNode = new HashMap<>(); + //Key - node template id, Value - related node template id in the substitution service template + private Map nodesRelatedSubstitutionServiceTemplateNode = new HashMap<>(); + private Map cleanedNodeTemplates = new HashMap<>(); + //Key - nested node template id, Value - related unified nested node template id + private Map nestedNodeTemplateRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - nested node type id, Value - related unified nested node template id + private Map nestedNodeTypeRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - handled compute type, Value - number of times it was handled + private Map handledComputeTypesInNestedSubstitutionTemplate = new HashMap<>(); + //Key - nested compute type, Value - list of nested files that the compute type is present + private Map handledNestedComputeTypesNestedFiles = new HashMap<>(); + //Key - new property id, Value - orig property value + private Map newParameterIdsToPropertiesFromOrigNodeTemplate = new HashMap<>(); + //handled nested files + private Set handledNestedFiles = new HashSet<>(); + //handled nested nodes + private Set handledNestedNodes = new HashSet<>(); + + public Map getNodesRelatedAbstractNode() { + return nodesRelatedAbstractNode; + } + + public void setNodesRelatedAbstractNode(Map nodesRelatedAbstractNode) { + this.nodesRelatedAbstractNode = nodesRelatedAbstractNode; } - } - public Optional getNewPropertyInputParam(String newPropertyId){ - if(!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)){ - return Optional.empty(); + public void addHandledNestedNodes(String handledNestedNodeId) { + this.handledNestedNodes.add(handledNestedNodeId); } - return Optional.of(newParameterIdsToPropertiesFromOrigNodeTemplate.get(newPropertyId)); - } + public Map getNodesRelatedSubstitutionServiceTemplateNode() { + return nodesRelatedSubstitutionServiceTemplateNode; + } + public void setNodesRelatedSubstitutionServiceTemplateNode(Map nodesRelatedSubstitutionServiceTemplateNode) { + this.nodesRelatedSubstitutionServiceTemplateNode = nodesRelatedSubstitutionServiceTemplateNode; + } + + public String getNodeRelatedAbstractNode(String origNodeId) { + return this.nodesRelatedAbstractNode.get(origNodeId); + } + + public Collection getAllRelatedAbstractNodeIds() { + return this.nodesRelatedAbstractNode.values(); + } + + public Collection getAllUnifiedNestedNodeTemplateIds() { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.values(); + } + + /** + * Add cleaned node template. + * + * @param nodeTemplateId the node template id + * @param unifiedCompositionEntity the unified composition entity + * @param nodeTemplate the node template + */ + public void addCleanedNodeTemplate(String nodeTemplateId, UnifiedCompositionEntity unifiedCompositionEntity, NodeTemplate nodeTemplate) { + NodeTemplateInformation nodeTemplateInformation = new NodeTemplateInformation(unifiedCompositionEntity, nodeTemplate); + this.cleanedNodeTemplates.putIfAbsent(nodeTemplateId, nodeTemplateInformation); + } + + public NodeTemplate getCleanedNodeTemplate(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getNodeTemplate().clone(); + } + + public UnifiedCompositionEntity getCleanedNodeTemplateCompositionEntity(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getUnifiedCompositionEntity(); + } + + public void addUnifiedNestedNodeTemplateId(String nestedNodeTemplateId, String unifiedNestedNodeRelatedId) { + this.nestedNodeTemplateRelatedUnifiedTranslatedId.put(nestedNodeTemplateId, unifiedNestedNodeRelatedId); + } + + public Optional getUnifiedNestedNodeTemplateId(String nestedNodeTemplateId) { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId) == null ? Optional.empty() + : Optional.of(this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId)); + } + + public void addUnifiedNestedNodeTypeId(String nestedNodeTypeId, String unifiedNestedNodeRelatedId) { + this.nestedNodeTypeRelatedUnifiedTranslatedId.put(nestedNodeTypeId, unifiedNestedNodeRelatedId); + } + + public Optional getUnifiedNestedNodeTypeId(String nestedNodeTypeId) { + return this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId) == null ? Optional.empty() + : Optional.of(this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId)); + } + + public Set getAllRelatedNestedNodeTypeIds() { + if (MapUtils.isEmpty(nestedNodeTypeRelatedUnifiedTranslatedId)) { + return new HashSet<>(); + } + return new HashSet<>(this.nestedNodeTypeRelatedUnifiedTranslatedId.values()); + } + + public void addHandledComputeType(String handledComputeType) { + if (this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(handledComputeType)) { + Integer timesHandled = this.handledComputeTypesInNestedSubstitutionTemplate.get(handledComputeType); + this.handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, timesHandled + 1); + } else { + //this.handledNestedFiles.add(nestedServiceTemplateFileName); + handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, 0); + } + } + + public boolean isComputeTypeHandledInServiceTemplate(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType); + } + + public int getHandledNestedComputeNodeTemplateIndex(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType) ? this.handledComputeTypesInNestedSubstitutionTemplate + .get(computeType) : 0; + } + + public void addHandlesNestedServiceTemplate(String nestedServiceTemplateFileName) { + this.handledNestedFiles.add(nestedServiceTemplateFileName); + } + + public boolean isNestedServiceTemplateWasHandled(String nestedServiceTemplateFileName) { + return this.handledNestedFiles.contains(nestedServiceTemplateFileName); + } + + public void updateUsedTimesForNestedComputeNodeType(String computeType) { + this.handledNestedComputeTypesNestedFiles.putIfAbsent(computeType, 0); + Integer usedNumber = this.handledNestedComputeTypesNestedFiles.get(computeType); + this.handledNestedComputeTypesNestedFiles.put(computeType, usedNumber + 1); + } + + public int getGlobalNodeTypeIndex(String computeType) { + return Objects.isNull(this.handledNestedComputeTypesNestedFiles.get(computeType)) + || this.handledNestedComputeTypesNestedFiles.get(computeType) == 0 ? 0 : this.handledNestedComputeTypesNestedFiles.get(computeType); + } + + public boolean isNestedNodeWasHandled(String nestedNodeId) { + return this.handledNestedNodes.contains(nestedNodeId); + } + + public Map getAllNewPropertyInputParamIds() { + return this.newParameterIdsToPropertiesFromOrigNodeTemplate; + } + + public void addNewPropertyIdToNodeTemplate(String newPropertyId, Object origPropertyValue) { + if (!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { + newParameterIdsToPropertiesFromOrigNodeTemplate.put(newPropertyId, origPropertyValue); + } + } + + public Optional getNewPropertyInputParam(String newPropertyId) { + if (!newParameterIdsToPropertiesFromOrigNodeTemplate.containsKey(newPropertyId)) { + return Optional.empty(); + } + return Optional.of(newParameterIdsToPropertiesFromOrigNodeTemplate.get(newPropertyId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java index 8fa2c74b1b..6a8fac6508 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/CommandImplNames.java @@ -13,18 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands; public class CommandImplNames { - private static final String COMMANDS_IMPL_BASE_PACKAGE = - "org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl"; - - public static final String COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".ComputeNewNodeTemplateIdGenerator"; - public static final String PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".PortNewNodeTemplateIdGenerator"; - public static final String SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = - COMMANDS_IMPL_BASE_PACKAGE + ".SubInterfaceNewNodeTemplateIdGenerator"; + private static final String COMMANDS_IMPL_BASE_PACKAGE = "org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl"; + public static final String COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = COMMANDS_IMPL_BASE_PACKAGE + ".ComputeNewNodeTemplateIdGenerator"; + public static final String PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = COMMANDS_IMPL_BASE_PACKAGE + ".PortNewNodeTemplateIdGenerator"; + public static final String SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL = + COMMANDS_IMPL_BASE_PACKAGE + ".SubInterfaceNewNodeTemplateIdGenerator"; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java index a932859807..fd5c05236e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/UnifiedSubstitutionNodeTemplateIdGenerator.java @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; - import java.util.Optional; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; public interface UnifiedSubstitutionNodeTemplateIdGenerator { - public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId); + + public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java index c39a26c545..f88f7b2002 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/ComputeNewNodeTemplateIdGenerator.java @@ -13,20 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import java.util.Optional; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.UnifiedSubstitutionNodeTemplateIdGenerator; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil; -import java.util.Optional; - public class ComputeNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - return Optional.ofNullable(UnifiedCompositionUtil.getNewComputeNodeTemplateId( - unifiedCompositionTo.getServiceTemplate(), originalNodeTemplateId)); - } + @Override + public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + return Optional + .ofNullable(UnifiedCompositionUtil.getNewComputeNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), originalNodeTemplateId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java index 7a49861452..746f435221 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/PortNewNodeTemplateIdGenerator.java @@ -13,34 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; + +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.UnifiedSubstitutionNodeTemplateIdGenerator; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to.UnifiedCompositionTo; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; - public class PortNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - originalNodeTemplateId); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - return Optional.of(getNewPortNodeTemplateId(originalNodeTemplateId, connectedComputeNodeTemplate.getType(), - connectedComputeConsolidationData)); + @Override + public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), originalNodeTemplateId); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + return Optional + .of(getNewPortNodeTemplateId(originalNodeTemplateId, connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData)); + } + return Optional.empty(); } - return Optional.empty(); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java index e2e938b83c..82ab669ddb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/commands/impl/SubInterfaceNewNodeTemplateIdGenerator.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.commands.impl; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; + +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; @@ -25,45 +31,31 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.SubInterfaceTemplateConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; - public class SubInterfaceNewNodeTemplateIdGenerator implements UnifiedSubstitutionNodeTemplateIdGenerator { - @Override - public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { - SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationDataById(unifiedCompositionTo.getUnifiedCompositionDataList(), - originalNodeTemplateId); - if (Objects.nonNull(subInterfaceTemplateConsolidationData)) { - String parentPortNodeTemplateId = subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(); - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - parentPortNodeTemplateId); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - return Optional.of(getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), - connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, - subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext())); - } + private static SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationDataById( + List unifiedCompositionDataList, String subInterfaceNodeTemplateId) { + return unifiedCompositionDataList.stream().map(UnifiedCompositionUtil::getSubInterfaceTemplateConsolidationDataList) + .flatMap(Collection::stream).filter( + subInterfaceTemplateConsolidationData -> subInterfaceNodeTemplateId.equals(subInterfaceTemplateConsolidationData.getNodeTemplateId())) + .findFirst().orElse(null); } - return Optional.empty(); - } - private static SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationDataById( - List unifiedCompositionDataList, - String subInterfaceNodeTemplateId) { - return unifiedCompositionDataList.stream() - .map(UnifiedCompositionUtil::getSubInterfaceTemplateConsolidationDataList) - .flatMap(Collection::stream) - .filter(subInterfaceTemplateConsolidationData -> subInterfaceNodeTemplateId - .equals(subInterfaceTemplateConsolidationData.getNodeTemplateId())) - .findFirst().orElse(null); - } + @Override + public Optional generate(UnifiedCompositionTo unifiedCompositionTo, String originalNodeTemplateId) { + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationDataById( + unifiedCompositionTo.getUnifiedCompositionDataList(), originalNodeTemplateId); + if (Objects.nonNull(subInterfaceTemplateConsolidationData)) { + String parentPortNodeTemplateId = subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(); + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), parentPortNodeTemplateId); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + return Optional.of(getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), connectedComputeNodeTemplate.getType(), + connectedComputeConsolidationData, subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext())); + } + } + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java index 6ae6785f3e..30c89accd0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/to/UnifiedCompositionTo.java @@ -13,73 +13,68 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.to; +import java.util.List; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import java.util.List; - public class UnifiedCompositionTo { - private ServiceTemplate serviceTemplate; - private ServiceTemplate substitutionServiceTemplate; - private List unifiedCompositionDataList; - private TranslationContext context; - private NodeTemplate nodeTemplate; - public UnifiedCompositionTo(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context, - NodeTemplate nodeTemplate) { - this.serviceTemplate = serviceTemplate; - this.substitutionServiceTemplate = substitutionServiceTemplate; - this.unifiedCompositionDataList = unifiedCompositionDataList; - this.context = context; - this.nodeTemplate = nodeTemplate; - } + private ServiceTemplate serviceTemplate; + private ServiceTemplate substitutionServiceTemplate; + private List unifiedCompositionDataList; + private TranslationContext context; + private NodeTemplate nodeTemplate; + + public UnifiedCompositionTo(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, TranslationContext context, NodeTemplate nodeTemplate) { + this.serviceTemplate = serviceTemplate; + this.substitutionServiceTemplate = substitutionServiceTemplate; + this.unifiedCompositionDataList = unifiedCompositionDataList; + this.context = context; + this.nodeTemplate = nodeTemplate; + } - public ServiceTemplate getServiceTemplate() { - return serviceTemplate; - } + public ServiceTemplate getServiceTemplate() { + return serviceTemplate; + } - public void setServiceTemplate(ServiceTemplate serviceTemplate) { - this.serviceTemplate = serviceTemplate; - } + public void setServiceTemplate(ServiceTemplate serviceTemplate) { + this.serviceTemplate = serviceTemplate; + } - public ServiceTemplate getSubstitutionServiceTemplate() { - return substitutionServiceTemplate; - } + public ServiceTemplate getSubstitutionServiceTemplate() { + return substitutionServiceTemplate; + } - public void setSubstitutionServiceTemplate(ServiceTemplate substitutionServiceTemplate) { - this.substitutionServiceTemplate = substitutionServiceTemplate; - } + public void setSubstitutionServiceTemplate(ServiceTemplate substitutionServiceTemplate) { + this.substitutionServiceTemplate = substitutionServiceTemplate; + } - public List getUnifiedCompositionDataList() { - return unifiedCompositionDataList; - } + public List getUnifiedCompositionDataList() { + return unifiedCompositionDataList; + } - public void setUnifiedCompositionDataList( - List unifiedCompositionDataList) { - this.unifiedCompositionDataList = unifiedCompositionDataList; - } + public void setUnifiedCompositionDataList(List unifiedCompositionDataList) { + this.unifiedCompositionDataList = unifiedCompositionDataList; + } - public TranslationContext getContext() { - return context; - } + public TranslationContext getContext() { + return context; + } - public void setContext(TranslationContext context) { - this.context = context; - } + public void setContext(TranslationContext context) { + this.context = context; + } - public NodeTemplate getNodeTemplate() { - return nodeTemplate; - } + public NodeTemplate getNodeTemplate() { + return nodeTemplate; + } - public void setNodeTemplate(NodeTemplate nodeTemplate) { - this.nodeTemplate=nodeTemplate; - } + public void setNodeTemplate(NodeTemplate nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java index 5e1d264f83..ddb6d52274 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.HashMap; @@ -38,19 +37,17 @@ public class ComputeConsolidationData { return fileComputeConsolidationData.get(serviceTemplateFileName); } - public void setFileComputeConsolidationData(String serviceTemplateFileName, - FileComputeConsolidationData fileComputeConsolidationData) { + public void setFileComputeConsolidationData(String serviceTemplateFileName, FileComputeConsolidationData fileComputeConsolidationData) { this.fileComputeConsolidationData.put(serviceTemplateFileName, fileComputeConsolidationData); } /** - * add compute template consolidation data entity if it doesn't exist yet - * base on given parameters. + * add compute template consolidation data entity if it doesn't exist yet base on given parameters. * * @return compute template consolidation data entity by given keys - */ - ComputeTemplateConsolidationData addComputeTemplateConsolidationData( - String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { + */ + ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String serviceTemplateFileName, String computeNodeType, + String computeNodeTemplateId) { FileComputeConsolidationData consolidationData = addFileComputeConsolidationData(serviceTemplateFileName); return consolidationData.addComputeTemplateConsolidationData(computeNodeType, computeNodeTemplateId); } @@ -71,9 +68,7 @@ public class ComputeConsolidationData { * @return the boolean */ public boolean isNumberOfComputeTypesLegal(String serviceTemplateName) { - FileComputeConsolidationData fileComputeConsolidationData = - getFileComputeConsolidationData(serviceTemplateName); - return Objects.nonNull(fileComputeConsolidationData) - && fileComputeConsolidationData.isNumberOfComputeTypesLegal(); + FileComputeConsolidationData fileComputeConsolidationData = getFileComputeConsolidationData(serviceTemplateName); + return Objects.nonNull(fileComputeConsolidationData) && fileComputeConsolidationData.isNumberOfComputeTypesLegal(); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java index 24b8524804..96324d77ba 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationDataHandler.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Objects; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -28,8 +28,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import java.util.Objects; - public class ComputeConsolidationDataHandler implements ConsolidationDataHandler { private final ComputeConsolidationData computeConsolidationData; @@ -41,60 +39,45 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { - String translatedSourceNodeId = translateTo.getTranslatedId(); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, translatedSourceNodeId); String nodeType = computeNodeTemplate.getType(); - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(translateTo, nodeType, translatedSourceNodeId); - + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(translateTo, nodeType, translatedSourceNodeId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, dependentNodeTemplateId); - String nodeType = getNodeType(nodeTemplate, translateTo.getHeatOrchestrationTemplate(), - targetResourceId, dependentNodeTemplateId, dependentNodeTemplateId); - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(translateTo, nodeType, dependentNodeTemplateId); - + String nodeType = getNodeType(nodeTemplate, translateTo.getHeatOrchestrationTemplate(), targetResourceId, dependentNodeTemplateId, + dependentNodeTemplateId); + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(translateTo, nodeType, dependentNodeTemplateId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); } } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId) { - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, sharedTranslatedResourceId); - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), nodeTemplate.getType(), sharedTranslatedResourceId); - + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + nodeTemplate.getType(), sharedTranslatedResourceId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.removeParamNameFromAttrFuncList(paramName); } } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, - functionTranslator.getResourceId(), resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, functionTranslator.getResourceId(), + resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -102,26 +85,21 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); } - } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getComputeTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -130,33 +108,26 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler /** * Add compute in consolidation data entity base on given keys. - * */ - public void addConsolidationData(String serviceTemplateFileName, - String computeNodeType, String computeNodeTemplateId) { - getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); + public void addConsolidationData(String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { + getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } /** * Add port to compute consolidation data entity base on given keys. - * */ - public void addPortToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String portType, String portNodeTemplateId) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); + public void addPortToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, String portType, + String portNodeTemplateId) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addPort(portType, portNodeTemplateId); } /** * Add volume to consolidation data. - * */ - public void addVolumeToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, - computeNodeTemplateId); + public void addVolumeToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, String requirementId, + RequirementAssignment requirementAssignment) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addVolume(requirementId, requirementAssignment); } @@ -165,12 +136,9 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler * * @param translatedGroupId Group id of which compute node is a part */ - - public void addGroupIdToConsolidationData(TranslateTo translateTo, String computeNodeType, - String computeNodeTemplateId, String translatedGroupId) { - ComputeTemplateConsolidationData consolidationData = - getComputeTemplateConsolidationData(translateTo, computeNodeType, - computeNodeTemplateId); + public void addGroupIdToConsolidationData(TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId, + String translatedGroupId) { + ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(translateTo, computeNodeType, computeNodeTemplateId); consolidationData.addGroupId(translatedGroupId); } @@ -178,46 +146,41 @@ public class ComputeConsolidationDataHandler implements ConsolidationDataHandler return computeConsolidationData.isNumberOfComputeTypesLegal(serviceTemplateName); } - private EntityConsolidationData getComputeTemplateConsolidationData(FunctionTranslator functionTranslator, - String resourceId, String computeNodeTemplateId) { + private EntityConsolidationData getComputeTemplateConsolidationData(FunctionTranslator functionTranslator, String resourceId, + String computeNodeTemplateId) { HeatOrchestrationTemplate heatOrchestrationTemplate = functionTranslator.getHeatOrchestrationTemplate(); TranslationContext context = functionTranslator.getContext(); String heatFileName = functionTranslator.getHeatFileName(); String translatedId = context.getTranslatedIds().get(heatFileName).get(resourceId); ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); String computeType = getNodeType(heatOrchestrationTemplate, resourceId, resourceId, translatedId); - return getComputeTemplateConsolidationData( - ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeType, computeNodeTemplateId); + return getComputeTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeType, computeNodeTemplateId); } - private ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - TranslateTo translateTo, String computeNodeType, String computeNodeTemplateId) { + private ComputeTemplateConsolidationData getComputeTemplateConsolidationData(TranslateTo translateTo, String computeNodeType, + String computeNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); return getComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } - private ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - String serviceTemplateFileName, String computeNodeType, String computeNodeTemplateId) { - - return computeConsolidationData.addComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, - computeNodeTemplateId); - + private ComputeTemplateConsolidationData getComputeTemplateConsolidationData(String serviceTemplateFileName, String computeNodeType, + String computeNodeTemplateId) { + return computeConsolidationData.addComputeTemplateConsolidationData(serviceTemplateFileName, computeNodeType, computeNodeTemplateId); } - private String getNodeType(HeatOrchestrationTemplate heatOrchestrationTemplate, - String targetResourceId, String nodeTemplateId, String translatedId) { - return getNodeType(null, heatOrchestrationTemplate, targetResourceId, - nodeTemplateId, translatedId); + private String getNodeType(HeatOrchestrationTemplate heatOrchestrationTemplate, String targetResourceId, String nodeTemplateId, + String translatedId) { + return getNodeType(null, heatOrchestrationTemplate, targetResourceId, nodeTemplateId, translatedId); } - private String getNodeType(NodeTemplate computeNodeTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, - String targetResourceId, String nodeTemplateId, String translatedId) { + private String getNodeType(NodeTemplate computeNodeTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, String targetResourceId, + String nodeTemplateId, String translatedId) { if (Objects.isNull(computeNodeTemplate)) { Resource targetResource = heatOrchestrationTemplate.getResources().get(targetResourceId); NameExtractor nodeTypeNameExtractor = TranslationContext.getNameExtractorImpl(targetResource.getType()); - return nodeTypeNameExtractor.extractNodeTypeName(heatOrchestrationTemplate.getResources() - .get(nodeTemplateId), nodeTemplateId, translatedId); + return nodeTypeNameExtractor + .extractNodeTypeName(heatOrchestrationTemplate.getResources().get(nodeTemplateId), nodeTemplateId, translatedId); } return computeNodeTemplate.getType(); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java index 639bcfbfcd..9ef9032a5f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java @@ -13,29 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; public class ComputeTemplateConsolidationData extends EntityConsolidationData { // key - volume node template id + // value - List of requirement id and the requirement assignment on the + // compute node which connect to this volume private Multimap volumes; - // key - port type (port id excluding index), + // value - List of connected port node template ids, with this port type private Map> ports; @@ -67,8 +66,7 @@ public class ComputeTemplateConsolidationData extends EntityConsolidationData { if (this.volumes == null) { this.volumes = ArrayListMultimap.create(); } - this.volumes.put(requirementAssignment.getNode(), new RequirementAssignmentData(requirementId, - requirementAssignment)); + this.volumes.put(requirementAssignment.getNode(), new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -92,8 +90,7 @@ public class ComputeTemplateConsolidationData extends EntityConsolidationData { */ public boolean isNumberOfPortFromEachTypeLegal() { Map> currPortsMap = getPorts(); - return MapUtils.isEmpty(currPortsMap) || currPortsMap.values().stream() - .allMatch(portList -> portList.size() == 1); + return MapUtils.isEmpty(currPortsMap) || currPortsMap.values().stream().allMatch(portList -> portList.size() == 1); } public Set getPortsIds() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java index 053795b82b..9f34aa3046 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java @@ -13,37 +13,29 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; - import java.util.Optional; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; public class ConsolidationData { private final ComputeConsolidationData computeConsolidationData; private final ComputeConsolidationDataHandler computeConsolidationDataHandler; - private final PortConsolidationData portConsolidationData; private final PortConsolidationDataHandler portConsolidationDataHandler; private final SubInterfaceConsolidationDataHandler subInterfaceConsolidationDataHandler; - - private NestedConsolidationData nestedConsolidationData; private final NestedConsolidationDataHandler nestedConsolidationDataHandler; + private NestedConsolidationData nestedConsolidationData; public ConsolidationData() { - computeConsolidationData = new ComputeConsolidationData(); computeConsolidationDataHandler = new ComputeConsolidationDataHandler(computeConsolidationData); - portConsolidationData = new PortConsolidationData(); portConsolidationDataHandler = new PortConsolidationDataHandler(portConsolidationData); subInterfaceConsolidationDataHandler = new SubInterfaceConsolidationDataHandler(portConsolidationData); - nestedConsolidationData = new NestedConsolidationData(); nestedConsolidationDataHandler = new NestedConsolidationDataHandler(nestedConsolidationData); - } /** @@ -52,7 +44,6 @@ public class ConsolidationData { * @return If there is no consolidation handler for a type, return an empty {@link Optional}. */ public Optional getConsolidationDataHandler(ConsolidationEntityType type) { - switch (type) { case COMPUTE: return Optional.of(getComputeConsolidationDataHandler()); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java index ade5fd21f3..fc945e1323 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationDataHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -31,8 +30,7 @@ public interface ConsolidationDataHandler { * @param requirementId the requirement id of requirement assignment * @param requirementAssignment the requirement assignment data connected to target node */ - void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, - String requirementId, RequirementAssignment requirementAssignment); + void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment); /** * Add source node connected in to target node consolidation entity. @@ -43,22 +41,18 @@ public interface ConsolidationDataHandler { * @param requirementId the requirement id of source node * @param requirementAssignment the requirement assignment data of source node */ - void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String targetNodeTemplateId, - String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment); + void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String targetNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment); - void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId); + void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, + String contrailSharedResourceId, String sharedTranslatedResourceId); - void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName); + void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName); - void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attributeName); + void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName); - void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName); + void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java index 814011d846..ac1fa57481 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -27,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -38,26 +35,24 @@ import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; public class EntityConsolidationData { private String nodeTemplateId; - //groups that point to this entity node template private List groupIds; - // key - node template id which has connection to this entity + // value - List of Requirement assignment data which connect to this entity private Multimap nodesConnectedIn; - // key - node template id which connected from this entity + // List of Requirement assignment data which connect to the key node template id private Multimap nodesConnectedOut; - //key - node template id which include get attribute function from this entity + //value - List of getAttr data private Map> nodesGetAttrIn; - //key - node template id which is pointed by this entity using get attribute function + //value - List of getAttr data private Map> nodesGetAttrOut; - //List of getAttr data private List outputParametersGetAttrIn; @@ -87,16 +82,6 @@ public class EntityConsolidationData { this.groupIds = groupIds; } - - /** - * Sets node connected to me. - * - * @param nodesConnectedIn the node connected to me - */ - public void setNodesConnectedIn(Multimap nodesConnectedIn) { - this.nodesConnectedIn = nodesConnectedIn; - } - /** * Add node connected to me. * @@ -104,15 +89,11 @@ public class EntityConsolidationData { * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public void addNodesConnectedIn(String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedIn(String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { if (this.nodesConnectedIn == null) { this.nodesConnectedIn = ArrayListMultimap.create(); } - - this.nodesConnectedIn.get(nodeTemplateId).add( - new RequirementAssignmentData(requirementId, requirementAssignment)); + this.nodesConnectedIn.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -124,6 +105,14 @@ public class EntityConsolidationData { return nodesConnectedIn; } + /** + * Sets node connected to me. + * + * @param nodesConnectedIn the node connected to me + */ + public void setNodesConnectedIn(Multimap nodesConnectedIn) { + this.nodesConnectedIn = nodesConnectedIn; + } /** * Gets node connected from me. @@ -150,15 +139,11 @@ public class EntityConsolidationData { * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public void addNodesConnectedOut(String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - + public void addNodesConnectedOut(String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { if (this.nodesConnectedOut == null) { this.nodesConnectedOut = ArrayListMultimap.create(); } - - this.nodesConnectedOut.get(nodeTemplateId).add( - new RequirementAssignmentData(requirementId, requirementAssignment)); + this.nodesConnectedOut.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, requirementAssignment)); } /** @@ -186,11 +171,9 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addNodesGetAttrIn(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { - if (nodesGetAttrIn == null) { nodesGetAttrIn = new HashMap<>(); } - this.nodesGetAttrIn.putIfAbsent(nodeTemplateId, new ArrayList<>()); this.nodesGetAttrIn.get(nodeTemplateId).add(getAttrFuncData); } @@ -219,11 +202,9 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addOutputParamGetAttrIn(GetAttrFuncData getAttrFuncData) { - if (outputParametersGetAttrIn == null) { outputParametersGetAttrIn = new ArrayList<>(); } - this.outputParametersGetAttrIn.add(getAttrFuncData); } @@ -252,21 +233,17 @@ public class EntityConsolidationData { * @param getAttrFuncData get attr data */ public void addNodesGetAttrOut(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { - if (nodesGetAttrOut == null) { nodesGetAttrOut = new HashMap<>(); } - this.nodesGetAttrOut.putIfAbsent(nodeTemplateId, new ArrayList<>()); this.nodesGetAttrOut.get(nodeTemplateId).add(getAttrFuncData); } public void removeParamNameFromAttrFuncList(String paramName) { - if (outputParametersGetAttrIn == null) { return; } - outputParametersGetAttrIn.removeIf(outputParameters -> paramName.equals(outputParameters.getFieldName())); } @@ -275,23 +252,17 @@ public class EntityConsolidationData { * * @param entityConsolidationDataList consolidation data list * @param portTypeToIds the port type to ids - * @return true in case get attr list same for all port types. - * otherwise return false + * @return true in case get attr list same for all port types. otherwise return false */ - public boolean isGetAttrOutFromEntityLegal(Collection - entityConsolidationDataList, Map> portTypeToIds) { - if (CollectionUtils.isEmpty(entityConsolidationDataList) - || MapUtils.isEmpty(portTypeToIds)) { + public boolean isGetAttrOutFromEntityLegal(Collection entityConsolidationDataList, + Map> portTypeToIds) { + if (CollectionUtils.isEmpty(entityConsolidationDataList) || MapUtils.isEmpty(portTypeToIds)) { return true; } - for (String portType : portTypeToIds.keySet()) { - Set startingGetAttrFunc = - getEntityGetAttrFuncAsSet(portType, portTypeToIds); - + Set startingGetAttrFunc = getEntityGetAttrFuncAsSet(portType, portTypeToIds); for (EntityConsolidationData entity : entityConsolidationDataList) { - Set currentGetAttrFuncData = - entity.getEntityGetAttrFuncAsSet(portType, portTypeToIds); + Set currentGetAttrFuncData = entity.getEntityGetAttrFuncAsSet(portType, portTypeToIds); if (!(startingGetAttrFunc.equals(currentGetAttrFuncData))) { return false; } @@ -304,12 +275,8 @@ public class EntityConsolidationData { if (MapUtils.isEmpty(nodesGetAttrOut)) { return new HashSet<>(); } - - return nodesGetAttrOut.entrySet().stream() - .filter(entry -> portType.equals(getPortTypeFromNodeTemplateId(entry.getKey(), - portTypeToIds))) - .flatMap(entry -> entry.getValue().stream()) - .collect(Collectors.toSet()); + return nodesGetAttrOut.entrySet().stream().filter(entry -> portType.equals(getPortTypeFromNodeTemplateId(entry.getKey(), portTypeToIds))) + .flatMap(entry -> entry.getValue().stream()).collect(Collectors.toSet()); } private String getPortTypeFromNodeTemplateId(String portNodeTemplateId, Map> portTypeToIds) { @@ -324,9 +291,8 @@ public class EntityConsolidationData { /** * Add group id information to consolidation data. * - * @param groupId Group id of which compute node is a part + * @param groupId Group id of which compute node is a part */ - void addGroupId(String groupId) { if (groupIds == null) { groupIds = new ArrayList<>(); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java index bde0dc0ede..daf03cd141 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -42,20 +41,16 @@ public class FileComputeConsolidationData { return typeComputeConsolidationData.get(computeType); } - public void setTypeComputeConsolidationData(String computeType, TypeComputeConsolidationData - typeComputeConsolidationData) { + public void setTypeComputeConsolidationData(String computeType, TypeComputeConsolidationData typeComputeConsolidationData) { this.typeComputeConsolidationData.put(computeType, typeComputeConsolidationData); } - /** - * add compute template consolidation data according to given key if it doesn't exist yet. - * - * @return compute template consolidation data by given keys - */ - ComputeTemplateConsolidationData addComputeTemplateConsolidationData( - String computeType, String computeNodeTemplateId) { - + * add compute template consolidation data according to given key if it doesn't exist yet. + * + * @return compute template consolidation data by given keys + */ + ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String computeType, String computeNodeTemplateId) { TypeComputeConsolidationData consolidationData = addTypeComputeConsolidationData(computeType); return consolidationData.addComputeTemplateConsolidationData(computeNodeTemplateId); } @@ -75,10 +70,8 @@ public class FileComputeConsolidationData { * @return the boolean */ public boolean isNumberOfComputeTypesLegal() { - Collection typeComputeConsolidationDataCollection = - getAllTypeComputeConsolidationData(); - return typeComputeConsolidationDataCollection.size() == 1 - && typeComputeConsolidationDataCollection.iterator().next() - .isNumberOfComputeConsolidationDataPerTypeLegal(); + Collection typeComputeConsolidationDataCollection = getAllTypeComputeConsolidationData(); + return typeComputeConsolidationDataCollection.size() == 1 && typeComputeConsolidationDataCollection.iterator().next() + .isNumberOfComputeConsolidationDataPerTypeLegal(); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java index 61f727ab49..2cd431a39b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -38,23 +37,20 @@ public class FileNestedConsolidationData { return nestedTemplateConsolidationData.values(); } - public NestedTemplateConsolidationData getNestedTemplateConsolidationData( - String nestedNodeTemplateId) { + public NestedTemplateConsolidationData getNestedTemplateConsolidationData(String nestedNodeTemplateId) { return nestedTemplateConsolidationData.get(nestedNodeTemplateId); } - public void setNestedTemplateConsolidationData( - String nestedNodeTemplateId, - NestedTemplateConsolidationData nestedTemplateConsolidationData) { + public void setNestedTemplateConsolidationData(String nestedNodeTemplateId, NestedTemplateConsolidationData nestedTemplateConsolidationData) { this.nestedTemplateConsolidationData.put(nestedNodeTemplateId, nestedTemplateConsolidationData); } /** - * create nested template consolidation data if it doesn't exist yet. - * - * @param nestedNodeTemplateId nested node template id - * @return nested template consolidation data by given key - */ + * create nested template consolidation data if it doesn't exist yet. + * + * @param nestedNodeTemplateId nested node template id + * @return nested template consolidation data by given key + */ NestedTemplateConsolidationData addNestedTemplateConsolidationData(String nestedNodeTemplateId) { NestedTemplateConsolidationData consolidationData = getNestedTemplateConsolidationData(nestedNodeTemplateId); if (consolidationData == null) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java index 0300f9fcd9..5b6fe10ab5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Collection; @@ -45,56 +44,44 @@ public class FilePortConsolidationData { return portTemplateConsolidationData.get(portNodeTemplateId); } - public void setPortTemplateConsolidationData(String portNodeTemplateId, - PortTemplateConsolidationData - portTemplateConsolidationData) { + public void setPortTemplateConsolidationData(String portNodeTemplateId, PortTemplateConsolidationData portTemplateConsolidationData) { this.portTemplateConsolidationData.put(portNodeTemplateId, portTemplateConsolidationData); } /** - * If entity doesn't exist yet - create subInterface template consolidation data entity - * base on given parameters. - * - * @return subInterface template consolidation data entity - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { - PortTemplateConsolidationData consolidationData = - addPortTemplateConsolidationData(parentPortNodeTemplateId); - return consolidationData.addSubInterfaceTemplateConsolidationData(resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + * If entity doesn't exist yet - create subInterface template consolidation data entity base on given parameters. + * + * @return subInterface template consolidation data entity + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { + PortTemplateConsolidationData consolidationData = addPortTemplateConsolidationData(parentPortNodeTemplateId); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** - * If entity doesn't exist yet - create subInterface template consolidation data entity - * base on given parameters. - * - * @return subInterface template consolidation data entity - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, - String parentPortResourceId, String parentPortResourceType) { - - PortTemplateConsolidationData consolidationData = - addPortTemplateConsolidationData(parentPortNodeTemplateId, parentPortResourceId, - parentPortResourceType, null); - - return consolidationData.addSubInterfaceTemplateConsolidationData(resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + * If entity doesn't exist yet - create subInterface template consolidation data entity base on given parameters. + * + * @return subInterface template consolidation data entity + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId, String parentPortResourceId, + String parentPortResourceType) { + PortTemplateConsolidationData consolidationData = addPortTemplateConsolidationData(parentPortNodeTemplateId, parentPortResourceId, + parentPortResourceType, null); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** - * If entity doesn't exist yet - create port template consolidation data and - * update it's network role according to given resource parameters. - * - * @return port template consolidation data entity by given keys - */ - PortTemplateConsolidationData addPortTemplateConsolidationData( - String portNodeTemplateId, String portResourceId, String portResourceType, String portType) { + * If entity doesn't exist yet - create port template consolidation data and update it's network role according to given resource parameters. + * + * @return port template consolidation data entity by given keys + */ + PortTemplateConsolidationData addPortTemplateConsolidationData(String portNodeTemplateId, String portResourceId, String portResourceType, + String portType) { PortTemplateConsolidationData consolidationData = getPortTemplateConsolidationData(portNodeTemplateId); if (consolidationData == null) { - consolidationData = createPortTemplateConsolidationData(portNodeTemplateId, - portResourceId, portResourceType, portType); + consolidationData = createPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); setPortTemplateConsolidationData(portNodeTemplateId, consolidationData); } if (consolidationData.getPortType() == null) { @@ -117,14 +104,13 @@ public class FilePortConsolidationData { } return consolidationData; } - - private PortTemplateConsolidationData createPortTemplateConsolidationData(String portNodeTemplateId, - String portResourceId, String portResourceType, String portType) { + + private PortTemplateConsolidationData createPortTemplateConsolidationData(String portNodeTemplateId, String portResourceId, + String portResourceType, String portType) { PortTemplateConsolidationData consolidationData = new PortTemplateConsolidationData(); consolidationData.setNodeTemplateId(portNodeTemplateId); consolidationData.setPortType(portType); - Optional portNetworkRole = HeatResourceUtil.evaluateNetworkRoleFromResourceId(portResourceId, - portResourceType); + Optional portNetworkRole = HeatResourceUtil.evaluateNetworkRoleFromResourceId(portResourceId, portResourceType); portNetworkRole.ifPresent(consolidationData::setNetworkRole); return consolidationData; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java index baef222642..c60bf966b6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; /** @@ -25,58 +24,55 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolid */ public class GetAttrFuncData { - private String fieldName; - private String attributeName; - - public GetAttrFuncData(){} - - public GetAttrFuncData(String fieldName, String attributeName) { - this.fieldName = fieldName; - this.attributeName = attributeName; - } - - public String getFieldName() { - return fieldName; - } - - public void setFieldName(String fieldName) { - this.fieldName = fieldName; - } - - public String getAttributeName() { - return attributeName; - } + private String fieldName; + private String attributeName; - public void setAttributeName(String attributeName) { - this.attributeName = attributeName; - } + public GetAttrFuncData() { + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; + public GetAttrFuncData(String fieldName, String attributeName) { + this.fieldName = fieldName; + this.attributeName = attributeName; } - if (o == null || getClass() != o.getClass()) { - return false; + + public String getFieldName() { + return fieldName; } - GetAttrFuncData that = (GetAttrFuncData) o; + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } - if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { - return false; + public String getAttributeName() { + return attributeName; } - if (attributeName != null ? !attributeName.equals(that.attributeName) - : that.attributeName != null) { - return false; + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; } - return true; - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GetAttrFuncData that = (GetAttrFuncData) o; + if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { + return false; + } + if (attributeName != null ? !attributeName.equals(that.attributeName) : that.attributeName != null) { + return false; + } + return true; + } - @Override - public int hashCode() { - int result = fieldName != null ? fieldName.hashCode() : 0; - result = 31 * result + (attributeName != null ? attributeName.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = fieldName != null ? fieldName.hashCode() : 0; + result = 31 * result + (attributeName != null ? attributeName.hashCode() : 0); + return result; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java index 1521d9d31e..0d24891b10 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.HashMap; @@ -38,19 +37,16 @@ public class NestedConsolidationData { return fileNestedConsolidationData.get(serviceTemplateFileName); } - public void setFileNestedConsolidationData(String serviceTemplateFileName, - FileNestedConsolidationData fileNestedConsolidationData) { + public void setFileNestedConsolidationData(String serviceTemplateFileName, FileNestedConsolidationData fileNestedConsolidationData) { this.fileNestedConsolidationData.put(serviceTemplateFileName, fileNestedConsolidationData); } /** - * Create nested template consolidation data base on given key - if it doesn't exist yet. - * - * @return nested template consolidation data by given keys - */ - NestedTemplateConsolidationData addNestedTemplateConsolidationData( - String serviceTemplateFileName, String nestedNodeTemplateId) { - + * Create nested template consolidation data base on given key - if it doesn't exist yet. + * + * @return nested template consolidation data by given keys + */ + NestedTemplateConsolidationData addNestedTemplateConsolidationData(String serviceTemplateFileName, String nestedNodeTemplateId) { FileNestedConsolidationData consolidationData = addFileNestedConsolidationData(serviceTemplateFileName); return consolidationData.addNestedTemplateConsolidationData(nestedNodeTemplateId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java index 680615000f..6643962152 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationDataHandler.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Objects; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.utilities.file.FileUtils; @@ -27,9 +27,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourceIdsInDifferentFilesErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; - -import java.util.Objects; - public class NestedConsolidationDataHandler implements ConsolidationDataHandler { private final NestedConsolidationData nestedConsolidationData; @@ -40,48 +37,35 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), - translateTo.getTranslatedId()); - + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), + translateTo.getTranslatedId()); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, - String requirementId, RequirementAssignment requirementAssignment) { - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), dependentNodeTemplateId); - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(translateTo, translateTo.getHeatFileName(), + dependentNodeTemplateId); if (Objects.nonNull(entityConsolidationData)) { entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); } } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, - String contrailSharedResourceId, - String sharedTranslatedResourceId) { - - throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList " - + "not supported for NestedConsolidationDataHandler"); - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { + throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList " + "not supported for NestedConsolidationDataHandler"); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, - functionTranslator.getHeatFileName(), resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -89,13 +73,10 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), - targetResourceId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + targetResourceId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -103,13 +84,10 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), - targetResourceId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getNestedTemplateConsolidationData(functionTranslator, functionTranslator.getHeatFileName(), + targetResourceId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -119,10 +97,9 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler /** * Add nested consolidation data base on given parameters. */ - public void addConsolidationData(String serviceTemplateFileName, TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - getNestedTemplateConsolidationData(serviceTemplateFileName, context, - nestedHeatFileName, nestedNodeTemplateId); + public void addConsolidationData(String serviceTemplateFileName, TranslationContext context, String nestedHeatFileName, + String nestedNodeTemplateId) { + getNestedTemplateConsolidationData(serviceTemplateFileName, context, nestedHeatFileName, nestedNodeTemplateId); } private GetAttrFuncData createGetAttrFuncData(String propertyName, String attributeName) { @@ -132,51 +109,43 @@ public class NestedConsolidationDataHandler implements ConsolidationDataHandler return getAttrFuncData; } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData(FunctionTranslator functionTranslator, - String nestedHeatFileName, String nestedNodeTemplateId) { + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(FunctionTranslator functionTranslator, String nestedHeatFileName, + String nestedNodeTemplateId) { ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); TranslationContext context = functionTranslator.getContext(); - return getNestedTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, nestedNodeTemplateId); - + return getNestedTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, + nestedNodeTemplateId); } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData(TranslateTo translateTo, - String nestedHeatFileName, String nestedNodeTemplateId) { + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(TranslateTo translateTo, String nestedHeatFileName, + String nestedNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); TranslationContext context = translateTo.getContext(); - return getNestedTemplateConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, nestedNodeTemplateId); + return getNestedTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), context, nestedHeatFileName, + nestedNodeTemplateId); } - private NestedTemplateConsolidationData getNestedTemplateConsolidationData( - String serviceTemplateFileName, TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - + private NestedTemplateConsolidationData getNestedTemplateConsolidationData(String serviceTemplateFileName, TranslationContext context, + String nestedHeatFileName, String nestedNodeTemplateId) { if (isNestedResourceIdOccursInDifferentNestedFiles(context, nestedHeatFileName, nestedNodeTemplateId)) { throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(nestedNodeTemplateId).build()); } - - if (isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates( - nestedNodeTemplateId, nestedHeatFileName, context)) { + if (isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(nestedNodeTemplateId, nestedHeatFileName, context)) { return null; } - return nestedConsolidationData - .addNestedTemplateConsolidationData(serviceTemplateFileName, nestedNodeTemplateId); + return nestedConsolidationData.addNestedTemplateConsolidationData(serviceTemplateFileName, nestedNodeTemplateId); } - private boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, - String nestedHeatFileName, TranslationContext context) { - - return context.isServiceTemplateWithoutNodeTemplatesSection( - FileUtils.getFileWithoutExtention(nestedHeatFileName)) - || context.isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); + private boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, String nestedHeatFileName, + TranslationContext context) { + return context.isServiceTemplateWithoutNodeTemplatesSection(FileUtils.getFileWithoutExtention(nestedHeatFileName)) || context + .isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); } - private boolean isNestedResourceIdOccursInDifferentNestedFiles(TranslationContext context, - String nestedHeatFileName, String nestedNodeTemplateId) { - return Objects.nonNull(nestedHeatFileName) && context.getAllTranslatedResourceIdsFromDiffNestedFiles( - nestedHeatFileName).contains(nestedNodeTemplateId); + private boolean isNestedResourceIdOccursInDifferentNestedFiles(TranslationContext context, String nestedHeatFileName, + String nestedNodeTemplateId) { + return Objects.nonNull(nestedHeatFileName) && context.getAllTranslatedResourceIdsFromDiffNestedFiles(nestedHeatFileName) + .contains(nestedNodeTemplateId); } public boolean isNestedConsolidationDataExist(String serviceTemplateName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java index dc4ec3303f..8cd37a0fc6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; /** diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java index 132a507298..bddd45c590 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java @@ -13,14 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.openecomp.sdc.heat.datatypes.model.Resource; - import java.util.HashMap; import java.util.Map; import java.util.Set; +import org.openecomp.sdc.heat.datatypes.model.Resource; public class PortConsolidationData { @@ -39,34 +37,31 @@ public class PortConsolidationData { return filePortConsolidationData.get(serviceTemplateFileName); } - public void setFilePortConsolidationData(String serviceTemplateFileName, FilePortConsolidationData - filePortConsolidationData) { + public void setFilePortConsolidationData(String serviceTemplateFileName, FilePortConsolidationData filePortConsolidationData) { this.filePortConsolidationData.put(serviceTemplateFileName, filePortConsolidationData); } /** - * Create port template consolidation data base on given parameters - if it doesn't exist yet. - * - * @return port template consolidation data - */ - PortTemplateConsolidationData addPortTemplateConsolidationData(String serviceTemplateFileName, - String portNodeTemplateId, String portResourceId, String portResourceType, String portType) { + * Create port template consolidation data base on given parameters - if it doesn't exist yet. + * + * @return port template consolidation data + */ + PortTemplateConsolidationData addPortTemplateConsolidationData(String serviceTemplateFileName, String portNodeTemplateId, String portResourceId, + String portResourceType, String portType) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData - .addPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); + return consolidationData.addPortTemplateConsolidationData(portNodeTemplateId, portResourceId, portResourceType, portType); } /** - * Create subInterface template consolidation data base on given parameters - if it doesn't exist yet. - * - * @return port template consolidation data by given keys - */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - String serviceTemplateFileName, Resource resource, String subInterfaceNodeTemplateId, - String parentPortNodeTemplateId) { + * Create subInterface template consolidation data base on given parameters - if it doesn't exist yet. + * + * @return port template consolidation data by given keys + */ + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(String serviceTemplateFileName, Resource resource, + String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData.addSubInterfaceTemplateConsolidationData( - resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); + return consolidationData.addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } /** @@ -74,14 +69,13 @@ public class PortConsolidationData { * * @return port template consolidation data by given keys */ - SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - String serviceTemplateFileName, Resource resource, - String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, - String parentPortResourceId, String parentPortResourceType) { + SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(String serviceTemplateFileName, Resource resource, + String subInterfaceNodeTemplateId, String parentPortNodeTemplateId, + String parentPortResourceId, String parentPortResourceType) { FilePortConsolidationData consolidationData = addFilePortConsolidationData(serviceTemplateFileName); - return consolidationData.addSubInterfaceTemplateConsolidationData( - resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, - parentPortResourceId, parentPortResourceType); + return consolidationData + .addSubInterfaceTemplateConsolidationData(resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, parentPortResourceId, + parentPortResourceType); } private FilePortConsolidationData addFilePortConsolidationData(String serviceTemplateFileName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java index 5114e5d25d..c76cec11bc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationDataHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Objects; @@ -35,60 +34,43 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), - translateTo.getResource().getType(), translateTo.getTranslatedId()); - + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), + translateTo.getResource().getType(), translateTo.getTranslatedId()); entityConsolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment); - } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, String requirementId, - RequirementAssignment requirementAssignment) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), - translateTo.getResource().getType(), dependentNodeTemplateId); - + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(translateTo, translateTo.getResourceId(), + translateTo.getResource().getType(), dependentNodeTemplateId); entityConsolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment); - } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, String paramName, - String contrailSharedResourceId, String sharedTranslatedResourceId) { - + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { Resource resource = heatOrchestrationTemplate.getResources().get(contrailSharedResourceId); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(serviceTemplateFileName, - contrailSharedResourceId, resource.getType(), sharedTranslatedResourceId, null); + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(serviceTemplateFileName, contrailSharedResourceId, + resource.getType(), sharedTranslatedResourceId, null); entityConsolidationData.removeParamNameFromAttrFuncList(paramName); - } /** * Add port in consolidation data base on given parameters. - * */ - public void addConsolidationData(String serviceTemplateFileName, - String portResourceId, String portResourceType, String portNodeTemplateId, String portType) { - getPortTemplateConsolidationData( - serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); + public void addConsolidationData(String serviceTemplateFileName, String portResourceId, String portResourceType, String portNodeTemplateId, + String portType) { + getPortTemplateConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { String resourceId = functionTranslator.getResourceId(); - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, resourceId, resourceTranslatedId); - + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, resourceId, resourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -96,11 +78,10 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attributeName) { - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -108,12 +89,10 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - EntityConsolidationData entityConsolidationData = - getPortTemplateConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(functionTranslator, targetResourceId, + targetResourceTranslatedId); if (Objects.nonNull(entityConsolidationData)) { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -127,28 +106,25 @@ public class PortConsolidationDataHandler implements ConsolidationDataHandler { return getAttrFuncData; } - private EntityConsolidationData getPortTemplateConsolidationData(FunctionTranslator functionTranslator, - String targetResourceId, String targetResourceTranslatedId) { + private EntityConsolidationData getPortTemplateConsolidationData(FunctionTranslator functionTranslator, String targetResourceId, + String targetResourceTranslatedId) { HeatOrchestrationTemplate heatOrchestrationTemplate = functionTranslator.getHeatOrchestrationTemplate(); Resource resource = heatOrchestrationTemplate.getResources().get(targetResourceId); ServiceTemplate serviceTemplate = functionTranslator.getServiceTemplate(); - return getPortTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - targetResourceId, resource.getType(), targetResourceTranslatedId, null); + return getPortTemplateConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), targetResourceId, resource.getType(), + targetResourceTranslatedId, null); } - private PortTemplateConsolidationData getPortTemplateConsolidationData(TranslateTo translateTo, - String portResourceId, String portResourceType, String portNodeTemplateId) { + private PortTemplateConsolidationData getPortTemplateConsolidationData(TranslateTo translateTo, String portResourceId, String portResourceType, + String portNodeTemplateId) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - return getPortTemplateConsolidationData(serviceTemplateFileName, - portResourceId, portResourceType, portNodeTemplateId, null); + return getPortTemplateConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, null); } - private PortTemplateConsolidationData getPortTemplateConsolidationData(String serviceTemplateFileName, - String portResourceId, String portResourceType, String portNodeTemplateId, String portType) { - - return portConsolidationData.addPortTemplateConsolidationData(serviceTemplateFileName, - portNodeTemplateId, portResourceId, portResourceType, portType); - + private PortTemplateConsolidationData getPortTemplateConsolidationData(String serviceTemplateFileName, String portResourceId, + String portResourceType, String portNodeTemplateId, String portType) { + return portConsolidationData + .addPortTemplateConsolidationData(serviceTemplateFileName, portNodeTemplateId, portResourceId, portResourceType, portType); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java index b529c7a55e..63ac262c70 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java @@ -13,31 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimaps; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - public class PortTemplateConsolidationData extends EntityConsolidationData { - // key - sub-interface type - for ResourceGroup it is the nested file name - // value - List of sub-interfaces of that type in the port - private final ListMultimap subInterfaceConsolidationData = - Multimaps.synchronizedListMultimap(ArrayListMultimap.create()); + // value - List of sub-interfaces of that type in the port + private final ListMultimap subInterfaceConsolidationData = Multimaps + .synchronizedListMultimap(ArrayListMultimap.create()); private String portType; - private String networkRole; public String getNetworkRole() { @@ -61,60 +57,51 @@ public class PortTemplateConsolidationData extends EntityConsolidationData { } /** - * Create Sub interface template consolidation data base on given parameters - if it doesn't exist yet. - * - * @param resource resource of sub Interface - * @param subInterfaceNodeTemplateId template id of sub interface - * @param parentPortNodeTemplateId node template id of port node to which sub interface is related - * @return sub interface template consolidation data entity - */ - public SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData( - Resource resource, String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { + * Create Sub interface template consolidation data base on given parameters - if it doesn't exist yet. + * + * @param resource resource of sub Interface + * @param subInterfaceNodeTemplateId template id of sub interface + * @param parentPortNodeTemplateId node template id of port node to which sub interface is related + * @return sub interface template consolidation data entity + */ + public SubInterfaceTemplateConsolidationData addSubInterfaceTemplateConsolidationData(Resource resource, String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { String subInterfaceType = createSubInterfaceType(resource); - List subInterfaceTemplateConsolidationDataList = - subInterfaceConsolidationData.get(subInterfaceType); + List subInterfaceTemplateConsolidationDataList = subInterfaceConsolidationData.get(subInterfaceType); SubInterfaceTemplateConsolidationData consolidationData = null; if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { - Optional optionalConsolidationData = - subInterfaceTemplateConsolidationDataList.stream() - .filter(s -> s.getNodeTemplateId().equals(subInterfaceNodeTemplateId)) - .findFirst(); + Optional optionalConsolidationData = subInterfaceTemplateConsolidationDataList.stream() + .filter(s -> s.getNodeTemplateId().equals(subInterfaceNodeTemplateId)).findFirst(); if (optionalConsolidationData.isPresent()) { consolidationData = optionalConsolidationData.get(); } } - if (Objects.isNull(consolidationData)) { - consolidationData = - createSubInterfaceConsolidationData(subInterfaceNodeTemplateId, parentPortNodeTemplateId); + consolidationData = createSubInterfaceConsolidationData(subInterfaceNodeTemplateId, parentPortNodeTemplateId); addSubInterfaceConsolidationData(subInterfaceType, consolidationData); } return consolidationData; } private String createSubInterfaceType(Resource resource) { - return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX - + FileUtils.getFileWithoutExtention( - HeatToToscaUtil.getSubInterfaceResourceType(resource)); + return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX + FileUtils + .getFileWithoutExtention(HeatToToscaUtil.getSubInterfaceResourceType(resource)); } - private SubInterfaceTemplateConsolidationData createSubInterfaceConsolidationData( - String subInterfaceNodeTemplateId, String parentPortNodeTemplateId) { + private SubInterfaceTemplateConsolidationData createSubInterfaceConsolidationData(String subInterfaceNodeTemplateId, + String parentPortNodeTemplateId) { SubInterfaceTemplateConsolidationData data = new SubInterfaceTemplateConsolidationData(); data.setNodeTemplateId(subInterfaceNodeTemplateId); data.setParentPortNodeTemplateId(parentPortNodeTemplateId); return data; } - public void addSubInterfaceConsolidationData(String subPortType, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData) { + public void addSubInterfaceConsolidationData(String subPortType, SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData) { this.subInterfaceConsolidationData.put(subPortType, subInterfaceTemplateConsolidationData); } public boolean hasSameSubInterfaceTypes(PortTemplateConsolidationData other) { - return other != null && this.subInterfaceConsolidationData.keySet().equals( - other.subInterfaceConsolidationData.keySet()); + return other != null && this.subInterfaceConsolidationData.keySet().equals(other.subInterfaceConsolidationData.keySet()); } public void copyMappedInto(ListMultimap subInterfaceTypeToEntity) { @@ -127,31 +114,26 @@ public class PortTemplateConsolidationData extends EntityConsolidationData { public boolean isNumberOfSubInterfacesPerTypeSimilar(PortTemplateConsolidationData other) { return isBothSubInterfaceConsolidationDataEmpty(this, other) - || isBothSubInterfaceConsolidationDataNotEmpty(this, other) - && this.subInterfaceConsolidationData.keySet().stream().allMatch( - subInterfaceType -> calculateSize(other.subInterfaceConsolidationData.get(subInterfaceType)) - == calculateSize(this.subInterfaceConsolidationData.get(subInterfaceType))); - + || isBothSubInterfaceConsolidationDataNotEmpty(this, other) && this.subInterfaceConsolidationData.keySet().stream().allMatch( + subInterfaceType -> calculateSize(other.subInterfaceConsolidationData.get(subInterfaceType)) == calculateSize( + this.subInterfaceConsolidationData.get(subInterfaceType))); } - private boolean isBothSubInterfaceConsolidationDataEmpty( - PortTemplateConsolidationData object, PortTemplateConsolidationData other) { + private boolean isBothSubInterfaceConsolidationDataEmpty(PortTemplateConsolidationData object, PortTemplateConsolidationData other) { return object.subInterfaceConsolidationData.isEmpty() && other.subInterfaceConsolidationData.isEmpty(); } - private boolean isBothSubInterfaceConsolidationDataNotEmpty( - PortTemplateConsolidationData object, PortTemplateConsolidationData other) { + private boolean isBothSubInterfaceConsolidationDataNotEmpty(PortTemplateConsolidationData object, PortTemplateConsolidationData other) { return !object.subInterfaceConsolidationData.isEmpty() && !other.subInterfaceConsolidationData.isEmpty(); } public boolean isSubInterfaceNodeTemplateIdParameter(String nodeTemplateType) { - List subInterfaceTemplateConsolidationDataList = - this.subInterfaceConsolidationData.get(nodeTemplateType); - return (Objects.nonNull(subInterfaceTemplateConsolidationDataList) - && subInterfaceTemplateConsolidationDataList.size() > 1); + List subInterfaceTemplateConsolidationDataList = this.subInterfaceConsolidationData + .get(nodeTemplateType); + return (Objects.nonNull(subInterfaceTemplateConsolidationDataList) && subInterfaceTemplateConsolidationDataList.size() > 1); } private int calculateSize(List subInterfaces) { return subInterfaces == null ? 0 : subInterfaces.size(); } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java index 934db78bfa..32cb7302a4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -27,54 +26,53 @@ import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; */ public class RequirementAssignmentData { - private String requirementId; - private RequirementAssignment requirementAssignment; + private String requirementId; + private RequirementAssignment requirementAssignment; - /** - * Instantiates a new Requirement assignment data. - * - * @param requirementId the requirement id - * @param requirementAssignment the requirement assignment - */ - public RequirementAssignmentData(String requirementId, RequirementAssignment - requirementAssignment) { - this.requirementId = requirementId; - this.requirementAssignment = requirementAssignment; - } + /** + * Instantiates a new Requirement assignment data. + * + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public RequirementAssignmentData(String requirementId, RequirementAssignment requirementAssignment) { + this.requirementId = requirementId; + this.requirementAssignment = requirementAssignment; + } - /** - * Gets requirement id. - * - * @return the requirement id - */ - public String getRequirementId() { - return requirementId; - } + /** + * Gets requirement id. + * + * @return the requirement id + */ + public String getRequirementId() { + return requirementId; + } - /** - * Sets requirement id. - * - * @param requirementId the requirement id - */ - public void setRequirementId(String requirementId) { - this.requirementId = requirementId; - } + /** + * Sets requirement id. + * + * @param requirementId the requirement id + */ + public void setRequirementId(String requirementId) { + this.requirementId = requirementId; + } - /** - * Gets requirement assignment. - * - * @return the requirement assignment - */ - public RequirementAssignment getRequirementAssignment() { - return requirementAssignment; - } + /** + * Gets requirement assignment. + * + * @return the requirement assignment + */ + public RequirementAssignment getRequirementAssignment() { + return requirementAssignment; + } - /** - * Sets requirement assignment. - * - * @param requirementAssignment the requirement assignment - */ - public void setRequirementAssignment(RequirementAssignment requirementAssignment) { - this.requirementAssignment = requirementAssignment; - } + /** + * Sets requirement assignment. + * + * @param requirementAssignment the requirement assignment + */ + public void setRequirementAssignment(RequirementAssignment requirementAssignment) { + this.requirementAssignment = requirementAssignment; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java index d1b4148672..dc79cf91c9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceConsolidationDataHandler.java @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -41,56 +39,42 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa @Override public void addNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { + RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - if (Objects.nonNull( - serviceTemplate.getTopology_template().getNode_templates().get(translateTo.getTranslatedId()))) { - Optional subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translateTo.getTranslatedId()); - - subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> - consolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment)); + if (Objects.nonNull(serviceTemplate.getTopology_template().getNode_templates().get(translateTo.getTranslatedId()))) { + Optional subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData( + translateTo, translateTo.getTranslatedId()); + subInterfaceTemplateConsolidationData + .ifPresent(consolidationData -> consolidationData.addNodesConnectedOut(nodeTemplateId, requirementId, requirementAssignment)); } } @Override - public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - String dependentNodeTemplateId, String targetResourceId, - String requirementId, RequirementAssignment requirementAssignment) { + public void addNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, String dependentNodeTemplateId, String targetResourceId, + String requirementId, RequirementAssignment requirementAssignment) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); TranslationContext translationContext = translateTo.getContext(); Resource targetResource = translateTo.getHeatOrchestrationTemplate().getResources().get(targetResourceId); - TranslateTo subInterfaceTo = new TranslateTo(translateTo.getHeatFileName(), serviceTemplate, - translateTo.getHeatOrchestrationTemplate(), targetResource, - targetResourceId, null, translationContext); - Optional subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceId); - - subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> - consolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment)); - + TranslateTo subInterfaceTo = new TranslateTo(translateTo.getHeatFileName(), serviceTemplate, translateTo.getHeatOrchestrationTemplate(), + targetResource, targetResourceId, null, translationContext); + Optional subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData( + subInterfaceTo, targetResourceId); + subInterfaceTemplateConsolidationData + .ifPresent(consolidationData -> consolidationData.addNodesConnectedIn(sourceNodeTemplateId, requirementId, requirementAssignment)); } @Override - public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String paramName, String contrailSharedResourceId, - String sharedTranslatedResourceId) { - - - throw new UnsupportedOperationException( - "API removeParamNameFromAttrFuncList doesn't supported for SubInterfaceConsolidationDataHandler"); + public void removeParamNameFromAttrFuncList(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + String paramName, String contrailSharedResourceId, String sharedTranslatedResourceId) { + throw new UnsupportedOperationException("API removeParamNameFromAttrFuncList doesn't supported for SubInterfaceConsolidationDataHandler"); } @Override - public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, - String resourceTranslatedId, String propertyName, String attributeName) { - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, functionTranslator.getResourceId(), - resourceTranslatedId); - - Optional subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, resourceTranslatedId); - + public void addNodesGetAttrOut(FunctionTranslator functionTranslator, String nodeTemplateId, String resourceTranslatedId, String propertyName, + String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, functionTranslator.getResourceId(), resourceTranslatedId); + Optional subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + resourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); @@ -98,15 +82,11 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } @Override - public void addNodesGetAttrIn(FunctionTranslator functionTranslator,String nodeTemplateId, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, - targetResourceTranslatedId); - - Optional subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceTranslatedId); - + public void addNodesGetAttrIn(FunctionTranslator functionTranslator, String nodeTemplateId, String targetResourceId, + String targetResourceTranslatedId, String propertyName, String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, targetResourceTranslatedId); + Optional subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + targetResourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); @@ -114,14 +94,11 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } @Override - public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, - String targetResourceTranslatedId, String propertyName, String attributeName) { - TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, - targetResourceTranslatedId); - - Optional subInterfaceConsolidationData = - getSubInterfaceTemplateConsolidationData(subInterfaceTo, targetResourceTranslatedId); - + public void addOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attributeName) { + TranslateTo subInterfaceTo = createTranslateTo(functionTranslator, targetResourceId, targetResourceTranslatedId); + Optional subInterfaceConsolidationData = getSubInterfaceTemplateConsolidationData(subInterfaceTo, + targetResourceTranslatedId); subInterfaceConsolidationData.ifPresent(consolidationData -> { GetAttrFuncData getAttrFuncData = createGetAttrFuncData(propertyName, attributeName); consolidationData.addOutputParamGetAttrIn(getAttrFuncData); @@ -129,77 +106,62 @@ public class SubInterfaceConsolidationDataHandler implements ConsolidationDataHa } public void setNetworkRole(TranslateTo translateTo, String translatedId, String networkRole) { - Optional subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translatedId); - - subInterfaceTemplateConsolidationData.ifPresent( - consolidationData -> consolidationData.setNetworkRole(networkRole)); + Optional subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData(translateTo, + translatedId); + subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> consolidationData.setNetworkRole(networkRole)); } - public void setResourceGroupCount(TranslateTo translateTo, String translatedId, - Object resourceGroupCount) { - Optional subInterfaceTemplateConsolidationData = - getSubInterfaceTemplateConsolidationData(translateTo, translatedId); - - subInterfaceTemplateConsolidationData.ifPresent( - consolidationData -> consolidationData.setResourceGroupCount(resourceGroupCount)); + public void setResourceGroupCount(TranslateTo translateTo, String translatedId, Object resourceGroupCount) { + Optional subInterfaceTemplateConsolidationData = getSubInterfaceTemplateConsolidationData(translateTo, + translatedId); + subInterfaceTemplateConsolidationData.ifPresent(consolidationData -> consolidationData.setResourceGroupCount(resourceGroupCount)); } - private Optional getSubInterfaceTemplateConsolidationData( - TranslateTo subInterfaceTo, String subInterfaceNodeTemplateId) { - Optional parentPortNodeTemplateId = - HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(subInterfaceTo); - return parentPortNodeTemplateId.map(s -> getSubInterfaceTemplateConsolidationData(subInterfaceTo, - s, subInterfaceNodeTemplateId)); + private Optional getSubInterfaceTemplateConsolidationData(TranslateTo subInterfaceTo, + String subInterfaceNodeTemplateId) { + Optional parentPortNodeTemplateId = HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(subInterfaceTo); + return parentPortNodeTemplateId.map(s -> getSubInterfaceTemplateConsolidationData(subInterfaceTo, s, subInterfaceNodeTemplateId)); } private SubInterfaceTemplateConsolidationData getSubInterfaceTemplateConsolidationData(TranslateTo subInterfaceTo, - String parentPortNodeTemplateId, String subInterfaceNodeTemplateId) { + String parentPortNodeTemplateId, + String subInterfaceNodeTemplateId) { String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(subInterfaceTo.getServiceTemplate()); Resource resource = subInterfaceTo.getResource(); Optional portResourceId = getPortResourceId(subInterfaceTo, parentPortNodeTemplateId); - if (portResourceId.isPresent()) { String portResourceType = getPortResourceType(subInterfaceTo, portResourceId.get()); return portConsolidationData - .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId, - portResourceId.get(), portResourceType); + .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId, + portResourceId.get(), portResourceType); } else { return portConsolidationData - .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, - subInterfaceNodeTemplateId, parentPortNodeTemplateId); + .addSubInterfaceTemplateConsolidationData(serviceTemplateFileName, resource, subInterfaceNodeTemplateId, parentPortNodeTemplateId); } } private String getPortResourceType(TranslateTo subInterfaceTo, String portResourceId) { - return HeatToToscaUtil.getResourceType(portResourceId, subInterfaceTo - .getHeatOrchestrationTemplate(), subInterfaceTo.getHeatFileName()); + return HeatToToscaUtil.getResourceType(portResourceId, subInterfaceTo.getHeatOrchestrationTemplate(), subInterfaceTo.getHeatFileName()); } private Optional getPortResourceId(TranslateTo subInterfaceTo, String parentPortNodeTemplateId) { - Map resourceIdTranslatedResourceIdMap = - subInterfaceTo.getContext().getTranslatedIds().get(subInterfaceTo.getHeatFileName()); - return getSubInterfaceParentPortResourceId(parentPortNodeTemplateId, - resourceIdTranslatedResourceIdMap); + Map resourceIdTranslatedResourceIdMap = subInterfaceTo.getContext().getTranslatedIds().get(subInterfaceTo.getHeatFileName()); + return getSubInterfaceParentPortResourceId(parentPortNodeTemplateId, resourceIdTranslatedResourceIdMap); } private Optional getSubInterfaceParentPortResourceId(String parentPortNodeTemplateId, - Map resourceIdTranslatedResourceIdMap) { + Map resourceIdTranslatedResourceIdMap) { if (MapUtils.isEmpty(resourceIdTranslatedResourceIdMap)) { return Optional.empty(); } - return resourceIdTranslatedResourceIdMap.entrySet().stream() - .filter(entry -> entry.getValue().equals(parentPortNodeTemplateId)) - .findFirst().map(Map.Entry::getKey); + return resourceIdTranslatedResourceIdMap.entrySet().stream().filter(entry -> entry.getValue().equals(parentPortNodeTemplateId)).findFirst() + .map(Map.Entry::getKey); } - private TranslateTo createTranslateTo(FunctionTranslator functionTranslator, String resourceId, - String resourceTranslatedId) { + private TranslateTo createTranslateTo(FunctionTranslator functionTranslator, String resourceId, String resourceTranslatedId) { Resource resource = functionTranslator.getHeatOrchestrationTemplate().getResources().get(resourceId); - return new TranslateTo(ToscaUtil.getServiceTemplateFileName(functionTranslator.getServiceTemplate()), - functionTranslator.getServiceTemplate(), functionTranslator.getHeatOrchestrationTemplate(), - resource, resourceId, resourceTranslatedId, functionTranslator.getContext()); + return new TranslateTo(ToscaUtil.getServiceTemplateFileName(functionTranslator.getServiceTemplate()), functionTranslator.getServiceTemplate(), + functionTranslator.getHeatOrchestrationTemplate(), resource, resourceId, resourceTranslatedId, functionTranslator.getContext()); } private GetAttrFuncData createGetAttrFuncData(String propertyName, String attributeName) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java index 261231a5c6..a0e7c7eea2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/SubInterfaceTemplateConsolidationData.java @@ -13,68 +13,63 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import java.util.Optional; - public class SubInterfaceTemplateConsolidationData extends EntityConsolidationData { - //Value of the property count in the resource group representing the sub-interface - private Object resourceGroupCount; - //Network role of the sub-interface - private String networkRole; - //Parent port node template id - private String parentPortNodeTemplateId; - - public Object getResourceGroupCount() { - return resourceGroupCount; - } + //Value of the property count in the resource group representing the sub-interface + private Object resourceGroupCount; + //Network role of the sub-interface + private String networkRole; + //Parent port node template id + private String parentPortNodeTemplateId; - public void setResourceGroupCount(Object resourceGroupCount) { - this.resourceGroupCount = resourceGroupCount; - } + public Object getResourceGroupCount() { + return resourceGroupCount; + } - public String getNetworkRole() { - return networkRole; - } + public void setResourceGroupCount(Object resourceGroupCount) { + this.resourceGroupCount = resourceGroupCount; + } - public void setNetworkRole(String networkRole) { - this.networkRole = networkRole; - } + public String getNetworkRole() { + return networkRole; + } - public String getParentPortNodeTemplateId() { - return parentPortNodeTemplateId; - } + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } - public void setParentPortNodeTemplateId(String parentPortNodeTemplateId) { - this.parentPortNodeTemplateId = parentPortNodeTemplateId; - } + public String getParentPortNodeTemplateId() { + return parentPortNodeTemplateId; + } - public Optional getParentPortTemplateConsolidationData(ServiceTemplate serviceTemplate, - TranslationContext context) { - FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); - PortTemplateConsolidationData portTemplateConsolidationData = null; - if (filePortConsolidationData != null) { - portTemplateConsolidationData = filePortConsolidationData - .getPortTemplateConsolidationData(parentPortNodeTemplateId); + public void setParentPortNodeTemplateId(String parentPortNodeTemplateId) { + this.parentPortNodeTemplateId = parentPortNodeTemplateId; } - return Optional.ofNullable(portTemplateConsolidationData); - } - public Optional getParentPortNetworkRole(ServiceTemplate serviceTemplate, - TranslationContext context) { - Optional subInterfacePortTemplateConsolidationData = - getParentPortTemplateConsolidationData(serviceTemplate, context); - if (!subInterfacePortTemplateConsolidationData.isPresent()) { - return Optional.empty(); + public Optional getParentPortTemplateConsolidationData(ServiceTemplate serviceTemplate, + TranslationContext context) { + FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + PortTemplateConsolidationData portTemplateConsolidationData = null; + if (filePortConsolidationData != null) { + portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(parentPortNodeTemplateId); + } + return Optional.ofNullable(portTemplateConsolidationData); } - return Optional.ofNullable(subInterfacePortTemplateConsolidationData.get().getNetworkRole()); - } + public Optional getParentPortNetworkRole(ServiceTemplate serviceTemplate, TranslationContext context) { + Optional subInterfacePortTemplateConsolidationData = getParentPortTemplateConsolidationData(serviceTemplate, + context); + if (!subInterfacePortTemplateConsolidationData.isPresent()) { + return Optional.empty(); + } + return Optional.ofNullable(subInterfacePortTemplateConsolidationData.get().getNetworkRole()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java index 94ea467759..8ff6140693 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java @@ -13,16 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; -import org.apache.commons.collections4.CollectionUtils; - import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.collections4.CollectionUtils; public class TypeComputeConsolidationData { @@ -42,27 +40,24 @@ public class TypeComputeConsolidationData { } /** - * Gets compute template consolidation data. - * - * @param computeNodeTemplateId the compute node template id - * @return the compute template consolidation data - */ - public ComputeTemplateConsolidationData getComputeTemplateConsolidationData( - String computeNodeTemplateId) { + * Gets compute template consolidation data. + * + * @param computeNodeTemplateId the compute node template id + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData(String computeNodeTemplateId) { return computeTemplateConsolidationData.get(computeNodeTemplateId); } - public void setComputeTemplateConsolidationData(String computeNodeTemplateId, - ComputeTemplateConsolidationData - computeTemplateConsolidationData) { + public void setComputeTemplateConsolidationData(String computeNodeTemplateId, ComputeTemplateConsolidationData computeTemplateConsolidationData) { this.computeTemplateConsolidationData.put(computeNodeTemplateId, computeTemplateConsolidationData); } /** - * create new compute template consolidation data if it doesn't exist yet. - * - * @return compute template consolidation data entity by given keys - */ + * create new compute template consolidation data if it doesn't exist yet. + * + * @return compute template consolidation data entity by given keys + */ ComputeTemplateConsolidationData addComputeTemplateConsolidationData(String computeNodeTemplateId) { ComputeTemplateConsolidationData consolidationData = getComputeTemplateConsolidationData(computeNodeTemplateId); if (consolidationData == null) { @@ -74,20 +69,15 @@ public class TypeComputeConsolidationData { } /** - * Gets all ports per port type, which are connected to the computes consolidation data entities - * computeTemplateConsolidationDataCollection. + * Gets all ports per port type, which are connected to the computes consolidation data entities computeTemplateConsolidationDataCollection. * * @return Map containing key as port type and value as ports id */ public Map> collectAllPortsOfEachTypeFromComputes() { Map> portTypeToIds = new HashMap<>(); - Collection computeTemplateConsolidationDataCollection = - getAllComputeTemplateConsolidationData(); - + Collection computeTemplateConsolidationDataCollection = getAllComputeTemplateConsolidationData(); computeTemplateConsolidationDataCollection - .forEach(computeTemplateConsolidationData1 -> - computeTemplateConsolidationData1.collectAllPortsOfEachTypeFromCompute(portTypeToIds)); - + .forEach(computeTemplateConsolidationData1 -> computeTemplateConsolidationData1.collectAllPortsOfEachTypeFromCompute(portTypeToIds)); return portTypeToIds; } @@ -98,13 +88,10 @@ public class TypeComputeConsolidationData { * @return true if get attr out are legal else false */ public boolean isGetAttrOutFromEntityLegal(Map> portTypeToIds) { - Collection entities = getAllComputeTemplateConsolidationData(); - if (CollectionUtils.isEmpty(entities)) { return true; } - EntityConsolidationData firstEntity = entities.iterator().next(); return firstEntity.isGetAttrOutFromEntityLegal(entities, portTypeToIds); } @@ -118,23 +105,16 @@ public class TypeComputeConsolidationData { } public boolean isNumberOfPortFromEachTypeLegal() { - return getAllComputeTemplateConsolidationData().stream().allMatch( - ComputeTemplateConsolidationData::isNumberOfPortFromEachTypeLegal); + return getAllComputeTemplateConsolidationData().stream().allMatch(ComputeTemplateConsolidationData::isNumberOfPortFromEachTypeLegal); } public boolean isPortTypesEqualsBetweenComputeNodes() { Set startingPortTypes = getAllComputeTemplateConsolidationData().iterator().next().getPortsIds(); - - return getAllComputeTemplateConsolidationData() - .stream().allMatch(compute -> compute.getPortsIds().equals(startingPortTypes)); + return getAllComputeTemplateConsolidationData().stream().allMatch(compute -> compute.getPortsIds().equals(startingPortTypes)); } public boolean isNumberOfPortsEqualsBetweenComputeNodes() { - int startingNumberOfPorts = - getAllComputeTemplateConsolidationData().iterator().next().getNumberOfPorts(); - - return getAllComputeTemplateConsolidationData() - .stream().allMatch(compute -> compute.getNumberOfPorts() == startingNumberOfPorts); - + int startingNumberOfPorts = getAllComputeTemplateConsolidationData().iterator().next().getNumberOfPorts(); + return getAllComputeTemplateConsolidationData().stream().allMatch(compute -> compute.getNumberOfPorts() == startingNumberOfPorts); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java index fe2286c912..8f9df4c078 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,19 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.impl.heattotosca; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; - public class HeatToToscaTranslatorFactoryImpl extends HeatToToscaTranslatorFactory { - private static HeatToToscaTranslator INSTANCE = new HeatToToscaTranslatorImpl(); + private static HeatToToscaTranslator INSTANCE = new HeatToToscaTranslatorImpl(); - @Override - public HeatToToscaTranslator createInterface() { - return new HeatToToscaTranslatorImpl(); - } + @Override + public HeatToToscaTranslator createInterface() { + return new HeatToToscaTranslatorImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java index 54a0285026..d713e9ce7c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.impl.heattotosca; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.datatypes.TranslatorOutput; @@ -42,102 +45,87 @@ import org.openecomp.sdc.translator.services.heattotosca.TranslationService; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionManager; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { - private TranslationContext translationContext = new TranslationContext(); - private ValidationManager validationManager = - ValidationManagerFactory.getInstance().createInterface(); - private boolean isValid = false; - - - @Override - public void addManifest(String name, byte[] content) { - ManifestContent manifestData = JsonUtil.json2Object(new String(content), ManifestContent.class); - ManifestFile manifest = new ManifestFile(); - manifest.setName(name); - manifest.setContent(manifestData); - translationContext.setManifest(manifest); - translationContext.addFile(name, content); - validationManager.addFile(SdcCommon.MANIFEST_NAME, content); - addFilesFromManifestToTranslationContextManifestFilesMap(manifestData.getData()); - isValid = false; - } - - @Override - public void addFile(String name, byte[] content) { - translationContext.addFile(name, content); - validationManager.addFile(name, content); - isValid = false; - } - - @Override - public void addFile(String name, InputStream content) { - addFile(name, FileUtils.toByteArray(content)); - } - - - @Override - public Map> validate() { - - Map> errors = new HashMap<>(); - if (translationContext.getManifest() == null) { - ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) - .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); - return errors; + private TranslationContext translationContext = new TranslationContext(); + private ValidationManager validationManager = ValidationManagerFactory.getInstance().createInterface(); + private boolean isValid = false; + + @Override + public void addManifest(String name, byte[] content) { + ManifestContent manifestData = JsonUtil.json2Object(new String(content), ManifestContent.class); + ManifestFile manifest = new ManifestFile(); + manifest.setName(name); + manifest.setContent(manifestData); + translationContext.setManifest(manifest); + translationContext.addFile(name, content); + validationManager.addFile(SdcCommon.MANIFEST_NAME, content); + addFilesFromManifestToTranslationContextManifestFilesMap(manifestData.getData()); + isValid = false; } - if (MapUtils.isEmpty(errors)) { - errors = validationManager.validate(); + @Override + public void addFile(String name, byte[] content) { + translationContext.addFile(name, content); + validationManager.addFile(name, content); + isValid = false; } - if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { - isValid = true; + + @Override + public void addFile(String name, InputStream content) { + addFile(name, FileUtils.toByteArray(content)); } - return errors; - } - @Override - public TranslatorOutput translate() { - TranslationService translationService = new TranslationService(); - TranslatorOutput translatorOutput = new TranslatorOutput(); - UnifiedCompositionManager unifiedCompositionManager = new UnifiedCompositionManager(new - ConsolidationService(new UnifiedCompositionService())); - if (!isValid) { - Map> errors = validate(); + @Override + public Map> validate() { + Map> errors = new HashMap<>(); + if (translationContext.getManifest() == null) { + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) + .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); + return errors; + } + if (MapUtils.isEmpty(errors)) { + errors = validationManager.validate(); + } + if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { + isValid = true; + } + return errors; + } - if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { - translatorOutput.setErrorMessages(errors); + @Override + public TranslatorOutput translate() { + TranslationService translationService = new TranslationService(); + TranslatorOutput translatorOutput = new TranslatorOutput(); + UnifiedCompositionManager unifiedCompositionManager = new UnifiedCompositionManager( + new ConsolidationService(new UnifiedCompositionService())); + if (!isValid) { + Map> errors = validate(); + if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { + translatorOutput.setErrorMessages(errors); + return translatorOutput; + } + } + translatorOutput = translationService.translateHeatFiles(translationContext); + ToscaServiceModel unifiedToscaServiceModel = unifiedCompositionManager + .createUnifiedComposition(translatorOutput.getToscaServiceModel(), translationContext); + translatorOutput.setToscaServiceModel(unifiedToscaServiceModel); return translatorOutput; - } } - translatorOutput = translationService.translateHeatFiles(translationContext); - ToscaServiceModel unifiedToscaServiceModel = unifiedCompositionManager - .createUnifiedComposition(translatorOutput.getToscaServiceModel(), translationContext); - translatorOutput.setToscaServiceModel(unifiedToscaServiceModel); - return translatorOutput; - } - - @Override - public void addExternalArtifacts(String name, byte[] content) { - translationContext.addExternalArtifacts(name, content); - } - - @Override - public void addExternalArtifacts(String name, InputStream content) { - addExternalArtifacts(name, FileUtils.toByteArray(content)); - } - - private void addFilesFromManifestToTranslationContextManifestFilesMap( - List fileDataListFromManifest) { - for (FileData fileFromManfiest : fileDataListFromManifest) { - translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType()); + @Override + public void addExternalArtifacts(String name, byte[] content) { + translationContext.addExternalArtifacts(name, content); } - } + @Override + public void addExternalArtifacts(String name, InputStream content) { + addExternalArtifacts(name, FileUtils.toByteArray(content)); + } + private void addFilesFromManifestToTranslationContextManifestFilesMap(List fileDataListFromManifest) { + for (FileData fileFromManfiest : fileDataListFromManifest) { + translationContext.addManifestFile(fileFromManfiest.getFile(), fileFromManfiest.getType()); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java index 676eb7d7a9..69d0f186a6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java @@ -13,41 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class ConfigConstants { - //namespaces - public static final String MANDATORY_TRANSLATOR_NAMESPACE = "mandatoryHeatToToscaTranslator"; - public static final String MANDATORY_UNIFIED_MODEL_NAMESPACE = "mandatoryUnifiedModel"; - public static final String UNIFIED_MODEL_NAMESPACE = "unifiedModel"; - public static final String TRANSLATOR_NAMESPACE = "heatToToscaTranslator"; - public static final String MAPPING_NAMESPACE = "heatToToscaMapping"; - - //keys - public static final String RESOURCE_TRANSLATION_IMPL_KEY = "resourceTranslationImpl"; - public static final String NESTED_RESOURCE_TRANSLATION_IMPL_KEY = "NestedResource"; - public static final String DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY = "DefaultResource"; - public static final String FUNCTION_TRANSLATION_IMPL_KEY = "functionTranslationImpl"; - public static final String NAMING_CONVENTION_EXTRACTOR_IMPL_KEY = "namingConventionExtractImpl"; - public static final String UNIFIED_COMPOSITION_IMPL_KEY = "unifiedCompositionImpl"; - public static final String CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY = "ContrailComputeNodeTypeName"; - public static final String RESOURCE_MAPPING_KEY = "resourceMapping"; - public static final String SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY = - "supportedConsolidationComputeResources"; - public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = - "supportedConsolidationPortResources"; - public static final String ENRICH_PORT_RESOURCE_PROP = - "enrichPortResourceProperties"; - public static final String UNIFIED_MODEL_IMPL_KEY = "unifiedModelImpl"; - public static final String VFC_INSTANCE_GROUP_KEY = "vfcInstanceGroup"; - public static final String FULL_EXPOSED_PROPERTIES_KEY = - "unifiedModelImpl.vfcInstanceGroup.properties.exposedProperties"; - - //others - public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; + //namespaces + public static final String MANDATORY_TRANSLATOR_NAMESPACE = "mandatoryHeatToToscaTranslator"; + public static final String MANDATORY_UNIFIED_MODEL_NAMESPACE = "mandatoryUnifiedModel"; + public static final String UNIFIED_MODEL_NAMESPACE = "unifiedModel"; + public static final String TRANSLATOR_NAMESPACE = "heatToToscaTranslator"; + public static final String MAPPING_NAMESPACE = "heatToToscaMapping"; + //keys + public static final String RESOURCE_TRANSLATION_IMPL_KEY = "resourceTranslationImpl"; + public static final String NESTED_RESOURCE_TRANSLATION_IMPL_KEY = "NestedResource"; + public static final String DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY = "DefaultResource"; + public static final String FUNCTION_TRANSLATION_IMPL_KEY = "functionTranslationImpl"; + public static final String NAMING_CONVENTION_EXTRACTOR_IMPL_KEY = "namingConventionExtractImpl"; + public static final String UNIFIED_COMPOSITION_IMPL_KEY = "unifiedCompositionImpl"; + public static final String CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY = "ContrailComputeNodeTypeName"; + public static final String RESOURCE_MAPPING_KEY = "resourceMapping"; + public static final String SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY = "supportedConsolidationComputeResources"; + public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = "supportedConsolidationPortResources"; + public static final String ENRICH_PORT_RESOURCE_PROP = "enrichPortResourceProperties"; + public static final String UNIFIED_MODEL_IMPL_KEY = "unifiedModelImpl"; + public static final String VFC_INSTANCE_GROUP_KEY = "vfcInstanceGroup"; + public static final String FULL_EXPOSED_PROPERTIES_KEY = "unifiedModelImpl.vfcInstanceGroup.properties.exposedProperties"; + //others + public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; - private ConfigConstants() { - } + private ConfigConstants() { + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java index 0fb2eb8606..c5ec622756 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; +import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; + import java.util.List; import java.util.Map; import java.util.Optional; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; @@ -38,12 +38,10 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationDataHandler; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; - - /** - * Utility class for consolidation data collection helper methods. - */ - public class ConsolidationDataUtil { +/** + * Utility class for consolidation data collection helper methods. + */ +public class ConsolidationDataUtil { private static final String UNDERSCORE = "_"; private static final String DIGIT_REGEX = "\\d+"; @@ -52,11 +50,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. // prevent instantiation of utility class } - public static boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates( - String nestedNodeTemplateId, String nestedHeatFileName, TranslationContext context) { - return context.isServiceTemplateWithoutNodeTemplatesSection( - FileUtils.getFileWithoutExtention(nestedHeatFileName)) - || context.isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); + public static boolean isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(String nestedNodeTemplateId, String nestedHeatFileName, + TranslationContext context) { + return context.isServiceTemplateWithoutNodeTemplatesSection(FileUtils.getFileWithoutExtention(nestedHeatFileName)) || context + .isNodeTemplateIdPointsToStWithoutNodeTemplates(nestedNodeTemplateId); } /** @@ -67,15 +64,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param computeNodeTemplateId Node template id of the compute node * @param requirementAssignment RequirementAssignment object */ - public static void updateComputeConsolidationDataVolumes(TranslateTo translateTo, - String computeType, - String computeNodeTemplateId, - String requirementId, - RequirementAssignment requirementAssignment) { - ComputeConsolidationDataHandler handler = - translateTo.getContext().getComputeConsolidationDataHandler(); - handler.addVolumeToConsolidationData( - translateTo, computeType, computeNodeTemplateId, requirementId, requirementAssignment); + public static void updateComputeConsolidationDataVolumes(TranslateTo translateTo, String computeType, String computeNodeTemplateId, + String requirementId, RequirementAssignment requirementAssignment) { + ComputeConsolidationDataHandler handler = translateTo.getContext().getComputeConsolidationDataHandler(); + handler.addVolumeToConsolidationData(translateTo, computeType, computeNodeTemplateId, requirementId, requirementAssignment); } /** @@ -86,22 +78,17 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param portResourceId the port resource id * @param portNodeTemplateId the port node template id */ - public static void updatePortInConsolidationData(TranslateTo translateTo, - String computeNodeType, - String portResourceId, - String portResourceType, - String portNodeTemplateId) { + public static void updatePortInConsolidationData(TranslateTo translateTo, String computeNodeType, String portResourceId, String portResourceType, + String portNodeTemplateId) { TranslationContext translationContext = translateTo.getContext(); String computeNodeTemplateId = translateTo.getTranslatedId(); String portType = getPortType(portNodeTemplateId, DataModelUtil.getNamespaceSuffix(computeNodeType)); - - translationContext.getComputeConsolidationDataHandler().addPortToConsolidationData( - translateTo, computeNodeType, computeNodeTemplateId, portType, portNodeTemplateId); - + translationContext.getComputeConsolidationDataHandler() + .addPortToConsolidationData(translateTo, computeNodeType, computeNodeTemplateId, portType, portNodeTemplateId); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - translationContext.getPortConsolidationDataHandler().addConsolidationData( - serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); + translationContext.getPortConsolidationDataHandler() + .addConsolidationData(serviceTemplateFileName, portResourceId, portResourceType, portNodeTemplateId, portType); } /** @@ -112,31 +99,28 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param nodeTemplateId the source node template id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedData(TranslateTo translateTo, String targetResourceId, - Resource targetResource, Resource sourceResource, - String nodeTemplateId, String requirementId, - RequirementAssignment requirementAssignment) { + public static void updateNodesConnectedData(TranslateTo translateTo, String targetResourceId, Resource targetResource, Resource sourceResource, + String nodeTemplateId, String requirementId, RequirementAssignment requirementAssignment) { ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; consolidationEntityType.setEntityType(sourceResource, targetResource, translateTo.getContext()); // Add resource dependency information in nodesConnectedIn if the target node + // is a consolidation entity if (isConsolidationEntity(consolidationEntityType.getTargetEntityType())) { - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, - nodeTemplateId, consolidationEntityType.getTargetEntityType(), targetResourceId, - requirementId, requirementAssignment); + ConsolidationDataUtil + .updateNodesConnectedIn(translateTo, nodeTemplateId, consolidationEntityType.getTargetEntityType(), targetResourceId, requirementId, + requirementAssignment); } - //Add resource dependency information in nodesConnectedOut if the source node + //is a consolidation entity if (isConsolidationEntity(consolidationEntityType.getSourceEntityType())) { - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, - requirementAssignment.getNode(), consolidationEntityType.getSourceEntityType(), - requirementId, requirementAssignment); - + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, requirementAssignment.getNode(), consolidationEntityType.getSourceEntityType(), requirementId, + requirementAssignment); } } - private static boolean isConsolidationEntity(ConsolidationEntityType consolidationEntityType) { return ConsolidationEntityType.getSupportedConsolidationEntities().contains(consolidationEntityType); } @@ -150,21 +134,15 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedOut(TranslateTo translateTo, - String nodeTemplateId, - ConsolidationEntityType consolidationEntityType, - String requirementId, - RequirementAssignment requirementAssignment) { + public static void updateNodesConnectedOut(TranslateTo translateTo, String nodeTemplateId, ConsolidationEntityType consolidationEntityType, + String requirementId, RequirementAssignment requirementAssignment) { TranslationContext translationContext = translateTo.getContext(); - translationContext.updateRequirementAssignmentIdIndex( - ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getResourceId(), + translationContext + .updateRequirementAssignmentIdIndex(ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getResourceId(), requirementId); - - Optional consolidationDataHandler = - translationContext.getConsolidationDataHandler(consolidationEntityType); - consolidationDataHandler.ifPresent(handler -> handler.addNodesConnectedOut( - translateTo, nodeTemplateId, requirementId, requirementAssignment)); - + Optional consolidationDataHandler = translationContext.getConsolidationDataHandler(consolidationEntityType); + consolidationDataHandler + .ifPresent(handler -> handler.addNodesConnectedOut(translateTo, nodeTemplateId, requirementId, requirementAssignment)); } /** @@ -177,20 +155,13 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @param requirementId Requirement Id * @param requirementAssignment the requirement assignment */ - public static void updateNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, - ConsolidationEntityType consolidationEntityType, - String targetResourceId, - String requirementId, - RequirementAssignment requirementAssignment) { - + public static void updateNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, ConsolidationEntityType consolidationEntityType, + String targetResourceId, String requirementId, RequirementAssignment requirementAssignment) { TranslationContext translationContext = translateTo.getContext(); - Optional consolidationDataHandler = - translationContext.getConsolidationDataHandler(consolidationEntityType); + Optional consolidationDataHandler = translationContext.getConsolidationDataHandler(consolidationEntityType); String dependentNodeTemplateId = requirementAssignment.getNode(); - consolidationDataHandler.ifPresent( - handler -> handler.addNodesConnectedIn(translateTo, sourceNodeTemplateId, dependentNodeTemplateId, - targetResourceId, requirementId, requirementAssignment)); - + consolidationDataHandler.ifPresent(handler -> handler + .addNodesConnectedIn(translateTo, sourceNodeTemplateId, dependentNodeTemplateId, targetResourceId, requirementId, requirementAssignment)); } /** @@ -201,8 +172,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isComputeResource(Resource resource) { String resourceType = resource.getType(); - Map supportedComputeResources = - TranslationContext.getSupportedConsolidationComputeResources(); + Map supportedComputeResources = TranslationContext.getSupportedConsolidationComputeResources(); if (supportedComputeResources.containsKey(resourceType)) { return supportedComputeResources.get(resourceType).isEnable(); } @@ -217,8 +187,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isPortResource(Resource resource) { String resourceType = resource.getType(); - Map supportedPortResources = - TranslationContext.getSupportedConsolidationPortResources(); + Map supportedPortResources = TranslationContext.getSupportedConsolidationPortResources(); if (supportedPortResources.containsKey(resourceType)) { return supportedPortResources.get(resourceType).isEnable(); } @@ -233,9 +202,8 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. */ public static boolean isVolumeResource(Resource resource) { String resourceType = resource.getType(); - return resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) - || resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE - .getHeatResource()); + return resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) || resourceType + .equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE.getHeatResource()); } /** @@ -245,32 +213,26 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. * @return the port type */ public static String getPortType(String portNodeTemplateId, String vmType) { - if (StringUtils.isBlank(portNodeTemplateId) || !portNodeTemplateId.startsWith(vmType + UNDERSCORE)) { return portNodeTemplateId; } String temp = portNodeTemplateId.substring(portNodeTemplateId.indexOf(vmType) + vmType.length()); - StringBuilder sb = new StringBuilder(vmType + UNDERSCORE); String[] tokens = temp.split(UNDERSCORE); - if (tokens.length == 0) { return portNodeTemplateId; } - - for (int i=0; i consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(heatOrchestrationTemplate, context, - contrailSharedResourceId); - - consolidationDataHandler.ifPresent( - handler -> handler.removeParamNameFromAttrFuncList(serviceTemplate, heatOrchestrationTemplate, - paramName, contrailSharedResourceId, sharedTranslatedResourceId)); + public static void removeSharedResource(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String paramName, String contrailSharedResourceId, + String sharedTranslatedResourceId) { + Optional consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(heatOrchestrationTemplate, context, contrailSharedResourceId); + consolidationDataHandler.ifPresent(handler -> handler + .removeParamNameFromAttrFuncList(serviceTemplate, heatOrchestrationTemplate, paramName, contrailSharedResourceId, + sharedTranslatedResourceId)); } - public static void updateNodeGetAttributeIn(FunctionTranslator functionTranslator, String resourceTranslatedId, - String targetResourceId, String targetResourceTranslatedId, String attributeName) { - + public static void updateNodeGetAttributeIn(FunctionTranslator functionTranslator, String resourceTranslatedId, String targetResourceId, + String targetResourceTranslatedId, String attributeName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - Optional consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), targetResourceId); - - consolidationDataHandler.ifPresent(handler -> handler.addNodesGetAttrIn(functionTranslator, - resourceTranslatedId, targetResourceId, targetResourceTranslatedId, + Optional consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), targetResourceId); + consolidationDataHandler.ifPresent(handler -> handler + .addNodesGetAttrIn(functionTranslator, resourceTranslatedId, targetResourceId, targetResourceTranslatedId, getToscaPropertyName(functionTranslator), attributeName)); } - public static void updateNodeGetAttributeOut(FunctionTranslator functionTranslator, - String targetTranslatedResourceId, String resourceTranslatedId, String attrName) { - + public static void updateNodeGetAttributeOut(FunctionTranslator functionTranslator, String targetTranslatedResourceId, + String resourceTranslatedId, String attrName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - - Optional consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), functionTranslator.getResourceId()); - - consolidationDataHandler.ifPresent(handler -> handler.addNodesGetAttrOut(functionTranslator, - targetTranslatedResourceId, resourceTranslatedId, getToscaPropertyName(functionTranslator), attrName)); + Optional consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), + functionTranslator.getResourceId()); + consolidationDataHandler.ifPresent(handler -> handler + .addNodesGetAttrOut(functionTranslator, targetTranslatedResourceId, resourceTranslatedId, getToscaPropertyName(functionTranslator), + attrName)); } - public static void updateOutputParamGetAttrIn(FunctionTranslator functionTranslator, - String targetResourceId, String targetResourceTranslatedId, String propertyName, String attrName) { + public static void updateOutputParamGetAttrIn(FunctionTranslator functionTranslator, String targetResourceId, String targetResourceTranslatedId, + String propertyName, String attrName) { if (functionTranslator == null || functionTranslator.getServiceTemplate() == null) { return; } - - Optional consolidationDataHandler = - ConsolidationDataUtil.getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), - functionTranslator.getContext(), targetResourceId); - - consolidationDataHandler.ifPresent(handler -> handler.addOutputParamGetAttrIn(functionTranslator, - targetResourceId, targetResourceTranslatedId, propertyName, attrName)); + Optional consolidationDataHandler = ConsolidationDataUtil + .getConsolidationDataHandler(functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext(), targetResourceId); + consolidationDataHandler.ifPresent( + handler -> handler.addOutputParamGetAttrIn(functionTranslator, targetResourceId, targetResourceTranslatedId, propertyName, attrName)); } - private static Optional getConsolidationDataHandler( - HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, - String contrailSharedResourceId) { + private static Optional getConsolidationDataHandler(HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String contrailSharedResourceId) { Resource resource = heatOrchestrationTemplate.getResources().get(contrailSharedResourceId); ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; consolidationEntityType.setEntityType(resource, resource, context); @@ -363,8 +309,7 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. Resource resource = heatOrchestrationTemplate.getResources().get(functionTranslator.getResourceId()); String toscaPropertyName = functionTranslator.getPropertyName(); if (!HeatToToscaUtil.isNestedResource(resource)) { - return HeatToToscaUtil.getToscaPropertyName(functionTranslator.getContext(), - resource.getType(), getHeatPropertyName(toscaPropertyName)); + return HeatToToscaUtil.getToscaPropertyName(functionTranslator.getContext(), resource.getType(), getHeatPropertyName(toscaPropertyName)); } return toscaPropertyName; } @@ -376,12 +321,10 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. return toscaPropertyName; } - public static boolean isComputeReferenceToPortId(ComputeTemplateConsolidationData compute, - String portId) { + public static boolean isComputeReferenceToPortId(ComputeTemplateConsolidationData compute, String portId) { if (MapUtils.isEmpty(compute.getPorts())) { return false; } - for (List portIdsPerType : compute.getPorts().values()) { if (portIdsPerType.contains(portId)) { return true; @@ -389,5 +332,4 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants. } return false; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java index f124d0474e..2e3b8386ff 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isComputeResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isPortResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isVolumeResource; import java.util.Collections; import java.util.EnumSet; import java.util.Set; import java.util.stream.Collectors; - -import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.*; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; /** * The enum Entity type. @@ -32,12 +32,23 @@ import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDat public enum ConsolidationEntityType { COMPUTE, PORT, VOLUME, NESTED, //Simple nested VFC (nested file with one compute) or a complex VFC (nested ST with more than + //one compute) VFC_NESTED, SUB_INTERFACE, OTHER; - + private static final Set consolidationEntityTypes = initConsolidationEntities(); private ConsolidationEntityType sourceEntityType; private ConsolidationEntityType targetEntityType; + private static Set initConsolidationEntities() { + return Collections.unmodifiableSet(EnumSet.allOf(ConsolidationEntityType.class).stream().filter( + consolidationEntityType -> consolidationEntityType != ConsolidationEntityType.OTHER + && consolidationEntityType != ConsolidationEntityType.VOLUME).collect(Collectors.toSet())); + } + + public static Set getSupportedConsolidationEntities() { + return consolidationEntityTypes; + } + public ConsolidationEntityType getSourceEntityType() { return sourceEntityType; } @@ -46,7 +57,6 @@ public enum ConsolidationEntityType { return targetEntityType; } - /** * Sets entity type. * @@ -58,18 +68,6 @@ public enum ConsolidationEntityType { sourceEntityType = getEntityType(sourceResource, context); } - private static final Set consolidationEntityTypes = initConsolidationEntities(); - - private static Set initConsolidationEntities() { - return Collections.unmodifiableSet(EnumSet.allOf(ConsolidationEntityType.class).stream().filter( - consolidationEntityType -> consolidationEntityType != ConsolidationEntityType.OTHER - && consolidationEntityType != ConsolidationEntityType.VOLUME).collect(Collectors.toSet())); - } - - public static Set getSupportedConsolidationEntities() { - return consolidationEntityTypes; - } - private ConsolidationEntityType getEntityType(Resource resource, TranslationContext context) { ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; if (isComputeResource(resource)) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java index b99bcf8bb8..767bcd37e0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java @@ -13,13 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -33,7 +31,6 @@ import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; @@ -68,465 +65,325 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.DuplicateResourc public class ConsolidationService { - private UnifiedCompositionService unifiedCompositionService; - - public ConsolidationService(UnifiedCompositionService unifiedCompositionService) { - this.unifiedCompositionService = unifiedCompositionService; - } - - ConsolidationService() { - - } + private UnifiedCompositionService unifiedCompositionService; - void serviceTemplateConsolidation(ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - - ConsolidationData consolidationData = translationContext.getConsolidationData(); + public ConsolidationService(UnifiedCompositionService unifiedCompositionService) { + this.unifiedCompositionService = unifiedCompositionService; + } - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + ConsolidationService() { + } - if (Objects.isNull(fileComputeConsolidationData)) { - return; - } - for (TypeComputeConsolidationData typeComputeConsolidationData : - fileComputeConsolidationData.getAllTypeComputeConsolidationData()) { - boolean preConditionResult = - consolidationPreCondition( - serviceTemplate, consolidationData, typeComputeConsolidationData); - - List unifiedCompositionDataList = - createUnifiedCompositionDataList( - serviceTemplate, consolidationData, typeComputeConsolidationData); - - if (preConditionResult) { - boolean consolidationRuleCheckResult = - checkConsolidationRules(serviceTemplate, typeComputeConsolidationData, - consolidationData); - - unifiedCompositionService.createUnifiedComposition( - serviceTemplate, null, unifiedCompositionDataList, - consolidationRuleCheckResult ? UnifiedCompositionMode.ScalingInstances - : UnifiedCompositionMode.CatalogInstance, - translationContext); - } else { - unifiedCompositionService.createUnifiedComposition( - serviceTemplate, null, unifiedCompositionDataList, UnifiedCompositionMode - .SingleSubstitution, - translationContext); - } - } - - } - - static Map getConsolidationEntityIdToType(ServiceTemplate serviceTemplate, - ConsolidationData consolidationData) { - Map consolidationEntityIdToType = new HashMap<>(); - - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() + static Map getConsolidationEntityIdToType(ServiceTemplate serviceTemplate, ConsolidationData consolidationData) { + Map consolidationEntityIdToType = new HashMap<>(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() .getFileComputeConsolidationData(serviceTemplateFileName); - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() .getFilePortConsolidationData(serviceTemplateFileName); - if (Objects.nonNull(fileComputeConsolidationData)) { - for (String computeType : fileComputeConsolidationData.getAllComputeTypes()) { - TypeComputeConsolidationData typeComputeConsolidationData = - fileComputeConsolidationData.getTypeComputeConsolidationData(computeType); - Collection computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - for (String computeNodeTemplateId : computeNodeTemplateIds) { - consolidationEntityIdToType.put(computeNodeTemplateId, computeType); + if (Objects.nonNull(fileComputeConsolidationData)) { + for (String computeType : fileComputeConsolidationData.getAllComputeTypes()) { + TypeComputeConsolidationData typeComputeConsolidationData = fileComputeConsolidationData.getTypeComputeConsolidationData(computeType); + Collection computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + for (String computeNodeTemplateId : computeNodeTemplateIds) { + consolidationEntityIdToType.put(computeNodeTemplateId, computeType); + } + } + } + if (Objects.nonNull(filePortConsolidationData)) { + Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + for (String portNodeTemplateId : portNodeTemplateIds) { + consolidationEntityIdToType + .put(portNodeTemplateId, filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId).getPortType()); + } } - } + return consolidationEntityIdToType; } - if (Objects.nonNull(filePortConsolidationData)) { - Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); - for (String portNodeTemplateId : portNodeTemplateIds) { - consolidationEntityIdToType - .put(portNodeTemplateId, - filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId).getPortType()); - } + void serviceTemplateConsolidation(ServiceTemplate serviceTemplate, TranslationContext translationContext) { + ConsolidationData consolidationData = translationContext.getConsolidationData(); + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.isNull(fileComputeConsolidationData)) { + return; + } + for (TypeComputeConsolidationData typeComputeConsolidationData : fileComputeConsolidationData.getAllTypeComputeConsolidationData()) { + boolean preConditionResult = consolidationPreCondition(serviceTemplate, consolidationData, typeComputeConsolidationData); + List unifiedCompositionDataList = createUnifiedCompositionDataList(serviceTemplate, consolidationData, + typeComputeConsolidationData); + if (preConditionResult) { + boolean consolidationRuleCheckResult = checkConsolidationRules(serviceTemplate, typeComputeConsolidationData, consolidationData); + unifiedCompositionService.createUnifiedComposition(serviceTemplate, null, unifiedCompositionDataList, + consolidationRuleCheckResult ? UnifiedCompositionMode.ScalingInstances : UnifiedCompositionMode.CatalogInstance, + translationContext); + } else { + unifiedCompositionService + .createUnifiedComposition(serviceTemplate, null, unifiedCompositionDataList, UnifiedCompositionMode.SingleSubstitution, + translationContext); + } + } } - return consolidationEntityIdToType; - } - - - private boolean checkConsolidationRules(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return checkComputeConsolidation(serviceTemplate, typeComputeConsolidationData) - && checkPortConsolidation(serviceTemplate, typeComputeConsolidationData, - consolidationData) - && !checkGetAttrBetweenEntityConsolidationOfTheSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData); - } + private boolean checkConsolidationRules(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return checkComputeConsolidation(serviceTemplate, typeComputeConsolidationData) && checkPortConsolidation(serviceTemplate, + typeComputeConsolidationData, consolidationData) && !checkGetAttrBetweenEntityConsolidationOfTheSameType(serviceTemplate, + typeComputeConsolidationData, consolidationData); + } - private boolean checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { + private boolean checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { Collection computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - - Map> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - - return typeComputeConsolidationData.isGetAttrOutFromEntityLegal(portTypeToIds) - && checkGetAttrOutFromPortLegal( - ToscaUtil.getServiceTemplateFileName(serviceTemplate), - computeNodeTemplateIds, portTypeToIds, consolidationData); - + Map> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + return typeComputeConsolidationData.isGetAttrOutFromEntityLegal(portTypeToIds) && checkGetAttrOutFromPortLegal( + ToscaUtil.getServiceTemplateFileName(serviceTemplate), computeNodeTemplateIds, portTypeToIds, consolidationData); + } + + private boolean checkGetAttrOutFromPortLegal(String serviceTemplateName, Collection computeNodeTemplateIds, + Map> portTypeToIds, ConsolidationData consolidationData) { + for (List portIdsFromSameType : portTypeToIds.values()) { + List portTemplateConsolidationDataList = collectAllPortsTemplateConsolidationData(portIdsFromSameType, + serviceTemplateName, consolidationData); + if (!(checkGetAttrOutFromEntityToPortIsLegal(portTemplateConsolidationDataList, portTypeToIds) + && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(portTemplateConsolidationDataList, computeNodeTemplateIds))) { + return false; + } + } + return true; } - private boolean checkGetAttrOutFromPortLegal(String serviceTemplateName, - Collection computeNodeTemplateIds, - Map> portTypeToIds, - ConsolidationData consolidationData) { - for (List portIdsFromSameType : portTypeToIds.values()) { - List portTemplateConsolidationDataList = - collectAllPortsTemplateConsolidationData(portIdsFromSameType, serviceTemplateName, - consolidationData); - - if (!(checkGetAttrOutFromEntityToPortIsLegal(portTemplateConsolidationDataList, portTypeToIds) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - portTemplateConsolidationDataList, - computeNodeTemplateIds))) { - return false; - } + private boolean checkGetAttrOutFromEntityToPortIsLegal(Collection entities, + Map> portTypeToIds) { + return CollectionUtils.isEmpty(entities) || entities.iterator().next().isGetAttrOutFromEntityLegal(entities, portTypeToIds); } - return true; - } - - private boolean checkGetAttrOutFromEntityToPortIsLegal(Collection entities, - Map> portTypeToIds) { - return CollectionUtils.isEmpty(entities) - || entities.iterator().next().isGetAttrOutFromEntityLegal(entities, portTypeToIds); - } - - private boolean checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - List entityConsolidationDataList, - Collection consolidationEntityNodeTemplateIds) { - if (CollectionUtils.isEmpty(entityConsolidationDataList)) { - return true; - } - EntityConsolidationData startingEntityTemplate = - (EntityConsolidationData) entityConsolidationDataList.get(0); - Map> startingGetAttrOutFuncData = - getConsolidationEntityGetAttrOutFuncData(startingEntityTemplate.getNodesGetAttrOut(), - consolidationEntityNodeTemplateIds); - - for (int i = 1; i < entityConsolidationDataList.size(); i++) { - EntityConsolidationData currentEntityTemplate = - (EntityConsolidationData) entityConsolidationDataList.get(i); - Map> currentGetAttrOutFuncData = - getConsolidationEntityGetAttrOutFuncData(currentEntityTemplate.getNodesGetAttrOut(), - consolidationEntityNodeTemplateIds); - - if (!isGetAttrRelationToEntitySimilarBetweenEntities(startingGetAttrOutFuncData, - currentGetAttrOutFuncData)) { - return false; - } + private boolean checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(List entityConsolidationDataList, + Collection consolidationEntityNodeTemplateIds) { + if (CollectionUtils.isEmpty(entityConsolidationDataList)) { + return true; + } + EntityConsolidationData startingEntityTemplate = (EntityConsolidationData) entityConsolidationDataList.get(0); + Map> startingGetAttrOutFuncData = getConsolidationEntityGetAttrOutFuncData( + startingEntityTemplate.getNodesGetAttrOut(), consolidationEntityNodeTemplateIds); + for (int i = 1; i < entityConsolidationDataList.size(); i++) { + EntityConsolidationData currentEntityTemplate = (EntityConsolidationData) entityConsolidationDataList.get(i); + Map> currentGetAttrOutFuncData = getConsolidationEntityGetAttrOutFuncData( + currentEntityTemplate.getNodesGetAttrOut(), consolidationEntityNodeTemplateIds); + if (!isGetAttrRelationToEntitySimilarBetweenEntities(startingGetAttrOutFuncData, currentGetAttrOutFuncData)) { + return false; + } + } + return true; } - return true; - } + private boolean isGetAttrRelationToEntitySimilarBetweenEntities(Map> firstMap, + Map> secondMap) { + if (MapUtils.isEmpty(firstMap) != MapUtils.isEmpty(secondMap)) { + return false; + } + return (MapUtils.isEmpty(firstMap) && MapUtils.isEmpty(secondMap)) || (new ArrayList<>(firstMap.values()) + .equals(new ArrayList<>(secondMap.values()))); + } - private boolean isGetAttrRelationToEntitySimilarBetweenEntities( - Map> firstMap, - Map> secondMap) { - if (MapUtils.isEmpty(firstMap) != MapUtils.isEmpty(secondMap)) { - return false; + private boolean checkSubInterfaceConsolidationPreCondition(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.isNull(filePortConsolidationData)) { + return true; + } + Map> portTypeToPortIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + Collection computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + for (List portIdsFromSameType : portTypeToPortIds.values()) { + List portTemplateConsolidationDataList = getAllPortTemplateConsolidationData(portIdsFromSameType, + filePortConsolidationData); + if (!areSubInterfacePreConditionRulesValid(portTypeToPortIds, computeNodeTemplateIds, portTemplateConsolidationDataList, + portTemplateConsolidationDataList.get(0))) { + return false; + } + } + return true; } - return (MapUtils.isEmpty(firstMap) && MapUtils.isEmpty(secondMap)) || - (new ArrayList<>(firstMap.values()).equals(new ArrayList<>(secondMap.values()))); + private boolean areSubInterfacePreConditionRulesValid(Map> portTypeToPortIds, Collection computeNodeTemplateIds, + List portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return areSubInterfaceTypesSimilarBetweenPorts(portTemplateConsolidationDataList, subInterfaceConsolidationData) + && isNumberOfSubInterfacesPerTypeSimilar(portTemplateConsolidationDataList, subInterfaceConsolidationData) + && isGetAttrFromSubInterfaceToOtherEntitiesLegal(computeNodeTemplateIds, portTypeToPortIds, portTemplateConsolidationDataList); + } - } + private boolean isGetAttrFromSubInterfaceToOtherEntitiesLegal(Collection computeNodeTemplateIds, + Map> portTypeToPortIds, + List portTemplateConsolidationDataList) { + ListMultimap subInterfacesFromSameTypeFromPorts = collectAllSubInterfacesFromSameTypeFromPorts( + portTemplateConsolidationDataList); + List subInterfaceList = new ArrayList<>(subInterfacesFromSameTypeFromPorts.values()); + return areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid(computeNodeTemplateIds, portTypeToPortIds, + portTemplateConsolidationDataList, subInterfaceList); + } - private boolean checkSubInterfaceConsolidationPreCondition(ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + private boolean areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid(Collection computeNodeTemplateIds, + Map> portTypeToPortIds, + List portTemplateConsolidationDataList, + List subInterfaceList) { + return checkGetAttrOutFromEntityToPortIsLegal(subInterfaceList, portTypeToPortIds) + && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal(portTemplateConsolidationDataList, + getSubInterfaceIdsFromSameType(subInterfaceList)) && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( + subInterfaceList, computeNodeTemplateIds); + } - if (Objects.isNull(filePortConsolidationData)) { - return true; + private boolean areSubInterfaceTypesSimilarBetweenPorts(List portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return portTemplateConsolidationDataList.stream().allMatch(element -> element.hasSameSubInterfaceTypes(subInterfaceConsolidationData)); } - Map> portTypeToPortIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + private boolean isNumberOfSubInterfacesPerTypeSimilar(List portTemplateConsolidationDataList, + PortTemplateConsolidationData subInterfaceConsolidationData) { + return portTemplateConsolidationDataList.stream() + .allMatch(element -> element.isNumberOfSubInterfacesPerTypeSimilar(subInterfaceConsolidationData)); + } - Collection computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + private Map> getConsolidationEntityGetAttrOutFuncData(Map> nodesGetAttrOut, + Collection computeNodeTemplateIds) { + Map> computeGetAttrFuncData = new HashMap<>(); + if (MapUtils.isEmpty(nodesGetAttrOut)) { + return computeGetAttrFuncData; + } + for (Map.Entry> getAttrFuncEntry : nodesGetAttrOut.entrySet()) { + if (computeNodeTemplateIds.contains(getAttrFuncEntry.getKey())) { + computeGetAttrFuncData.put(getAttrFuncEntry.getKey(), new HashSet<>(getAttrFuncEntry.getValue())); + } + } + return computeGetAttrFuncData; + } - for (List portIdsFromSameType : portTypeToPortIds.values()) { - List portTemplateConsolidationDataList = - getAllPortTemplateConsolidationData(portIdsFromSameType, filePortConsolidationData); + private boolean checkGetAttrBetweenEntityConsolidationOfTheSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return areThereGetAttrRelationsBetweenComputesOfSameType(typeComputeConsolidationData) || areThereGetAttrRelationsBetweenPortsOfTheSameType( + serviceTemplate, typeComputeConsolidationData, consolidationData); + } - if (!areSubInterfacePreConditionRulesValid(portTypeToPortIds, computeNodeTemplateIds, - portTemplateConsolidationDataList, portTemplateConsolidationDataList.get(0))) { - return false; - } - } - return true; - } - - private boolean areSubInterfacePreConditionRulesValid(Map> portTypeToPortIds, - Collection computeNodeTemplateIds, - List portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - return areSubInterfaceTypesSimilarBetweenPorts(portTemplateConsolidationDataList, - subInterfaceConsolidationData) - && isNumberOfSubInterfacesPerTypeSimilar(portTemplateConsolidationDataList, - subInterfaceConsolidationData) - && isGetAttrFromSubInterfaceToOtherEntitiesLegal(computeNodeTemplateIds, - portTypeToPortIds, portTemplateConsolidationDataList); - } - - private boolean isGetAttrFromSubInterfaceToOtherEntitiesLegal( - Collection computeNodeTemplateIds, - Map> portTypeToPortIds, - List portTemplateConsolidationDataList) { - - ListMultimap subInterfacesFromSameTypeFromPorts = - collectAllSubInterfacesFromSameTypeFromPorts(portTemplateConsolidationDataList); - - List subInterfaceList = new ArrayList<>(subInterfacesFromSameTypeFromPorts - .values()); - return areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid( - computeNodeTemplateIds, portTypeToPortIds, portTemplateConsolidationDataList, subInterfaceList); - } - - private boolean areGetAttrRelationshipsBetweenSubInterfaceToConsolidationEntitiesValid( - Collection computeNodeTemplateIds, Map> portTypeToPortIds, - List portTemplateConsolidationDataList, - List subInterfaceList) { - return checkGetAttrOutFromEntityToPortIsLegal(subInterfaceList, portTypeToPortIds) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - portTemplateConsolidationDataList, getSubInterfaceIdsFromSameType(subInterfaceList)) - && checkGetAttrOutFromConsolidationEntityToEntityNotFromSameTypeIsLegal( - subInterfaceList, computeNodeTemplateIds); - } - - private boolean areSubInterfaceTypesSimilarBetweenPorts( - List portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - - return portTemplateConsolidationDataList.stream().allMatch( - element -> element.hasSameSubInterfaceTypes(subInterfaceConsolidationData)); - } - - private boolean isNumberOfSubInterfacesPerTypeSimilar( - List portTemplateConsolidationDataList, - PortTemplateConsolidationData subInterfaceConsolidationData) { - - return portTemplateConsolidationDataList.stream() - .allMatch(element -> element.isNumberOfSubInterfacesPerTypeSimilar(subInterfaceConsolidationData)); - } - - private Map> getConsolidationEntityGetAttrOutFuncData( - Map> nodesGetAttrOut, - Collection computeNodeTemplateIds) { - Map> computeGetAttrFuncData = new HashMap<>(); - - if (MapUtils.isEmpty(nodesGetAttrOut)) { - return computeGetAttrFuncData; - } - - for (Map.Entry> getAttrFuncEntry : nodesGetAttrOut.entrySet()) { - if (computeNodeTemplateIds.contains(getAttrFuncEntry.getKey())) { - computeGetAttrFuncData.put(getAttrFuncEntry.getKey(), new HashSet<>(getAttrFuncEntry - .getValue())); - } - } - - return computeGetAttrFuncData; - } - - private boolean checkGetAttrBetweenEntityConsolidationOfTheSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return areThereGetAttrRelationsBetweenComputesOfSameType(typeComputeConsolidationData) - || areThereGetAttrRelationsBetweenPortsOfTheSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData); - - } - - private boolean areThereGetAttrRelationsBetweenComputesOfSameType( - TypeComputeConsolidationData typeComputeConsolidationData) { - - Collection computeTemplateConsolidationEntities = - typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); - Collection computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - - return checkGetAttrRelationsForEntityConsolidationData( - computeTemplateConsolidationEntities, computeNodeTemplateIds, - EntityConsolidationData::getNodesGetAttrIn); - } - - private boolean areThereGetAttrRelationsBetweenPortsOfTheSameType( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - Map> portTypeToPortIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData().getFilePortConsolidationData( - ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + private boolean areThereGetAttrRelationsBetweenComputesOfSameType(TypeComputeConsolidationData typeComputeConsolidationData) { + Collection computeTemplateConsolidationEntities = typeComputeConsolidationData + .getAllComputeTemplateConsolidationData(); + Collection computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + return checkGetAttrRelationsForEntityConsolidationData(computeTemplateConsolidationEntities, computeNodeTemplateIds, + EntityConsolidationData::getNodesGetAttrIn); + } + private boolean areThereGetAttrRelationsBetweenPortsOfTheSameType(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + Map> portTypeToPortIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); for (List portsOfTheSameTypeIds : portTypeToPortIds.values()) { - List portTemplateConsolidationDataOfSameType = - getAllPortTemplateConsolidationData(portsOfTheSameTypeIds, filePortConsolidationData); - if (!checkGetAttrRelationsForEntityConsolidationData(portTemplateConsolidationDataOfSameType, - portsOfTheSameTypeIds, EntityConsolidationData::getNodesGetAttrIn)) { + List portTemplateConsolidationDataOfSameType = getAllPortTemplateConsolidationData(portsOfTheSameTypeIds, + filePortConsolidationData); + if (!checkGetAttrRelationsForEntityConsolidationData(portTemplateConsolidationDataOfSameType, portsOfTheSameTypeIds, + EntityConsolidationData::getNodesGetAttrIn)) { return false; } } - return true; } - private boolean areThereGetAttrRelationsBetweenSubInterfacesOfSameType( - List subInterfacesIdsFromSameType, - List subInterfaceList) { - - return checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, - subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrIn) - || checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, - subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrOut); + private boolean areThereGetAttrRelationsBetweenSubInterfacesOfSameType(List subInterfacesIdsFromSameType, + List subInterfaceList) { + return checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, subInterfacesIdsFromSameType, + EntityConsolidationData::getNodesGetAttrIn) || checkGetAttrRelationsForEntityConsolidationData(subInterfaceList, + subInterfacesIdsFromSameType, EntityConsolidationData::getNodesGetAttrOut); + } - } + private List getAllPortTemplateConsolidationData(List portsIds, + FilePortConsolidationData filePortConsolidationData) { + List portTemplateConsolidationDataOfSameType = new ArrayList<>(); + for (String portId : portsIds) { + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataOfSameType.add(portTemplateConsolidationData); + } + } + return portTemplateConsolidationDataOfSameType; + } - private List getAllPortTemplateConsolidationData( - List portsIds, - FilePortConsolidationData filePortConsolidationData) { - List portTemplateConsolidationDataOfSameType = new ArrayList<>(); + private boolean checkGetAttrRelationsForEntityConsolidationData(Collection entities, Collection nodeTemplateIdsOfTheSameType, + Function>> getAttrValuesMethod) { + for (Object entity : entities) { + Map> getAttrValue = getAttrValuesMethod.apply((EntityConsolidationData) entity); + Set getAttrNodeIds = getAttrValue == null ? new HashSet<>() : getAttrValue.keySet(); + if (getAttrNodeIds.stream().anyMatch(nodeTemplateIdsOfTheSameType::contains)) { + return true; + } + } + return false; + } - for (String portId : portsIds) { - PortTemplateConsolidationData portTemplateConsolidationData = - filePortConsolidationData.getPortTemplateConsolidationData(portId); - if (Objects.nonNull(portTemplateConsolidationData)) { - portTemplateConsolidationDataOfSameType.add(portTemplateConsolidationData); - } + private boolean checkComputeConsolidation(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData) { + Collection computeNodeTemplateIds = typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + List propertiesWithIdenticalVal = getComputePropertiesWithIdenticalVal(); + return arePropertiesSimilarBetweenComputeNodeTemplates(serviceTemplate, computeNodeTemplateIds, propertiesWithIdenticalVal) + && checkComputeRelations(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); } - return portTemplateConsolidationDataOfSameType; - } + private boolean checkComputeRelations(Collection computeTemplateConsolidationEntities) { + return checkEntityConsolidationDataRelations(computeTemplateConsolidationEntities) && checkComputesRelationsToVolume( + computeTemplateConsolidationEntities); + } - private boolean checkGetAttrRelationsForEntityConsolidationData(Collection entities, - Collection nodeTemplateIdsOfTheSameType, - Function>> getAttrValuesMethod) { - for (Object entity : entities) { - Map> getAttrValue = - getAttrValuesMethod.apply((EntityConsolidationData) entity); - Set getAttrNodeIds = - getAttrValue == null ? new HashSet<>() - : getAttrValue.keySet(); - if (getAttrNodeIds.stream().anyMatch(nodeTemplateIdsOfTheSameType::contains)) { + private boolean checkEntityConsolidationDataRelations(Collection entities) { + EntityConsolidationData startingEntity = (EntityConsolidationData) entities.iterator().next(); + for (Object entity : entities) { + EntityConsolidationData currentEntity = (EntityConsolidationData) entity; + if (!(checkNodesConnectedInRelations(startingEntity, currentEntity) && (checkNodesConnectedOutRelations(startingEntity, currentEntity)) + && (checkGroupIdsRelations(startingEntity, currentEntity)))) { + return false; + } + } return true; - } } - return false; - } - - - private boolean checkComputeConsolidation( - ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData) { - Collection computeNodeTemplateIds = - typeComputeConsolidationData.getAllComputeNodeTemplateIds(); - List propertiesWithIdenticalVal = getComputePropertiesWithIdenticalVal(); - - return arePropertiesSimilarBetweenComputeNodeTemplates(serviceTemplate, computeNodeTemplateIds, - propertiesWithIdenticalVal) - && checkComputeRelations( - typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); - } - - private boolean checkComputeRelations( - Collection computeTemplateConsolidationEntities) { - - return checkEntityConsolidationDataRelations(computeTemplateConsolidationEntities) - && checkComputesRelationsToVolume(computeTemplateConsolidationEntities); - } - - private boolean checkEntityConsolidationDataRelations(Collection entities) { - EntityConsolidationData startingEntity = (EntityConsolidationData) entities.iterator().next(); - - for (Object entity : entities) { - EntityConsolidationData currentEntity = (EntityConsolidationData) entity; - if (!(checkNodesConnectedInRelations(startingEntity, currentEntity) - && (checkNodesConnectedOutRelations(startingEntity, currentEntity)) - && (checkGroupIdsRelations(startingEntity, currentEntity)))) { - return false; - } + private boolean checkNodesConnectedInRelations(EntityConsolidationData firstEntity, EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedIn(), secondEntity.getNodesConnectedIn()); } - return true; - } - - private boolean checkNodesConnectedInRelations(EntityConsolidationData firstEntity, - EntityConsolidationData secondEntity) { - return compareNodeConnectivity(firstEntity.getNodesConnectedIn(), - secondEntity.getNodesConnectedIn()); - } - private boolean checkNodesConnectedOutRelations(EntityConsolidationData firstEntity, - EntityConsolidationData secondEntity) { - return compareNodeConnectivity(firstEntity.getNodesConnectedOut(), - secondEntity.getNodesConnectedOut()); - } - - private boolean compareNodeConnectivity( - Multimap firstEntityMap, - Multimap secondEntityMap) { + private boolean checkNodesConnectedOutRelations(EntityConsolidationData firstEntity, EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedOut(), secondEntity.getNodesConnectedOut()); + } + private boolean compareNodeConnectivity(Multimap firstEntityMap, + Multimap secondEntityMap) { if (CommonUtil.isMultimapEmpty(firstEntityMap) && CommonUtil.isMultimapEmpty(secondEntityMap)) { return true; } - return !CommonUtil.isMultimapEmpty(firstEntityMap) && !CommonUtil.isMultimapEmpty(secondEntityMap) - && equalsIgnoreSuffix(new HashSet<>(firstEntityMap.keySet()),new HashSet<>(secondEntityMap.keySet())); + return !CommonUtil.isMultimapEmpty(firstEntityMap) && !CommonUtil.isMultimapEmpty(secondEntityMap) && equalsIgnoreSuffix( + new HashSet<>(firstEntityMap.keySet()), new HashSet<>(secondEntityMap.keySet())); } - private boolean equalsIgnoreSuffix(Set firstKeySet, Set secondKeySet){ - Set firstKeySetTrimmed = firstKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); - Set secondKeySetTrimmed = secondKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); - return firstKeySetTrimmed.equals(secondKeySetTrimmed); + private boolean equalsIgnoreSuffix(Set firstKeySet, Set secondKeySet) { + Set firstKeySetTrimmed = firstKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); + Set secondKeySetTrimmed = secondKeySet.stream().map(this::trimSuffix).collect(Collectors.toSet()); + return firstKeySetTrimmed.equals(secondKeySetTrimmed); } - private String trimSuffix(String volumeName){ - int suffixPosition = volumeName.lastIndexOf("_"); - return volumeName.substring(0, suffixPosition); + private String trimSuffix(String volumeName) { + int suffixPosition = volumeName.lastIndexOf("_"); + return volumeName.substring(0, suffixPosition); } - private boolean checkGroupIdsRelations(EntityConsolidationData startingEntity, - EntityConsolidationData currentEntity) { - return CollectionUtils.isEmpty(startingEntity.getGroupIds()) - && CollectionUtils.isEmpty(currentEntity.getGroupIds()) - || startingEntity.getGroupIds().equals(currentEntity.getGroupIds()); - - } - - private boolean checkComputesRelationsToVolume( - Collection computeTemplateConsolidationEntities) { - Iterator iterator = - computeTemplateConsolidationEntities.iterator(); - - Multimap startingVolumes = - iterator.next().getVolumes(); + private boolean checkGroupIdsRelations(EntityConsolidationData startingEntity, EntityConsolidationData currentEntity) { + return CollectionUtils.isEmpty(startingEntity.getGroupIds()) && CollectionUtils.isEmpty(currentEntity.getGroupIds()) || startingEntity + .getGroupIds().equals(currentEntity.getGroupIds()); + } + private boolean checkComputesRelationsToVolume(Collection computeTemplateConsolidationEntities) { + Iterator iterator = computeTemplateConsolidationEntities.iterator(); + Multimap startingVolumes = iterator.next().getVolumes(); for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationEntities) { - Multimap currentVolumes = - compute.getVolumes(); + Multimap currentVolumes = compute.getVolumes(); if (!compareNodeConnectivity(startingVolumes, currentVolumes)) { return false; } @@ -534,502 +391,357 @@ public class ConsolidationService { return true; } + private boolean checkPortConsolidation(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return validateWantedPortProperties(serviceTemplate, typeComputeConsolidationData) && checkPortRelations( + ToscaUtil.getServiceTemplateFileName(serviceTemplate), typeComputeConsolidationData, consolidationData); + } - private boolean checkPortConsolidation(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - return validateWantedPortProperties(serviceTemplate, - typeComputeConsolidationData) - && checkPortRelations(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - typeComputeConsolidationData, consolidationData); - } - - - private boolean validateWantedPortProperties(ServiceTemplate serviceTemplate, - TypeComputeConsolidationData typeComputeConsolidationData) { - Map> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); - + private boolean validateWantedPortProperties(ServiceTemplate serviceTemplate, TypeComputeConsolidationData typeComputeConsolidationData) { + Map> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); List propertiesWithIdenticalVal = getPortPropertiesWithIdenticalVal(); List propertiesThatNeedToHaveSameUsage = getPortPropertiesThatNeedToHaveSameUsage(); - for (List portsIds : portTypeToIds.values()) { - if (!arePortPropertiesValid( - serviceTemplate, propertiesWithIdenticalVal, propertiesThatNeedToHaveSameUsage, portsIds)) { + if (!arePortPropertiesValid(serviceTemplate, propertiesWithIdenticalVal, propertiesThatNeedToHaveSameUsage, portsIds)) { return false; } } - return true; } - private boolean arePortPropertiesValid(ServiceTemplate serviceTemplate, - List propertiesWithIdenticalVal, - List propertiesThatNeedToHaveSameUsage, - List portsIds) { - Map nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - - Predicate similar = property -> - isPropertyValueSimilarBetweenNodeTemplates(property, - portsIds, nodeTemplates); - - Predicate exists = property -> - isPropertyUsageSimilarBetweenAllNodeTemplates(property, - portsIds, nodeTemplates); - - return areWantedPortPropertiesValid( - propertiesWithIdenticalVal, similar) - && areWantedPortPropertiesValid( - propertiesThatNeedToHaveSameUsage, exists); - } - - private boolean checkPortRelations(String serviceTemplateName, - TypeComputeConsolidationData typeComputeConsolidationData, - ConsolidationData consolidationData) { - Map> portTypeToIds = - typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); + private boolean arePortPropertiesValid(ServiceTemplate serviceTemplate, List propertiesWithIdenticalVal, + List propertiesThatNeedToHaveSameUsage, List portsIds) { + Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + Predicate similar = property -> isPropertyValueSimilarBetweenNodeTemplates(property, portsIds, nodeTemplates); + Predicate exists = property -> isPropertyUsageSimilarBetweenAllNodeTemplates(property, portsIds, nodeTemplates); + return areWantedPortPropertiesValid(propertiesWithIdenticalVal, similar) && areWantedPortPropertiesValid(propertiesThatNeedToHaveSameUsage, + exists); + } + private boolean checkPortRelations(String serviceTemplateName, TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + Map> portTypeToIds = typeComputeConsolidationData.collectAllPortsOfEachTypeFromComputes(); for (List portIds : portTypeToIds.values()) { - List portTemplateConsolidationDataList = - collectAllPortsTemplateConsolidationData(portIds, serviceTemplateName, consolidationData); - + List portTemplateConsolidationDataList = collectAllPortsTemplateConsolidationData(portIds, + serviceTemplateName, consolidationData); if (!checkEntityConsolidationDataRelations(portTemplateConsolidationDataList) || !checkSubInterfaceRules( - portTemplateConsolidationDataList)) { + portTemplateConsolidationDataList)) { return false; } } - return true; } - private boolean checkSubInterfaceRules(List - portTemplateConsolidationDataList) { - ListMultimap subInterfaceTypeToEntity = - collectAllSubInterfacesFromSameTypeFromPorts(portTemplateConsolidationDataList); - List subInterfaceList = new ArrayList<>(subInterfaceTypeToEntity.values()); - return areSubInterfacePropertiesAndRelationsValid(subInterfaceList); - } - - private boolean areSubInterfacePropertiesAndRelationsValid( - List subInterfaceList) { - return isResourceGroupPropertiesSimilarBetweenSubPorts(subInterfaceList) - && checkSubInterfaceRelations(subInterfaceList) - && !areThereGetAttrRelationsBetweenSubInterfacesOfSameType( - getSubInterfaceIdsFromSameType(subInterfaceList), subInterfaceList); - } - - private boolean checkSubInterfaceRelations(List - subInterfaceList) { - return CollectionUtils.isEmpty(subInterfaceList) - || checkEntityConsolidationDataRelations(subInterfaceList); - } - - private boolean isResourceGroupPropertiesSimilarBetweenSubPorts( - List subInterfaceList) { - if (CollectionUtils.isEmpty(subInterfaceList)) { - return true; - } - - SubInterfaceTemplateConsolidationData startingSubInterface = subInterfaceList.get(0); - for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceList) { - if (!startingSubInterface.getResourceGroupCount().equals(subInterface.getResourceGroupCount()) - || !StringUtils.equals(startingSubInterface.getNetworkRole(), subInterface.getNetworkRole())) { - return false; - } + private boolean checkSubInterfaceRules(List portTemplateConsolidationDataList) { + ListMultimap subInterfaceTypeToEntity = collectAllSubInterfacesFromSameTypeFromPorts( + portTemplateConsolidationDataList); + List subInterfaceList = new ArrayList<>(subInterfaceTypeToEntity.values()); + return areSubInterfacePropertiesAndRelationsValid(subInterfaceList); } - return true; - } - - private List getSubInterfaceIdsFromSameType(List - subInterfaceList) { - if (CollectionUtils.isEmpty(subInterfaceList)) { - return new ArrayList<>(); + private boolean areSubInterfacePropertiesAndRelationsValid(List subInterfaceList) { + return isResourceGroupPropertiesSimilarBetweenSubPorts(subInterfaceList) && checkSubInterfaceRelations(subInterfaceList) + && !areThereGetAttrRelationsBetweenSubInterfacesOfSameType(getSubInterfaceIdsFromSameType(subInterfaceList), subInterfaceList); } - return subInterfaceList.stream().map(SubInterfaceTemplateConsolidationData::getNodeTemplateId) - .collect(Collectors.toList()); - } + private boolean checkSubInterfaceRelations(List subInterfaceList) { + return CollectionUtils.isEmpty(subInterfaceList) || checkEntityConsolidationDataRelations(subInterfaceList); + } - private ListMultimap collectAllSubInterfacesFromSameTypeFromPorts( - List portTemplateConsolidationDataList) { - ListMultimap subInterfaceTypeToEntity = ArrayListMultimap.create(); - for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { - portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + private boolean isResourceGroupPropertiesSimilarBetweenSubPorts(List subInterfaceList) { + if (CollectionUtils.isEmpty(subInterfaceList)) { + return true; + } + SubInterfaceTemplateConsolidationData startingSubInterface = subInterfaceList.get(0); + for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceList) { + if (!startingSubInterface.getResourceGroupCount().equals(subInterface.getResourceGroupCount()) || !StringUtils + .equals(startingSubInterface.getNetworkRole(), subInterface.getNetworkRole())) { + return false; + } + } + return true; } - return subInterfaceTypeToEntity; - } + private List getSubInterfaceIdsFromSameType(List subInterfaceList) { + if (CollectionUtils.isEmpty(subInterfaceList)) { + return new ArrayList<>(); + } + return subInterfaceList.stream().map(SubInterfaceTemplateConsolidationData::getNodeTemplateId).collect(Collectors.toList()); + } - private List collectAllPortsTemplateConsolidationData(List portIds, - String serviceTemplateName, - ConsolidationData consolidationData) { + private ListMultimap collectAllSubInterfacesFromSameTypeFromPorts( + List portTemplateConsolidationDataList) { + ListMultimap subInterfaceTypeToEntity = ArrayListMultimap.create(); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + } + return subInterfaceTypeToEntity; + } - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData() + private List collectAllPortsTemplateConsolidationData(List portIds, String serviceTemplateName, + ConsolidationData consolidationData) { + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() .getFilePortConsolidationData(serviceTemplateName); - List portTemplateConsolidationDataList = new ArrayList<>(); - - for (String portId : portIds) { - PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData - .getPortTemplateConsolidationData(portId); - if (Objects.nonNull(portTemplateConsolidationData)) { - portTemplateConsolidationDataList.add(portTemplateConsolidationData); - } + List portTemplateConsolidationDataList = new ArrayList<>(); + for (String portId : portIds) { + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataList.add(portTemplateConsolidationData); + } + } + return portTemplateConsolidationDataList; } - return portTemplateConsolidationDataList; - } - - private boolean areWantedPortPropertiesValid(List propertiesToCheck, - Predicate condition) { - - return propertiesToCheck.stream().allMatch(condition); - } - - - private boolean arePropertiesSimilarBetweenComputeNodeTemplates( - ServiceTemplate serviceTemplate, - Collection computeNodeTemplateIds, - List propertiesThatNeedToBeSimilar) { - - Map idToNodeTemplate = - serviceTemplate.getTopology_template().getNode_templates(); - - for (String property : propertiesThatNeedToBeSimilar) { - if (!isPropertyValueSimilarBetweenNodeTemplates(property, computeNodeTemplateIds, - idToNodeTemplate)) { - return false; - } - } - return true; - } - - private boolean isPropertyUsageSimilarBetweenAllNodeTemplates(String propertyToCheck, - List entityNodeTemplateIds, - Map idToNodeTemplate) { - NodeTemplate startingNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(0)); - if (Objects.isNull(startingNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(0)) - .build()); - } - - boolean propertyExistCondition = - isPropertyExistInNodeTemplate(propertyToCheck, startingNodeTemplate); - - for (int i = 1; i < entityNodeTemplateIds.size(); i++) { - NodeTemplate currentNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(i)); - if (Objects.isNull(currentNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(i)) - .build()); - } - if (propertyExistCondition != isPropertyExistInNodeTemplate(propertyToCheck, currentNodeTemplate)) { - return false; - } + private boolean areWantedPortPropertiesValid(List propertiesToCheck, Predicate condition) { + return propertiesToCheck.stream().allMatch(condition); } - return true; - - } - - private boolean isPropertyValueSimilarBetweenNodeTemplates(String propertyToCheck, - Collection entityNodeTemplateIds, - Map idToNodeTemplate) { - - Set propertiesValues = new HashSet<>(); - Iterator iterator = entityNodeTemplateIds.iterator(); - - handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); - - while (iterator.hasNext()) { - handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + private boolean arePropertiesSimilarBetweenComputeNodeTemplates(ServiceTemplate serviceTemplate, Collection computeNodeTemplateIds, + List propertiesThatNeedToBeSimilar) { + Map idToNodeTemplate = serviceTemplate.getTopology_template().getNode_templates(); + for (String property : propertiesThatNeedToBeSimilar) { + if (!isPropertyValueSimilarBetweenNodeTemplates(property, computeNodeTemplateIds, idToNodeTemplate)) { + return false; + } + } + return true; } - return propertiesValues.size() == 1; - } - - private void handlePropertyValue(String propertyToCheck, - Map idToNodeTemplate, - Set propertiesValues, String nodeId) { - NodeTemplate startingNodeTemplate = idToNodeTemplate.get(nodeId); - if (Objects.isNull(startingNodeTemplate)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(nodeId) - .build()); + private boolean isPropertyUsageSimilarBetweenAllNodeTemplates(String propertyToCheck, List entityNodeTemplateIds, + Map idToNodeTemplate) { + NodeTemplate startingNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(0)); + if (Objects.isNull(startingNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(0)).build()); + } + boolean propertyExistCondition = isPropertyExistInNodeTemplate(propertyToCheck, startingNodeTemplate); + for (int i = 1; i < entityNodeTemplateIds.size(); i++) { + NodeTemplate currentNodeTemplate = idToNodeTemplate.get(entityNodeTemplateIds.get(i)); + if (Objects.isNull(currentNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(entityNodeTemplateIds.get(i)).build()); + } + if (propertyExistCondition != isPropertyExistInNodeTemplate(propertyToCheck, currentNodeTemplate)) { + return false; + } + } + return true; } - addPropertyValue(propertyToCheck, startingNodeTemplate, propertiesValues); - } + private boolean isPropertyValueSimilarBetweenNodeTemplates(String propertyToCheck, Collection entityNodeTemplateIds, + Map idToNodeTemplate) { + Set propertiesValues = new HashSet<>(); + Iterator iterator = entityNodeTemplateIds.iterator(); + handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + while (iterator.hasNext()) { + handlePropertyValue(propertyToCheck, idToNodeTemplate, propertiesValues, iterator.next()); + } + return propertiesValues.size() == 1; + } - private void addPropertyValue(String property, - NodeTemplate nodeTemplate, - Set propertiesValues) { - propertiesValues.add( - isPropertyExistInNodeTemplate(property, nodeTemplate) ? nodeTemplate.getProperties() - .get(property) : ""); - } + private void handlePropertyValue(String propertyToCheck, Map idToNodeTemplate, Set propertiesValues, + String nodeId) { + NodeTemplate startingNodeTemplate = idToNodeTemplate.get(nodeId); + if (Objects.isNull(startingNodeTemplate)) { + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(nodeId).build()); + } + addPropertyValue(propertyToCheck, startingNodeTemplate, propertiesValues); + } - private boolean isPropertyExistInNodeTemplate(String propertyToCheck, NodeTemplate nodeTemplate) { - return !(nodeTemplate.getProperties() == null - || nodeTemplate.getProperties().get(propertyToCheck) == null); - } + private void addPropertyValue(String property, NodeTemplate nodeTemplate, Set propertiesValues) { + propertiesValues.add(isPropertyExistInNodeTemplate(property, nodeTemplate) ? nodeTemplate.getProperties().get(property) : ""); + } - void substitutionServiceTemplateConsolidation(String substituteNodeTemplateId, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - TranslationContext translationContext) { + private boolean isPropertyExistInNodeTemplate(String propertyToCheck, NodeTemplate nodeTemplate) { + return !(nodeTemplate.getProperties() == null || nodeTemplate.getProperties().get(propertyToCheck) == null); + } + void substitutionServiceTemplateConsolidation(String substituteNodeTemplateId, ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, TranslationContext translationContext) { ConsolidationData consolidationData = translationContext.getConsolidationData(); - - boolean substitutionConsolidationRuleResult = - substitutionServiceTemplateConsolidationRule(substitutionServiceTemplate, translationContext); - + boolean substitutionConsolidationRuleResult = substitutionServiceTemplateConsolidationRule(substitutionServiceTemplate, translationContext); if (substitutionConsolidationRuleResult) { - List unifiedCompositionDataList = - createSubstitutionUnifiedCompositionDataList(substituteNodeTemplateId, serviceTemplate, - substitutionServiceTemplate, consolidationData); - unifiedCompositionService - .createUnifiedComposition(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - UnifiedCompositionMode.NestedSingleCompute, translationContext); + List unifiedCompositionDataList = createSubstitutionUnifiedCompositionDataList(substituteNodeTemplateId, + serviceTemplate, substitutionServiceTemplate, consolidationData); + unifiedCompositionService.createUnifiedComposition(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + UnifiedCompositionMode.NestedSingleCompute, translationContext); } else { //The node template does not represent unified VFC but complexVFC - //Adding the id in the context for fixing connectivity from/to nested non-unified nodes - translationContext.addUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - substituteNodeTemplateId, substituteNodeTemplateId); + //Adding the id in the context for fixing connectivity from/to nested non-unified nodes + translationContext.addUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), substituteNodeTemplateId, + substituteNodeTemplateId); if (!translationContext.isUnifiedHandledServiceTemplate(substitutionServiceTemplate)) { serviceTemplateConsolidation(substitutionServiceTemplate, translationContext); } } } - private boolean substitutionServiceTemplateConsolidationRule(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { + private boolean substitutionServiceTemplateConsolidationRule(ServiceTemplate nestedServiceTemplate, TranslationContext context) { ConsolidationData consolidationData = context.getConsolidationData(); - - return consolidationData.getComputeConsolidationDataHandler().isNumberOfComputeTypesLegal( - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)) - && !isThereMoreThanOneNestedLevel(nestedServiceTemplate, context); + return consolidationData.getComputeConsolidationDataHandler() + .isNumberOfComputeTypesLegal(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)) && !isThereMoreThanOneNestedLevel( + nestedServiceTemplate, context); } - private boolean isThereMoreThanOneNestedLevel(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { + private boolean isThereMoreThanOneNestedLevel(ServiceTemplate nestedServiceTemplate, TranslationContext context) { String nestedServiceTemplateName = ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); if (Objects.isNull(nestedServiceTemplateName)) { return false; } - NestedConsolidationDataHandler nestedConsolidationDataHandler = context.getNestedConsolidationDataHandler(); - //Condition to check if there is nested file and if file contains only sub interfaces then + // return false - return nestedConsolidationDataHandler.isNestedConsolidationDataExist(nestedServiceTemplateName) - && !ifNestedFileContainsOnlySubInterface(nestedServiceTemplate, context); + return nestedConsolidationDataHandler.isNestedConsolidationDataExist(nestedServiceTemplateName) && !ifNestedFileContainsOnlySubInterface( + nestedServiceTemplate, context); } private boolean ifNestedFileContainsOnlySubInterface(ServiceTemplate serviceTemplate, TranslationContext context) { Map nestedNodeTemplateMap = DataModelUtil.getNodeTemplates(serviceTemplate); - Set nestedHeatFileNames = getNestedHeatFileNames(nestedNodeTemplateMap); - return ifAllResourceAreSubInterface(nestedHeatFileNames, context); } private Set getNestedHeatFileNames(Map nestedNodeTemplateMap) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - - return nestedNodeTemplateMap.entrySet().stream() - .filter(entry -> toscaAnalyzerService.isSubstitutableNodeTemplate(entry.getValue()) - && toscaAnalyzerService.getSubstituteServiceTemplateName( - entry.getKey(), entry.getValue()).isPresent()) - .map(entry -> toscaAnalyzerService.getSubstituteServiceTemplateName( - entry.getKey(), entry.getValue()).get()) - .collect(Collectors.toSet()); + return nestedNodeTemplateMap.entrySet().stream().filter( + entry -> toscaAnalyzerService.isSubstitutableNodeTemplate(entry.getValue()) && toscaAnalyzerService + .getSubstituteServiceTemplateName(entry.getKey(), entry.getValue()).isPresent()) + .map(entry -> toscaAnalyzerService.getSubstituteServiceTemplateName(entry.getKey(), entry.getValue()).get()).collect(Collectors.toSet()); } // Method returns true if all of the resource are sub interface - private boolean ifAllResourceAreSubInterface(Set nestedHeatFileNames, - TranslationContext context) { + private boolean ifAllResourceAreSubInterface(Set nestedHeatFileNames, TranslationContext context) { if (nestedHeatFileNames.isEmpty()) { - return true; + return true; } - for (String fileName : nestedHeatFileNames) { String heatFileName = context.getNestedHeatFileName().get(fileName); - - if (Objects.nonNull(heatFileName) - && !context.getTranslatedServiceTemplates().get(heatFileName).getTopology_template() - .getNode_templates().values().stream() - .allMatch(nodeTemplate -> ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE - .equals(nodeTemplate.getType()))) { + if (Objects.nonNull(heatFileName) && !context.getTranslatedServiceTemplates().get(heatFileName).getTopology_template().getNode_templates() + .values().stream().allMatch(nodeTemplate -> ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE.equals(nodeTemplate.getType()))) { return false; } } - return true; } - private List createUnifiedCompositionDataList( - ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - - List unifiedCompositionDataList = new ArrayList<>(); - - for (ComputeTemplateConsolidationData computeTemplateConsolidationData : typeComputeConsolidationData - .getAllComputeTemplateConsolidationData()) { - UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); - unifiedCompositionData.setComputeTemplateConsolidationData(computeTemplateConsolidationData); - FilePortConsolidationData filePortConsolidationData = - consolidationData.getPortConsolidationData().getFilePortConsolidationData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate)); - setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, filePortConsolidationData, - unifiedCompositionData); - unifiedCompositionDataList.add(unifiedCompositionData); - } - return unifiedCompositionDataList; - } - - private void setPortTemplateConsolidationData(FilePortConsolidationData filePortConsolidationData, - String portId, - UnifiedCompositionData unifiedCompositionData, - List - subInterfaceTemplateConsolidationDataList) { - if (Objects.isNull(filePortConsolidationData)) { - return; - } - PortTemplateConsolidationData portTemplateConsolidationData = - filePortConsolidationData.getPortTemplateConsolidationData(portId); - unifiedCompositionData.addPortTemplateConsolidationData(portTemplateConsolidationData); - if (portTemplateConsolidationData != null) { - portTemplateConsolidationData.copyFlatInto(subInterfaceTemplateConsolidationDataList); - } - } - - private List createSubstitutionUnifiedCompositionDataList( - String substituteNodeTemplateId, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - ConsolidationData consolidationData) { - List unifiedCompositionDataList = new ArrayList<>(); - FileNestedConsolidationData fileNestedConsolidationData = - consolidationData.getNestedConsolidationData() + private List createUnifiedCompositionDataList(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + List unifiedCompositionDataList = new ArrayList<>(); + for (ComputeTemplateConsolidationData computeTemplateConsolidationData : typeComputeConsolidationData + .getAllComputeTemplateConsolidationData()) { + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setComputeTemplateConsolidationData(computeTemplateConsolidationData); + FilePortConsolidationData filePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, filePortConsolidationData, unifiedCompositionData); + unifiedCompositionDataList.add(unifiedCompositionData); + } + return unifiedCompositionDataList; + } + + private void setPortTemplateConsolidationData(FilePortConsolidationData filePortConsolidationData, String portId, + UnifiedCompositionData unifiedCompositionData, + List subInterfaceTemplateConsolidationDataList) { + if (Objects.isNull(filePortConsolidationData)) { + return; + } + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData.getPortTemplateConsolidationData(portId); + unifiedCompositionData.addPortTemplateConsolidationData(portTemplateConsolidationData); + if (portTemplateConsolidationData != null) { + portTemplateConsolidationData.copyFlatInto(subInterfaceTemplateConsolidationDataList); + } + } + + private List createSubstitutionUnifiedCompositionDataList(String substituteNodeTemplateId, + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + ConsolidationData consolidationData) { + List unifiedCompositionDataList = new ArrayList<>(); + FileNestedConsolidationData fileNestedConsolidationData = consolidationData.getNestedConsolidationData() .getFileNestedConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + if (Objects.nonNull(fileNestedConsolidationData)) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = fileNestedConsolidationData + .getNestedTemplateConsolidationData(substituteNodeTemplateId); + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setNestedTemplateConsolidationData(nestedTemplateConsolidationData); + unifiedCompositionDataList.add(unifiedCompositionData); + addSubInterfaceDataToNestedCompositionData(substitutionServiceTemplate, consolidationData, unifiedCompositionData); + } + return unifiedCompositionDataList; + } - if (Objects.nonNull(fileNestedConsolidationData)) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - fileNestedConsolidationData.getNestedTemplateConsolidationData(substituteNodeTemplateId); - UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); - unifiedCompositionData.setNestedTemplateConsolidationData(nestedTemplateConsolidationData); - unifiedCompositionDataList.add(unifiedCompositionData); - addSubInterfaceDataToNestedCompositionData(substitutionServiceTemplate, consolidationData, - unifiedCompositionData); - } - - return unifiedCompositionDataList; - } - - private void addSubInterfaceDataToNestedCompositionData(ServiceTemplate substitutionServiceTemplate, - ConsolidationData consolidationData, - UnifiedCompositionData unifiedCompositionData) { - FileComputeConsolidationData nestedFileComputeConsolidationData = consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); - FilePortConsolidationData nestedFilePortConsolidationData = consolidationData.getPortConsolidationData() - .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); - if (Objects.isNull(nestedFileComputeConsolidationData) - || Objects.isNull(nestedFilePortConsolidationData)) { - return; - } - TypeComputeConsolidationData computeType = - nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); - if (Objects.isNull(computeType)) { - return; - } - ComputeTemplateConsolidationData computeTemplateConsolidationData = - computeType.getAllComputeTemplateConsolidationData().iterator().next(); - setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, nestedFilePortConsolidationData, - unifiedCompositionData); - } - - private void setUnifiedCompositionDataWithPortTemplateData(ComputeTemplateConsolidationData - computeTemplateConsolidationData, - FilePortConsolidationData filePortConsolidationData, - UnifiedCompositionData unifiedCompositionData) { - Collection> portCollection = - computeTemplateConsolidationData.getPorts() == null ? Collections.emptyList() - : computeTemplateConsolidationData.getPorts().values(); - List subInterfaceTemplateConsolidationDataList = new ArrayList<>(); - portCollection.stream() - .flatMap(Collection::stream) - .forEach(portId -> setPortTemplateConsolidationData(filePortConsolidationData, portId, - unifiedCompositionData, subInterfaceTemplateConsolidationDataList)); - unifiedCompositionData.setSubInterfaceTemplateConsolidationDataList( - subInterfaceTemplateConsolidationDataList); - } - - private boolean consolidationPreCondition( - ServiceTemplate serviceTemplate, - ConsolidationData consolidationData, - TypeComputeConsolidationData typeComputeConsolidationData) { - - return (typeComputeConsolidationData.isThereMoreThanOneComputeTypeInstance() - && typeComputeConsolidationData.isNumberOfPortsEqualsBetweenComputeNodes() - && typeComputeConsolidationData.isNumberOfPortFromEachTypeLegal() - && typeComputeConsolidationData.isPortTypesEqualsBetweenComputeNodes() - && checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType(serviceTemplate, - typeComputeConsolidationData, consolidationData) - && checkSubInterfaceConsolidationPreCondition(serviceTemplate, consolidationData, - typeComputeConsolidationData)); - - } - - List getPropertiesWithIdenticalVal(UnifiedCompositionEntity entity) { - switch (entity) { - case COMPUTE: - return getComputePropertiesWithIdenticalVal(); - - case OTHER: - return getComputePropertiesWithIdenticalVal(); - - case PORT: - return getPortPropertiesWithIdenticalVal(); - - default: - return new ArrayList<>(); - } - } - - private List getComputePropertiesWithIdenticalVal() { - List propertyWithIdenticalValue = new ArrayList<>(); - propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_IMAGE); - propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_FLAVOR); - return propertyWithIdenticalValue; - } - - private List getPortPropertiesWithIdenticalVal() { - List propertiesThatNeedToHaveIdenticalVal = new ArrayList<>(); - propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); - propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.MAC_ADDRESS); - - propertiesThatNeedToHaveIdenticalVal - .addAll(TranslationContext.getEnrichPortResourceProperties()); - - return propertiesThatNeedToHaveIdenticalVal; - } - - private List getPortPropertiesThatNeedToHaveSameUsage() { - List propertiesThatNeedToHaveSameUsage = new ArrayList<>(); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_FIXED_IPS); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); - propertiesThatNeedToHaveSameUsage.add(ToscaConstants.MAC_ADDRESS); - - propertiesThatNeedToHaveSameUsage.addAll(TranslationContext.getEnrichPortResourceProperties()); - - return propertiesThatNeedToHaveSameUsage; - } + private void addSubInterfaceDataToNestedCompositionData(ServiceTemplate substitutionServiceTemplate, ConsolidationData consolidationData, + UnifiedCompositionData unifiedCompositionData) { + FileComputeConsolidationData nestedFileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); + FilePortConsolidationData nestedFilePortConsolidationData = consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); + if (Objects.isNull(nestedFileComputeConsolidationData) || Objects.isNull(nestedFilePortConsolidationData)) { + return; + } + TypeComputeConsolidationData computeType = nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); + if (Objects.isNull(computeType)) { + return; + } + ComputeTemplateConsolidationData computeTemplateConsolidationData = computeType.getAllComputeTemplateConsolidationData().iterator().next(); + setUnifiedCompositionDataWithPortTemplateData(computeTemplateConsolidationData, nestedFilePortConsolidationData, unifiedCompositionData); + } + + private void setUnifiedCompositionDataWithPortTemplateData(ComputeTemplateConsolidationData computeTemplateConsolidationData, + FilePortConsolidationData filePortConsolidationData, + UnifiedCompositionData unifiedCompositionData) { + Collection> portCollection = + computeTemplateConsolidationData.getPorts() == null ? Collections.emptyList() : computeTemplateConsolidationData.getPorts().values(); + List subInterfaceTemplateConsolidationDataList = new ArrayList<>(); + portCollection.stream().flatMap(Collection::stream).forEach( + portId -> setPortTemplateConsolidationData(filePortConsolidationData, portId, unifiedCompositionData, + subInterfaceTemplateConsolidationDataList)); + unifiedCompositionData.setSubInterfaceTemplateConsolidationDataList(subInterfaceTemplateConsolidationDataList); + } + + private boolean consolidationPreCondition(ServiceTemplate serviceTemplate, ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + return (typeComputeConsolidationData.isThereMoreThanOneComputeTypeInstance() && typeComputeConsolidationData + .isNumberOfPortsEqualsBetweenComputeNodes() && typeComputeConsolidationData.isNumberOfPortFromEachTypeLegal() + && typeComputeConsolidationData.isPortTypesEqualsBetweenComputeNodes() && checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType( + serviceTemplate, typeComputeConsolidationData, consolidationData) && checkSubInterfaceConsolidationPreCondition(serviceTemplate, + consolidationData, typeComputeConsolidationData)); + } + + List getPropertiesWithIdenticalVal(UnifiedCompositionEntity entity) { + switch (entity) { + case COMPUTE: + return getComputePropertiesWithIdenticalVal(); + case OTHER: + return getComputePropertiesWithIdenticalVal(); + case PORT: + return getPortPropertiesWithIdenticalVal(); + default: + return new ArrayList<>(); + } + } -} + private List getComputePropertiesWithIdenticalVal() { + List propertyWithIdenticalValue = new ArrayList<>(); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_IMAGE); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_FLAVOR); + return propertyWithIdenticalValue; + } + + private List getPortPropertiesWithIdenticalVal() { + List propertiesThatNeedToHaveIdenticalVal = new ArrayList<>(); + propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); + propertiesThatNeedToHaveIdenticalVal.add(ToscaConstants.MAC_ADDRESS); + propertiesThatNeedToHaveIdenticalVal.addAll(TranslationContext.getEnrichPortResourceProperties()); + return propertiesThatNeedToHaveIdenticalVal; + } + private List getPortPropertiesThatNeedToHaveSameUsage() { + List propertiesThatNeedToHaveSameUsage = new ArrayList<>(); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_FIXED_IPS); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); + propertiesThatNeedToHaveSameUsage.add(ToscaConstants.MAC_ADDRESS); + propertiesThatNeedToHaveSameUsage.addAll(TranslationContext.getEnrichPortResourceProperties()); + return propertiesThatNeedToHaveSameUsage; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java index a3d434b138..584cbf5fb2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationTypesConnectivity.java @@ -26,27 +26,23 @@ import com.google.common.collect.Multimap; public class ConsolidationTypesConnectivity { private static Multimap entityToEntitiesWithoutRelationship; - private static ImmutableSet consolidationEntityRelationNodes = ImmutableSet.of( - ConsolidationEntityType.COMPUTE, ConsolidationEntityType.VOLUME, - ConsolidationEntityType.PORT, ConsolidationEntityType.NESTED, + private static ImmutableSet consolidationEntityRelationNodes = ImmutableSet + .of(ConsolidationEntityType.COMPUTE, ConsolidationEntityType.VOLUME, ConsolidationEntityType.PORT, ConsolidationEntityType.NESTED, ConsolidationEntityType.VFC_NESTED); static { - entityToEntitiesWithoutRelationship = - ImmutableSetMultimap.builder() - .putAll(ConsolidationEntityType.COMPUTE, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.PORT, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.VOLUME, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.VFC_NESTED, consolidationEntityRelationNodes) - .putAll(ConsolidationEntityType.NESTED, consolidationEntityRelationNodes) - .build(); + entityToEntitiesWithoutRelationship = ImmutableSetMultimap.builder() + .putAll(ConsolidationEntityType.COMPUTE, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.PORT, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.VOLUME, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.VFC_NESTED, consolidationEntityRelationNodes) + .putAll(ConsolidationEntityType.NESTED, consolidationEntityRelationNodes).build(); } private ConsolidationTypesConnectivity() { } static boolean isDependsOnRelationshipValid(ConsolidationEntityType source, ConsolidationEntityType target) { - return !entityToEntitiesWithoutRelationship.containsKey(source) - || !entityToEntitiesWithoutRelationship.containsEntry(source, target); + return !entityToEntitiesWithoutRelationship.containsKey(source) || !entityToEntitiesWithoutRelationship.containsEntry(source, target); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java index 7c4b23be27..d5a6d6971b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class Constants { @@ -27,19 +26,11 @@ public class Constants { public static final String NAME_PROPERTY_NAME = "name"; public static final String SECURITY_GROUPS_PROPERTY_NAME = "security_groups"; public static final String PORT_PROPERTY_NAME = "port"; - static final String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; - static final String SUB_INTERFACE_ROLE = "subinterface_role"; //General public static final String PROP = "properties"; public static final String ATTR = "attributes"; public static final String SERVICE_INSTANCE_PORT_PREFIX = "port_"; public static final String SERVICE_INSTANCE_LINK_PREFIX = "link_"; - static final String GROUP = "group"; - //Unified model - static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX = "vm_"; - static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX = "_name"; - static final String PORT_IDENTICAL_VALUE_PROPERTY_PREFIX = "port_"; - static final String SUB_INTERFACE_PROPERTY_VALUE_PREFIX = "subinterface_"; public static final String ABSTRACT_NODE_TEMPLATE_ID_PREFIX = "abstract_"; public static final String VNF_NODE_TEMPLATE_ID_SUFFIX = "_VNF"; //GlobalTypesServiceTemplates @@ -48,6 +39,14 @@ public class Constants { public static final String FAILED_TO_GENERATE_GLOBAL_TYPES = "Failed to generate globalTypes"; public static final String OPENECOMP_INVENTORY = "openecomp-inventory"; public static final String GLOBAL_TYPES = "globalTypes"; + static final String VFC_PARENT_PORT_ROLE = "vfc_parent_port_role"; + static final String SUB_INTERFACE_ROLE = "subinterface_role"; + static final String GROUP = "group"; + //Unified model + static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX = "vm_"; + static final String COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX = "_name"; + static final String PORT_IDENTICAL_VALUE_PROPERTY_PREFIX = "port_"; + static final String SUB_INTERFACE_PROPERTY_VALUE_PREFIX = "subinterface_"; private Constants() { } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java index 54805bed2c..6b0b20ce52 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; - public interface FunctionTranslation { Object translateFunction(FunctionTranslator functionTranslator); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java index 257bb9bd3a..f0975cb15c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java @@ -13,27 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; +import java.util.Map; +import java.util.Optional; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; -import java.util.Map; -import java.util.Optional; - public class FunctionTranslationFactory { + private static final Map functionTranslationImplMap; static { Configuration config = ConfigurationManager.lookup(); - functionTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); - functionTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, - ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); - + functionTranslationImplMap = config + .populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + functionTranslationImplMap.putAll(config + .populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, + ImplementationConfiguration.class)); } /** @@ -44,10 +43,8 @@ public class FunctionTranslationFactory { */ public static Optional getInstance(String heatFunctionKey) { if (isSupportedFunction(heatFunctionKey)) { - String functionTranslationImplClassName = - functionTranslationImplMap.get(heatFunctionKey).getImplementationClass(); - return Optional.of(CommonMethods - .newInstance(functionTranslationImplClassName, FunctionTranslation.class)); + String functionTranslationImplClassName = functionTranslationImplMap.get(heatFunctionKey).getImplementationClass(); + return Optional.of(CommonMethods.newInstance(functionTranslationImplClassName, FunctionTranslation.class)); } return Optional.empty(); } @@ -55,6 +52,4 @@ public class FunctionTranslationFactory { private static boolean isSupportedFunction(String heatFunctionKey) { return functionTranslationImplMap.containsKey(heatFunctionKey); } - } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java index 02f4fd6226..67bf8e43c3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaLogConstants.java @@ -13,133 +13,111 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; public class HeatToToscaLogConstants { - private static final String LOG_HEAT_RESOURCE_TYPE_PREFIX = "Heat resource: '{}' with type: '{}' "; - private static final String LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX = - "therefore this resource will be ignored in TOSCA translation."; - private static final String LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX = - "therefore this connection will be ignored in TOSCA translation."; - private static final String LOG_UNSUPPORTED_PROPERTY_SUFFIX = - "therefore this property will be ignored in TOSCA translation."; - - //Contrail Attach Policy messages - public static final String LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'policy' property without 'get_attr' of 'fq_name'/'get_resource' function, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_UNSUPPORTED_POLICY_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include unsupported policy resource, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'network' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - - //Service Instance messages - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'service_template' property without 'get_resource' function, currently not supported, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE = - "Resource id '{}' with type '{} has reference to resource '{}' with type '{}' in property service_template" - + ". Invalid type, resource type should be type of '{}', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE = - "Resource id '{}' with type '{}' has reference to unsupported resource '{}' with type '{}' in" - + " property 'service_template', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES = - "More than one ServiceInstance pointing to the same ServiceTemplate '{} ' with different number of " - + "interfaces., " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - public static final String LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "missing 'virtual_network' property in 'interface_list' entry, therefore, no network connection is " - + "define for this entry."; - public static final String LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has connection to invalid/not supported network resource, " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - public static final String LOG_INVALID_NETWORK_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'virtual_network' property with value '{}', the connection to this network wasn't found/not " - + "supported " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX + " for this property."; - - //Contrail v2 virtual network - public static final String LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "property network_policy_refs is referenced to an unsupported resource " - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - - public static final String LOG_INVALID_PROPERTY_VALUE_FORMAT = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "invalid format of property value, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; - - public static final String LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has property with invalid format of 'get_attr' function with 'fq_name' value, " - + LOG_UNSUPPORTED_PROPERTY_SUFFIX; - public static final String LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "has property with invalid format of 'get_resource' function, " - + LOG_UNSUPPORTED_PROPERTY_SUFFIX; - - //Contrail v2 vlan subinterface - public static final String LOG_MULTIPLE_INTERFACE_VALUES = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include '{}' property with more than one interface values, only the first interface will be connected, " - + "all rest will be ignored in TOSCA translation"; - public static final String LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include '{}' property which is connect to unsupported/incorrect {} resource '{}' with type '{}', " - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; //Security rules to port public static final String LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION = - "Nested resource '{}' property '{}' is pointing to resource with type '{}' which is not supported for " - + "capability '{}' connection, (security rules to port connection). Supported types are: '{}', " - + "therefore, this TOSCA capability will not be connected."; - + "Nested resource '{}' property '{}' is pointing to resource with type '{}' which is not supported for " + + "capability '{}' connection, (security rules to port connection). Supported types are: '{}', " + + "therefore, this TOSCA capability will not be connected."; //Neutron Port public static final String LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION = - "'{}' property of port resource('{}') is pointing to a resource of type '{}' which is not supported for " - + "this requirement. Supported types are: {}"; - //Volume Attachment - public static final String LOG_INVALID_INSTANCE_UUID = LOG_HEAT_RESOURCE_TYPE_PREFIX - + "include 'instance_uuid' property without 'get_resource' function, " - + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + "'{}' property of port resource('{}') is pointing to a resource of type '{}' which is not supported for " + + "this requirement. Supported types are: {}"; public static final String LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG = - "Volume attachment with id '{}' is pointing to unsupported resource type({}) through the property " - + "'volume_id'. The connection to the volume is ignored. Supported types are: {}"; - + "Volume attachment with id '{}' is pointing to unsupported resource type({}) through the property " + + "'volume_id'. The connection to the volume is ignored. Supported types are: {}"; //Capability/Requirement helpers - public static final String LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED = "'{}' property is not define in nested " - + "resource '{}' for the nested heat file, therefore, '{}' TOSCA {} will not be connected."; - public static final String LOG_UNSUPPORTED_CAPABILITY_CONNECTION = - "'{}' connection to '{}' capability of type '{}' is not supported/invalid," - + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; - + public static final String LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED = + "'{}' property is not define in nested " + "resource '{}' for the nested heat file, therefore, '{}' TOSCA {} will not be connected."; //Port to Net Resource Connection public static final String LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " - + "supported for requirement '{}' that connect port to network. Supported types are: '{}', " - + "therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " + + "supported for requirement '{}' that connect port to network. Supported types are: '{}', " + + "therefore, this TOSCA requirement will not be connected."; public static final String LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " - + "supported for requirement '{}' that connect VolumeAttachment to Volume. Supported " - + "types are: '{}', therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not " + + "supported for requirement '{}' that connect VolumeAttachment to Volume. Supported " + + "types are: '{}', therefore, this TOSCA requirement will not be connected."; //Contrail v2 vmi to net resource connection - public static final String LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES = - "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with " - + "type '{}' which include 'virtual_network_refs' property with more than one network values, " - + "only the first network will be translated, all rest will be ignored in TOSCA translation."; + public static final String LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES = "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with " + + "type '{}' which include 'virtual_network_refs' property with more than one network values, " + + "only the first network will be translated, all rest will be ignored in TOSCA translation."; public static final String LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported for " - + "requirement '{}' that connect virtual machine interface to network. Supported " - + "types are: '{}', therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported for " + + "requirement '{}' that connect virtual machine interface to network. Supported " + + "types are: '{}', therefore, this TOSCA requirement will not be connected."; //Contrail v2 vlan to interface connection public static final String LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a {} resource with type '{}' which is not supported " - + "for requirement '{}' that connect vmi vlan sub interface to interface. Supported types are: " - + "'{}' (excluding Vlan), therefore, this TOSCA requirement will not be connected."; - + "Nested resource '{}' property '{}' is pointing to a {} resource with type '{}' which is not supported " + + "for requirement '{}' that connect vmi vlan sub interface to interface. Supported types are: " + + "'{}' (excluding Vlan), therefore, this TOSCA requirement will not be connected."; public static final String LOG_MULTIPLE_INTERFACE_VALUES_NESTED = - "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with type '{}' which include '{}' " - + "property with more than one interface values, only the first interface will be connected, all " - + "rest will be ignored in TOSCA translation."; - + "Heat resource: '{}' with nested heat file: '{}' has resource '{}' with type '{}' which include '{}' " + + "property with more than one interface values, only the first interface will be connected, all " + + "rest will be ignored in TOSCA translation."; public static final String LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION = - "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported" - + "for requirement '{}' that connect contrail port to network. Supported types " - + "are: '{}', therefore, this TOSCA requirement will not be connected."; + "Nested resource '{}' property '{}' is pointing to a resource with type '{}' which is not supported" + + "for requirement '{}' that connect contrail port to network. Supported types " + + "are: '{}', therefore, this TOSCA requirement will not be connected."; + private static final String LOG_HEAT_RESOURCE_TYPE_PREFIX = "Heat resource: '{}' with type: '{}' "; + public static final String LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "missing 'virtual_network' property in 'interface_list' entry, therefore, no network connection is " + + "define for this entry."; + //Contrail v2 vlan subinterface + public static final String LOG_MULTIPLE_INTERFACE_VALUES = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include '{}' property with more than one interface values, only the first interface will be connected, " + + "all rest will be ignored in TOSCA translation"; + private static final String LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX = "therefore this resource will be ignored in TOSCA translation."; + //Contrail Attach Policy messages + public static final String LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'policy' property without 'get_attr' of 'fq_name'/'get_resource' function, " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_UNSUPPORTED_POLICY_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include unsupported policy resource, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'network' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + //Service Instance messages + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'service_template' property without 'get_resource' function, currently not supported, " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE = + "Resource id '{}' with type '{} has reference to resource '{}' with type '{}' in property service_template" + + ". Invalid type, resource type should be type of '{}', " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE = + "Resource id '{}' with type '{}' has reference to unsupported resource '{}' with type '{}' in" + " property 'service_template', " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES = + "More than one ServiceInstance pointing to the same ServiceTemplate '{} ' with different number of " + "interfaces., " + + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + public static final String LOG_INVALID_PROPERTY_VALUE_FORMAT = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "invalid format of property value, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + //Volume Attachment + public static final String LOG_INVALID_INSTANCE_UUID = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'instance_uuid' property without 'get_resource' function, " + LOG_UNSUPPORTED_HEAT_RESOURCE_SUFFIX; + private static final String LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX = "therefore this connection will be ignored in TOSCA translation."; + public static final String LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has connection to invalid/not supported network resource, " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_INVALID_NETWORK_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include 'virtual_network' property with value '{}', the connection to this network wasn't found/not " + + "supported " + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX + " for this property."; + //Contrail v2 virtual network + public static final String LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "property network_policy_refs is referenced to an unsupported resource " + + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "include '{}' property which is connect to unsupported/incorrect {} resource '{}' with type '{}', " + + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + public static final String LOG_UNSUPPORTED_CAPABILITY_CONNECTION = + "'{}' connection to '{}' capability of type '{}' is not supported/invalid," + LOG_UNSUPPORTED_RESOURCE_CONNECTION_SUFFIX; + private static final String LOG_UNSUPPORTED_PROPERTY_SUFFIX = "therefore this property will be ignored in TOSCA translation."; + public static final String LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has property with invalid format of 'get_attr' function with 'fq_name' value, " + + LOG_UNSUPPORTED_PROPERTY_SUFFIX; + public static final String LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE = + LOG_HEAT_RESOURCE_TYPE_PREFIX + "has property with invalid format of 'get_resource' function, " + LOG_UNSUPPORTED_PROPERTY_SUFFIX; private HeatToToscaLogConstants() { //Hiding implicit constructor diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java index d204281d6b..b7f1ff2cb9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import static org.openecomp.sdc.heat.services.HeatResourceUtil.extractNetworkRoleFromSubInterfaceId; @@ -31,7 +30,6 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.io.FilenameUtils; @@ -119,24 +117,19 @@ public class HeatToToscaUtil { */ public static TranslatorOutput loadAndTranslateTemplateData(FileContentHandler fileNameContentMap) { HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface(); - try (InputStream fileContent = fileNameContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent)); } catch (IOException e) { throw new SdcRuntimeException("Failed to read manifest", e); } - fileNameContentMap.getFileList().stream().filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))) - .forEach(fileName -> heatToToscaTranslator.addFile(fileName, - fileNameContentMap.getFileContent(fileName))); - + .forEach(fileName -> heatToToscaTranslator.addFile(fileName, fileNameContentMap.getFileContent(fileName))); Map> errors = heatToToscaTranslator.validate(); if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { TranslatorOutput translatorOutput = new TranslatorOutput(); translatorOutput.setErrorMessages(errors); return translatorOutput; } - try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) { heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile); return heatToToscaTranslator.translate(); @@ -146,7 +139,6 @@ public class HeatToToscaUtil { } } - private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) { HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap); heatTreeManager.createTree(); @@ -163,8 +155,7 @@ public class HeatToToscaUtil { * @param types the types * @return the optional */ - public static Optional> buildListOfFilesToSearch(String heatFileName, List filesDataList, - FileData.Type... types) { + public static Optional> buildListOfFilesToSearch(String heatFileName, List filesDataList, FileData.Type... types) { List list = new ArrayList<>(filesDataList); Optional resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList); if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) { @@ -180,8 +171,7 @@ public class HeatToToscaUtil { * @param types the types * @return the filtered list of file data by types */ - public static List getFilteredListOfFileDataByTypes(List filesToSearch, - FileData.Type... types) { + public static List getFilteredListOfFileDataByTypes(List filesToSearch, FileData.Type... types) { return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types)).collect(Collectors.toList()); } @@ -202,8 +192,7 @@ public class HeatToToscaUtil { } /** - * Gets file data which is supported by the translator, from the context according the input heat - * file name. + * Gets file data which is supported by the translator, from the context according the input heat file name. * * @param heatFileName the heat file name * @param context the translation context @@ -212,8 +201,7 @@ public class HeatToToscaUtil { public static FileData getFileData(String heatFileName, TranslationContext context) { List fileDataList = context.getManifest().getContent().getData(); for (FileData fileData : fileDataList) { - if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile() - .equals(heatFileName)) { + if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile().equals(heatFileName)) { return fileData; } } @@ -225,8 +213,7 @@ public class HeatToToscaUtil { Map filteredFiles = filterFileDataListByType(fileDataList, typeFilter); for (FileData fileData : filteredFiles.values()) { String fileName = fileData.getFile(); - if((fileData.getType().equals(FileData.Type.HELM))) - { + if ((fileData.getType().equals(FileData.Type.HELM))) { fileDataCollection.addHelmFiles(fileData); } } @@ -234,33 +221,28 @@ public class HeatToToscaUtil { } static FileDataCollection getFileCollectionsByFilter(List fileDataList, Set typeFilter, - TranslationContext translationContext) { + TranslationContext translationContext) { FileDataCollection fileDataCollection = new FileDataCollection(); Map filteredFiles = filterFileDataListByType(fileDataList, typeFilter); Set referenced = new HashSet<>(); for (FileData fileData : filteredFiles.values()) { String fileName = fileData.getFile(); - if (FileData.isHeatFile(fileData.getType())) { if (fileData.getBase() != null && fileData.getBase()) { fileDataCollection.addBaseFiles(fileData); } - HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(fileName), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(fileName), HeatOrchestrationTemplate.class); if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) { - referenced.addAll(applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext, - fileDataCollection, filteredFiles)); + referenced.addAll(applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext, fileDataCollection, filteredFiles)); } - } else { fileDataCollection.addArtifactFiles(fileData); filteredFiles.remove(fileData.getFile()); } } - referenced.addAll(getAssociatedFiles(filteredFiles.values())); referenced.forEach(filteredFiles::remove); - if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) { for (FileData fileData : fileDataCollection.getBaseFile()) { filteredFiles.remove(fileData.getFile()); @@ -272,16 +254,13 @@ public class HeatToToscaUtil { private static Set getAssociatedFiles(Collection filteredFiles) { Set associatedFiles = new HashSet<>(); - filteredFiles.stream().filter(file -> file.getParentFile() != null - && FileData.Type.canBeAssociated(file.getType())) - .forEach(file -> associatedFiles.add(file.getFile())); + filteredFiles.stream().filter(file -> file.getParentFile() != null && FileData.Type.canBeAssociated(file.getType())) + .forEach(file -> associatedFiles.add(file.getFile())); return associatedFiles; } - private static Set applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext translationContext, - FileDataCollection fileDataCollection, - Map filteredFiles) { + private static Set applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext translationContext, + FileDataCollection fileDataCollection, Map filteredFiles) { Set nestedFiles = new HashSet<>(); List filenames = extractFilenamesFromFileDataList(filteredFiles.values()); for (Resource resource : heatOrchestrationTemplate.getResources().values()) { @@ -290,24 +269,22 @@ public class HeatToToscaUtil { handleNestedFile(translationContext, fileDataCollection, filteredFiles, resourceType); nestedFiles.add(resourceType); } else if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { - Optional nestedFile = handleResourceGrpNestedFile(resource, translationContext, - fileDataCollection, filteredFiles, filenames); + Optional nestedFile = handleResourceGrpNestedFile(resource, translationContext, fileDataCollection, filteredFiles, filenames); nestedFile.ifPresent(nestedFiles::add); } } return nestedFiles; } - private static Optional handleResourceGrpNestedFile(Resource resource, TranslationContext - translationContext, FileDataCollection fileDataCollection, - Map filteredFiles, List filenames) { + private static Optional handleResourceGrpNestedFile(Resource resource, TranslationContext translationContext, + FileDataCollection fileDataCollection, Map filteredFiles, + List filenames) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); if (innerTypeDef instanceof String) { String internalResourceType = (String) innerTypeDef; if (filenames.contains(internalResourceType)) { - handleNestedFile(translationContext, fileDataCollection, filteredFiles, - internalResourceType); + handleNestedFile(translationContext, fileDataCollection, filteredFiles, internalResourceType); return Optional.of(internalResourceType); } } @@ -315,33 +292,26 @@ public class HeatToToscaUtil { } private static void handleNestedFile(TranslationContext translationContext, FileDataCollection fileDataCollection, - Map filteredFiles, - String nestedFileName) { + Map filteredFiles, String nestedFileName) { fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName)); translationContext.getNestedHeatsFiles().add(nestedFileName); } - private static Map filterFileDataListByType(List fileDataList, - Set typesToGet) { + private static Map filterFileDataListByType(List fileDataList, Set typesToGet) { Map filtered = new HashMap<>(); filterFileDataListByType(fileDataList, filtered, typesToGet, null); return filtered; } - private static void filterFileDataListByType(List fileDataList, Map filtered, - Set typesToGet, String parentFileName) { - fileDataList.stream().filter(file -> typesToGet.contains(file.getType())) - .forEach(file -> { - filtered.put(file.getFile(), file); - file.setParentFile(parentFileName); - }); - - Set canBeAssociatedTypes = typesToGet.stream() - .filter(FileData.Type::canBeAssociated).collect(Collectors.toSet()); - + private static void filterFileDataListByType(List fileDataList, Map filtered, Set typesToGet, + String parentFileName) { + fileDataList.stream().filter(file -> typesToGet.contains(file.getType())).forEach(file -> { + filtered.put(file.getFile(), file); + file.setParentFile(parentFileName); + }); + Set canBeAssociatedTypes = typesToGet.stream().filter(FileData.Type::canBeAssociated).collect(Collectors.toSet()); fileDataList.stream().filter(file -> Objects.nonNull(file.getData())) - .forEach(file -> filterFileDataListByType(file.getData(), filtered, - canBeAssociatedTypes, file.getFile())); + .forEach(file -> filterFileDataListByType(file.getData(), filtered, canBeAssociatedTypes, file.getFile())); } private static List extractFilenamesFromFileDataList(Collection fileDataList) { @@ -360,8 +330,8 @@ public class HeatToToscaUtil { if (propertyValue == null) { return Optional.empty(); } - return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), propertyValue); + return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + propertyValue); } /** @@ -373,18 +343,13 @@ public class HeatToToscaUtil { * @param propertyValue the property value * @return the optional */ - public static Optional extractAttachedResourceId(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - Object propertyValue) { - + public static Optional extractAttachedResourceId(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, Object propertyValue) { Object entity; Object translatedId = null; - if (Objects.isNull(propertyValue)) { return Optional.empty(); } - ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map propMap = (Map) propertyValue; @@ -392,14 +357,11 @@ public class HeatToToscaUtil { entity = entry.getValue(); String key = entry.getKey(); referenceType = getReferenceTypeFromAttachedResouce(key); - if (FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) { - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(null, null, - heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null); - translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get() - .translateFunction(functionTranslator); - if (translatedId instanceof String - && !new FunctionTranslator().isResourceSupported((String) translatedId)) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(null, null, heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null); + translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get().translateFunction(functionTranslator); + if (translatedId instanceof String && !new FunctionTranslator().isResourceSupported((String) translatedId)) { translatedId = null; } } @@ -407,7 +369,6 @@ public class HeatToToscaUtil { translatedId = propertyValue; entity = propertyValue; } - return Optional.of(new AttachedResourceId(translatedId, entity, referenceType)); } @@ -427,7 +388,6 @@ public class HeatToToscaUtil { referenceType = ReferenceType.OTHER; break; } - return referenceType; } @@ -441,11 +401,9 @@ public class HeatToToscaUtil { if (attachedResource == null) { return Optional.empty(); } - if (attachedResource.isGetResource()) { return Optional.of((String) attachedResource.getEntityId()); } - if (attachedResource.isGetAttr()) { return getResourceId(attachedResource.getEntityId()); } @@ -463,7 +421,6 @@ public class HeatToToscaUtil { if (Objects.isNull(propertyValue)) { return Optional.empty(); } - ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map propMap = (Map) propertyValue; @@ -483,7 +440,6 @@ public class HeatToToscaUtil { default: break; } - } else { attachedPropertyVal = propertyValue; } @@ -522,7 +478,6 @@ public class HeatToToscaUtil { } } - /** * Is yml file type boolean. * @@ -542,16 +497,15 @@ public class HeatToToscaUtil { */ public static boolean isNestedResource(Resource resource) { String resourceType = resource.getType(); - if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof String)) { //currently only resource group which is poinitng to nested heat file is supported + //dynamic type is currently not supported return false; } - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); if (isYamlFile(internalResourceType)) { return true; } @@ -577,18 +531,16 @@ public class HeatToToscaUtil { } private static boolean isNestedVlanResource(String nestedHeatFileName, TranslationContext translationContext) { - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(nestedHeatFileName), HeatOrchestrationTemplate.class); - return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate - .getResources().values() - .stream().anyMatch( - new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(nestedHeatFileName), HeatOrchestrationTemplate.class); + return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate.getResources().values().stream() + .anyMatch(new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource); } public static Optional getSubInterfaceParentPortNodeTemplateId(TranslateTo subInterfaceTo) { String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource()); - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - subInterfaceTo.getContext().getFileContentAsStream(subInterfaceResourceType), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(subInterfaceTo.getContext().getFileContentAsStream(subInterfaceResourceType), HeatOrchestrationTemplate.class); if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) { return Optional.empty(); } @@ -596,14 +548,9 @@ public class HeatToToscaUtil { Resource resource = resourceEntry.getValue(); if (isVmiRefsPropertyExists(resource)) { Object toscaPropertyValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(), - resourceEntry.getKey(), - HeatConstants.VMI_REFS_PROPERTY_NAME, - resource.getProperties() - .get(HeatConstants.VMI_REFS_PROPERTY_NAME), - resource.getType(), subInterfaceResourceType, - nestedHeatOrchestrationTemplate, null, - subInterfaceTo.getContext()); + .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(), resourceEntry.getKey(), HeatConstants.VMI_REFS_PROPERTY_NAME, + resource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME), resource.getType(), subInterfaceResourceType, + nestedHeatOrchestrationTemplate, null, subInterfaceTo.getContext()); return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo); } } @@ -611,44 +558,39 @@ public class HeatToToscaUtil { } private static boolean isVmiRefsPropertyExists(Resource resource) { - return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource() - .equals(resource.getType()) - && MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey( - HeatConstants.VMI_REFS_PROPERTY_NAME); + return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource().equals(resource.getType()) && MapUtils + .isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME); } - + public static boolean isValueSpecsPropertyExists(Resource resource) { - return MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey( - HeatConstants.VALUE_SPECS_PROPERTY_NAME); + return MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(HeatConstants.VALUE_SPECS_PROPERTY_NAME); } - - public static Optional getResourceProperty(Resource resource, String propertyName){ + + public static Optional getResourceProperty(Resource resource, String propertyName) { Map properties = resource.getProperties(); - if(MapUtils.isNotEmpty(properties) && properties.containsKey(propertyName)){ + if (MapUtils.isNotEmpty(properties) && properties.containsKey(propertyName)) { return Optional.ofNullable(resource.getProperties().get(propertyName)); } - return Optional.empty(); + return Optional.empty(); } public static String getSubInterfaceResourceType(Resource resource) { if (!HeatToToscaUtil.isYamlFile(resource.getType())) { - return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) - .get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME).toString(); + return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) + .toString(); } return resource.getType(); } - private static Optional getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue, - TranslateTo subInterfaceTo) { + private static Optional getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue, TranslateTo subInterfaceTo) { if (toscaPropertyValue instanceof List && ((List) toscaPropertyValue).get(0) instanceof Map) { Resource subInterfaceResource = subInterfaceTo.getResource(); Map toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0); String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT.getFunctionName()); Map resourceDefPropertiesMap; if (!isYamlFile(subInterfaceResource.getType())) { - resourceDefPropertiesMap = - (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) - .get(HeatConstants.RESOURCE_DEF_PROPERTIES); + resourceDefPropertiesMap = (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME)) + .get(HeatConstants.RESOURCE_DEF_PROPERTIES); } else { resourceDefPropertiesMap = subInterfaceResource.getProperties(); } @@ -656,10 +598,9 @@ public class HeatToToscaUtil { if (parentPortObj instanceof Map) { Map parentPortPropertyValue = (Map) parentPortObj; if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) { - return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(), - subInterfaceTo.getHeatOrchestrationTemplate(), - parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()), - subInterfaceTo.getContext()); + return ResourceTranslationBase + .getResourceTranslatedId(subInterfaceTo.getHeatFileName(), subInterfaceTo.getHeatOrchestrationTemplate(), + parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()), subInterfaceTo.getContext()); } } } @@ -667,8 +608,7 @@ public class HeatToToscaUtil { } /** - * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at - * least one or more compute nodes). + * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at least one or more compute nodes). * * @param resource the resource * @param context the context @@ -676,11 +616,10 @@ public class HeatToToscaUtil { */ public static boolean isNestedVfcResource(Resource resource, TranslationContext context) { Optional nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource); - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - context.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(context.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); Map resources = nestedHeatOrchestrationTemplate.getResources(); - return Objects.nonNull(resources) && resources.values().stream() - .anyMatch(ConsolidationDataUtil::isComputeResource); + return Objects.nonNull(resources) && resources.values().stream().anyMatch(ConsolidationDataUtil::isComputeResource); } /** @@ -693,13 +632,10 @@ public class HeatToToscaUtil { if (!isNestedResource(resource)) { return Optional.empty(); } - String resourceType = resource.getType(); - if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); return Optional.of(internalResourceType); } return Optional.of(resourceType); @@ -718,8 +654,7 @@ public class HeatToToscaUtil { String resourceType = resource.getType(); if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - String internalResourceType = - (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME); return Optional.of(internalResourceType); } else { return Optional.of(resourceType); @@ -738,8 +673,7 @@ public class HeatToToscaUtil { * @param heatFileName the heat file name * @return the resource */ - public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId, - String heatFileName) { + public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId, String heatFileName) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); @@ -747,7 +681,6 @@ public class HeatToToscaUtil { return resource; } - /** * Get resource type. * @@ -756,8 +689,7 @@ public class HeatToToscaUtil { * @param heatFileName heat file name * @return resource type */ - public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName) { + public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName) { return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName).getType(); } @@ -799,8 +731,8 @@ public class HeatToToscaUtil { } private static Optional getResourceId(Object data) { - if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1)) - && ((List) data).get(0) instanceof String) { + if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1)) && ((List) data) + .get(0) instanceof String) { return Optional.of((String) ((List) data).get(0)); } else { LOGGER.warn("invalid format of 'get_attr' function - " + data.toString()); @@ -847,15 +779,13 @@ public class HeatToToscaUtil { * @param entryDefinitionMetadata template name of the entry definition servie template * @return the tosca service model */ - private static ToscaServiceModel getToscaServiceModel(TranslationContext context, - Map entryDefinitionMetadata) { + private static ToscaServiceModel getToscaServiceModel(TranslationContext context, Map entryDefinitionMetadata) { Map serviceTemplates = new HashMap<>(context.getGlobalServiceTemplates()); Collection tmpServiceTemplates = context.getTranslatedServiceTemplates().values(); for (ServiceTemplate serviceTemplate : tmpServiceTemplates) { ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate); } - return new ToscaServiceModel(null, serviceTemplates, - ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata)); + return new ToscaServiceModel(null, serviceTemplates, ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata)); } /** @@ -865,8 +795,7 @@ public class HeatToToscaUtil { * @param context the context * @return the service template from context */ - public static Optional getServiceTemplateFromContext(String serviceTemplateFileName, - TranslationContext context) { + public static Optional getServiceTemplateFromContext(String serviceTemplateFileName, TranslationContext context) { for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) { if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) { return Optional.of(serviceTemplate); @@ -881,8 +810,7 @@ public class HeatToToscaUtil { * @param portNodeTemplate port node template * @param networkTranslatedId network node template id */ - public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate, - String networkTranslatedId) { + public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate, String networkTranslatedId) { RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE); requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); @@ -897,14 +825,12 @@ public class HeatToToscaUtil { * @param subInterfaceNodeTemplate sub interface template * @param interfaceTranslatedId interface node template id */ - public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate, - String interfaceTranslatedId) { + public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) { RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE); requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO); requirement.setNode(interfaceTranslatedId); - DataModelUtil - .addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement); + DataModelUtil.addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement); } /** @@ -936,8 +862,7 @@ public class HeatToToscaUtil { } } - public static String getToscaPropertyName(TranslationContext context, String heatResourceType, - String heatPropertyName) { + public static String getToscaPropertyName(TranslationContext context, String heatResourceType, String heatPropertyName) { return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName); } @@ -949,8 +874,7 @@ public class HeatToToscaUtil { * @return the tosca property name */ public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) { - return translateTo.getContext() - .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName); + return translateTo.getContext().getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName); } /** @@ -961,8 +885,7 @@ public class HeatToToscaUtil { * @param heatAttrName the heat attr name * @return the tosca attribute name */ - public static String getToscaAttributeName(TranslationContext context, String heatResourceType, - String heatAttrName) { + public static String getToscaAttributeName(TranslationContext context, String heatResourceType, String heatAttrName) { return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName); } @@ -974,8 +897,7 @@ public class HeatToToscaUtil { * @return the tosca attribute name */ public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) { - return translateTo.getContext() - .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName); + return translateTo.getContext().getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName); } /** @@ -992,8 +914,7 @@ public class HeatToToscaUtil { nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); List> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList(); - globalTypesImportList - .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + globalTypesImportList.addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); return nestedSubstitutionServiceTemplate; } @@ -1006,8 +927,7 @@ public class HeatToToscaUtil { private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() { ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate(); Map templateMetadata = new HashMap<>(); - templateMetadata - .put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); globalSubstitutionServiceTemplate.setMetadata(templateMetadata); globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); @@ -1015,78 +935,8 @@ public class HeatToToscaUtil { } /** - * Create substitution node type node type. - * - * @param substitutionServiceTemplate the substitution service template - * @return the node type - */ - public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) { - NodeType substitutionNodeType = new NodeType(); - substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE); - substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); - substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate)); - substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate)); - return substitutionNodeType; - } - - private Map manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) { - Map substitutionNodeTypeProperties = new HashMap<>(); - Map properties = substitutionServiceTemplate.getTopology_template().getInputs(); - if (properties == null) { - return null; - } - - PropertyDefinition propertyDefinition; - String toscaPropertyName; - for (Map.Entry entry : properties.entrySet()) { - toscaPropertyName = entry.getKey(); - propertyDefinition = new PropertyDefinition(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); - propertyDefinition.setType(parameterDefinition.getType()); - propertyDefinition.setDescription(parameterDefinition.getDescription()); - propertyDefinition.setRequired(parameterDefinition.getRequired()); - propertyDefinition.set_default(parameterDefinition.get_default()); - propertyDefinition.setConstraints(parameterDefinition.getConstraints()); - propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - propertyDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); - } - return substitutionNodeTypeProperties; - } - - private Map manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) { - Map substitutionNodeTypeAttributes = new HashMap<>(); - Map attributes = substitutionServiceTemplate.getTopology_template().getOutputs(); - if (attributes == null) { - return null; - } - AttributeDefinition attributeDefinition; - String toscaAttributeName; - - for (Map.Entry entry : attributes.entrySet()) { - attributeDefinition = new AttributeDefinition(); - toscaAttributeName = entry.getKey(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); - if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { - attributeDefinition.setType(parameterDefinition.getType()); - } else { - attributeDefinition.setType(PropertyType.STRING.getDisplayName()); - } - attributeDefinition.setDescription(parameterDefinition.getDescription()); - attributeDefinition.set_default(parameterDefinition.get_default()); - attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - attributeDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); - } - return substitutionNodeTypeAttributes; - } - - /** - * . - * Create and add substitution mapping to the nested substitution service template, and update - * the subtitution node type accordingly with the exposed requerments and capabilities + * . Create and add substitution mapping to the nested substitution service template, and update the subtitution node type accordingly with the + * exposed requerments and capabilities * * @param context the translation context * @param substitutionNodeTypeKey the substitution node type key @@ -1094,17 +944,12 @@ public class HeatToToscaUtil { * @param substitutionNodeType the substitution node type */ public static void handleSubstitutionMapping(TranslationContext context, String substitutionNodeTypeKey, - ServiceTemplate nestedSubstitutionServiceTemplate, - NodeType substitutionNodeType) { - Map>> substitutionMapping = - getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, nestedSubstitutionServiceTemplate, - context); + ServiceTemplate nestedSubstitutionServiceTemplate, NodeType substitutionNodeType) { + Map>> substitutionMapping = getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, + nestedSubstitutionServiceTemplate, context); //add substitution mapping after capability and requirement expose calculation - nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(DataModelUtil - .createSubstitutionTemplateSubMapping( - substitutionNodeTypeKey, - substitutionNodeType, - substitutionMapping)); + nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings( + DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey, substitutionNodeType, substitutionMapping)); } /** @@ -1115,16 +960,13 @@ public class HeatToToscaUtil { * @param context the context * @return the node type with flat hierarchy */ - public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate, - TranslationContext context) { + public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate, TranslationContext context) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata()); - return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, - toscaServiceModel).getFlatEntity(); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata()); + return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel) + .getFlatEntity(); } - /** * Create abstract substitution node template. * @@ -1133,72 +975,57 @@ public class HeatToToscaUtil { * @param substitutionNodeTypeKey the substitution node type key * @return the abstract substitute node template */ - public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName, - String substitutionNodeTypeKey) { + public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName, String substitutionNodeTypeKey) { NodeTemplate substitutionNodeTemplate = new NodeTemplate(); List directiveList = new ArrayList<>(); directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); substitutionNodeTemplate.setDirectives(directiveList); substitutionNodeTemplate.setType(substitutionNodeTypeKey); - substitutionNodeTemplate.setProperties( - managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName)); + substitutionNodeTemplate.setProperties(managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName)); return substitutionNodeTemplate; } - /** - * Checks if the source and target resource is a valid candidate for adding tosca dependency - * relationship. + * Checks if the source and target resource is a valid candidate for adding tosca dependency relationship. * * @param sourceResource the source resource * @param targetResource the target resource * @param dependencyEntity the dependency entity - * @return true if the candidate resources are a valid combination for the dependency relationship - * and false otherwise + * @return true if the candidate resources are a valid combination for the dependency relationship and false otherwise */ - public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource, - ConsolidationEntityType dependencyEntity, - TranslationContext context) { + public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource, ConsolidationEntityType dependencyEntity, + TranslationContext context) { dependencyEntity.setEntityType(sourceResource, targetResource, context); ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType(); ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType(); - return ConsolidationTypesConnectivity.isDependsOnRelationshipValid(sourceEntityType, targetEntityType); } - private static Map managerSubstitutionNodeTemplateProperties(TranslateTo translateTo, - Template template, - String templateName) { + private static Map managerSubstitutionNodeTemplateProperties(TranslateTo translateTo, Template template, String templateName) { Map substitutionProperties = new HashMap<>(); Map heatProperties = translateTo.getResource().getProperties(); if (Objects.nonNull(heatProperties)) { for (Map.Entry entry : heatProperties.entrySet()) { Object property = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), - translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null, - translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), template, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext()); substitutionProperties.put(entry.getKey(), property); } } return addAbstractSubstitutionProperty(templateName, substitutionProperties); } - private static Map addAbstractSubstitutionProperty(String templateName, - Map substitutionProperties) { + private static Map addAbstractSubstitutionProperty(String templateName, Map substitutionProperties) { Map innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(templateName)); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, ToscaUtil.getServiceTemplateFileName(templateName)); substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); return substitutionProperties; } private static Map>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context) { - Map nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); + ServiceTemplate substitutionServiceTemplate, + TranslationContext context) { + Map nodeTemplates = substitutionServiceTemplate.getTopology_template().getNode_templates(); String nodeTemplateId; NodeTemplate nodeTemplate; String nodeType; @@ -1206,7 +1033,6 @@ public class HeatToToscaUtil { if (nodeTemplates == null) { return substitutionMapping; } - Map> capabilitySubstitutionMapping = new HashMap<>(); Map> requirementSubstitutionMapping = new HashMap<>(); substitutionMapping.put("capability", capabilitySubstitutionMapping); @@ -1218,54 +1044,43 @@ public class HeatToToscaUtil { Map nodeTypeCapabilitiesDefinition = new HashMap<>(); Map exposedCapabilitiesDefinition; ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - for (Map.Entry entry : nodeTemplates.entrySet()) { nodeTemplateId = entry.getKey(); nodeTemplate = entry.getValue(); nodeType = nodeTemplate.getType(); - // get requirements - nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate, - requirementSubstitutionMapping, context); + nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate, requirementSubstitutionMapping, + context); nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate); fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment); //set substitution node type requirements exposedRequirementsDefinition = toscaAnalyzerService - .calculateExposedRequirements(nodeTypeRequirementsDefinition, - nodeTemplateRequirementsAssignment); - DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, - nodeTemplateId); - + .calculateExposedRequirements(nodeTypeRequirementsDefinition, nodeTemplateRequirementsAssignment); + DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, nodeTemplateId); //get capabilities - addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType, - nodeTemplateId, substitutionServiceTemplate, context); + addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType, nodeTemplateId, + substitutionServiceTemplate, context); } - exposedCapabilitiesDefinition = toscaAnalyzerService - .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, - fullFilledRequirementsDefinition); + .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, fullFilledRequirementsDefinition); DataModelUtil.setNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition); return substitutionMapping; } private static void addNodeTypeCapabilitiesToSubMapping(Map nodeTypeCapabilitiesDefinition, - Map> capabilitySubstitutionMapping, - String type, String templateName, - ServiceTemplate serviceTemplate, - TranslationContext context) { + Map> capabilitySubstitutionMapping, String type, String templateName, + ServiceTemplate serviceTemplate, TranslationContext context) { NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); - if (flatNodeType.getCapabilities() != null) { flatNodeType.getCapabilities().entrySet().stream().forEach( - capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry, - nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping)); + capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry, nodeTypeCapabilitiesDefinition, + capabilitySubstitutionMapping)); } } - private static void addCapabilityToSubMapping(String templateName, - Map.Entry capabilityNodeEntry, - Map nodeTypeCapabilitiesDefinition, - Map> capabilitySubstitutionMapping) { + private static void addCapabilityToSubMapping(String templateName, Map.Entry capabilityNodeEntry, + Map nodeTypeCapabilitiesDefinition, + Map> capabilitySubstitutionMapping) { String capabilityKey; List capabilityMapping; capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName; @@ -1276,26 +1091,22 @@ public class HeatToToscaUtil { capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping); } - private static List> getNodeTypeReqs(String type, String templateName, - ServiceTemplate serviceTemplate, - Map> requirementSubstitutionMapping, - TranslationContext context) { + private static List> getNodeTypeReqs(String type, String templateName, ServiceTemplate serviceTemplate, + Map> requirementSubstitutionMapping, + TranslationContext context) { List> requirementList = new ArrayList<>(); NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); List requirementMapping; - if (flatNodeType.getRequirements() == null) { return requirementList; } - for (Map requirementMap : flatNodeType.getRequirements()) { for (Map.Entry requirementNodeEntry : requirementMap.entrySet()) { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), - RequirementDefinition.class); + RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), RequirementDefinition.class); if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } Map requirementDef = new HashMap<>(); requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue); @@ -1303,10 +1114,9 @@ public class HeatToToscaUtil { requirementMapping = new ArrayList<>(); requirementMapping.add(templateName); requirementMapping.add(requirementNodeEntry.getKey()); - requirementSubstitutionMapping - .put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping); + requirementSubstitutionMapping.put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping); if (Objects.isNull(requirementNodeEntryValue.getNode())) { - requirementNodeEntryValue.setOccurrences(new Object[] {1, 1}); + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); } } } @@ -1320,21 +1130,17 @@ public class HeatToToscaUtil { * @param context the context * @return the service template */ - public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, - TranslationContext context) { - ServiceTemplate globalSubstitutionServiceTemplate = - context.getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = context.getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (globalSubstitutionServiceTemplate == null) { globalSubstitutionServiceTemplate = HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate(); - context.getTranslatedServiceTemplates() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); + context.getTranslatedServiceTemplates().put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); } boolean isImportAddedToServiceTemplate = DataModelUtil - .isImportAddedToServiceTemplate(serviceTemplate.getImports(), - Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (!isImportAddedToServiceTemplate) { - serviceTemplate.getImports() - .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + serviceTemplate.getImports().addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); } return globalSubstitutionServiceTemplate; } @@ -1371,33 +1177,28 @@ public class HeatToToscaUtil { return serviceTemplateImport; } - public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate, - TranslationContext translationContext) { + public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate, TranslationContext translationContext) { return new ToscaServiceModel(getCsarArtifactFiles(translationContext), getServiceTemplates(translationContext), - ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); + ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); } private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) { FileContentHandler artifactFiles = new FileContentHandler(); artifactFiles.addAll(translationContext.getFiles()); artifactFiles.addAll(translationContext.getExternalArtifacts()); - HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles()); heatTreeManager.createTree(); ValidationStructureList validationStructureList = new ValidationStructureList(heatTreeManager.getTree()); - byte[] validationStructureFile = - FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); + byte[] validationStructureFile = FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); artifactFiles.addFile("HEAT.meta", validationStructureFile); return artifactFiles; } - private static Map getServiceTemplates(TranslationContext translationContext) { List serviceTemplates = new ArrayList<>(); serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values()); serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values()); Map serviceTemplatesMap = new HashMap<>(); - for (ServiceTemplate template : serviceTemplates) { serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template); } @@ -1405,8 +1206,7 @@ public class HeatToToscaUtil { } public static String getNestedResourceTypePrefix(TranslateTo translateTo) { - if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort( - translateTo)) { + if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort(translateTo)) { return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX; } return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX; @@ -1416,36 +1216,91 @@ public class HeatToToscaUtil { return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent(); } - //Method evaluate the network role from sub interface node template id, designed considering // only single sub interface present in nested file else it will return null - public static Optional getNetworkRoleFromSubInterfaceId(Resource resource, - TranslationContext translationContext) { + public static Optional getNetworkRoleFromSubInterfaceId(Resource resource, TranslationContext translationContext) { Optional networkRole = Optional.empty(); Optional nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource); - if (!nestedHeatFileName.isPresent()) { return networkRole; } - - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject( - translationContext.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); - + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translationContext.getFileContentAsStream(nestedHeatFileName.get()), HeatOrchestrationTemplate.class); if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) { - ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = - new ContrailV2VirtualMachineInterfaceHelper(); - Optional> vlanSubInterfaceResource = - nestedHeatOrchestrationTemplate.getResources().entrySet().stream() - .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource( - resourceEntry.getValue())) - .findFirst(); + ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = new ContrailV2VirtualMachineInterfaceHelper(); + Optional> vlanSubInterfaceResource = nestedHeatOrchestrationTemplate.getResources().entrySet().stream() + .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(resourceEntry.getValue())).findFirst(); if (vlanSubInterfaceResource.isPresent()) { Map.Entry vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get(); networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(), - vlanSubInterfaceResourceEntry.getValue().getType()); + vlanSubInterfaceResourceEntry.getValue().getType()); } } return networkRole; } + /** + * Create substitution node type node type. + * + * @param substitutionServiceTemplate the substitution service template + * @return the node type + */ + public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) { + NodeType substitutionNodeType = new NodeType(); + substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE); + substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); + substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate)); + substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate)); + return substitutionNodeType; + } + + private Map manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) { + Map substitutionNodeTypeProperties = new HashMap<>(); + Map properties = substitutionServiceTemplate.getTopology_template().getInputs(); + if (properties == null) { + return null; + } + PropertyDefinition propertyDefinition; + String toscaPropertyName; + for (Map.Entry entry : properties.entrySet()) { + toscaPropertyName = entry.getKey(); + propertyDefinition = new PropertyDefinition(); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); + propertyDefinition.setType(parameterDefinition.getType()); + propertyDefinition.setDescription(parameterDefinition.getDescription()); + propertyDefinition.setRequired(parameterDefinition.getRequired()); + propertyDefinition.set_default(parameterDefinition.get_default()); + propertyDefinition.setConstraints(parameterDefinition.getConstraints()); + propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + propertyDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); + } + return substitutionNodeTypeProperties; + } + //Method evaluate the network role from sub interface node template id, designed considering + + private Map manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) { + Map substitutionNodeTypeAttributes = new HashMap<>(); + Map attributes = substitutionServiceTemplate.getTopology_template().getOutputs(); + if (attributes == null) { + return null; + } + AttributeDefinition attributeDefinition; + String toscaAttributeName; + for (Map.Entry entry : attributes.entrySet()) { + attributeDefinition = new AttributeDefinition(); + toscaAttributeName = entry.getKey(); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); + if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { + attributeDefinition.setType(parameterDefinition.getType()); + } else { + attributeDefinition.setType(PropertyType.STRING.getDisplayName()); + } + attributeDefinition.setDescription(parameterDefinition.getDescription()); + attributeDefinition.set_default(parameterDefinition.get_default()); + attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + attributeDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); + } + return substitutionNodeTypeAttributes; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java index e732080cb5..a54c85ff82 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; import org.openecomp.sdc.heat.datatypes.model.Resource; public interface NameExtractor { - String extractNodeTypeName(Resource resource, String resourceId, String translatedId); - + String extractNodeTypeName(Resource resource, String resourceId, String translatedId); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java index b4d41f5b6c..abd19863d5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,58 +17,51 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; -import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; - import java.util.List; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; public class NameExtractorUtil { - /** - * Extract Node Type Name By Properties Priority. - * @param properties properties list - * @param propertiesRegexMatchers Regex expression list - * @return node type name - */ - public static Optional extractNodeTypeNameByPropertiesPriority( - Map properties, - List propertiesRegexMatchers) { - - for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { - Optional parameterNameValue = - HeatToToscaUtil.getPropertyParameterNameValue( - properties.get(propertyRegexMatcher.getPropertyName())); - if (parameterNameValue.isPresent()) { - if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { - return Optional.of(parameterNameValue.get().substring(0, parameterNameValue.get() - .lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); + /** + * Extract Node Type Name By Properties Priority. + * + * @param properties properties list + * @param propertiesRegexMatchers Regex expression list + * @return node type name + */ + public static Optional extractNodeTypeNameByPropertiesPriority(Map properties, + List propertiesRegexMatchers) { + for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { + Optional parameterNameValue = HeatToToscaUtil + .getPropertyParameterNameValue(properties.get(propertyRegexMatcher.getPropertyName())); + if (parameterNameValue.isPresent()) { + if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { + return Optional.of(parameterNameValue.get() + .substring(0, parameterNameValue.get().lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); + } + } } - } + return Optional.empty(); } - return Optional.empty(); - } - /** - * Check if property value match the naming convention using Regex expression. - * @param propertyRegexMatcher naming convention using Regex expression - * @param propertyValue property value - * @return true is there is a match, false otherwise - */ - public static boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher - propertyRegexMatcher, - String propertyValue) { - for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { - if (pattern.matcher(propertyValue).matches()) { - return true; - } + /** + * Check if property value match the naming convention using Regex expression. + * + * @param propertyRegexMatcher naming convention using Regex expression + * @param propertyValue property value + * @return true is there is a match, false otherwise + */ + public static boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher propertyRegexMatcher, String propertyValue) { + for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { + if (pattern.matcher(propertyValue).matches()) { + return true; + } + } + return false; } - return false; - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java index 6537e95eeb..158d5ed60e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,23 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; - +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import java.util.Optional; - - public interface ResourceTranslation { - //return the Id of translated object (NodeTemplate, RelationshipTemplate and etc) - Optional translateResource(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, - TranslationContext context); + //return the Id of translated object (NodeTemplate, RelationshipTemplate and etc) + Optional translateResource(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource resource, String resourceId, TranslationContext context); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java index d5157debce..50607b9b35 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; - +import java.util.Map; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.core.utilities.CommonMethods; @@ -28,49 +27,43 @@ import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; -import java.util.Map; - - public class ResourceTranslationFactory { - private static Map resourceTranslationImplMap; - static { - Configuration config = ConfigurationManager.lookup(); - resourceTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, - ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); - resourceTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, - ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); - } + private static Map resourceTranslationImplMap; - /** - * Gets resource translation instance. - * - * @param resource the resource - * @return the instance - */ - public static ResourceTranslationBase getInstance(Resource resource) { - if (isSupportedResource(resource.getType())) { - return getResourceTranslationImpl(resource.getType()); - } else if (HeatToToscaUtil.isYmlFileType(resource.getType())) { - return getResourceTranslationImpl(ConfigConstants.NESTED_RESOURCE_TRANSLATION_IMPL_KEY); + static { + Configuration config = ConfigurationManager.lookup(); + resourceTranslationImplMap = config + .populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + resourceTranslationImplMap.putAll(config + .populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, + ImplementationConfiguration.class)); } - return getResourceTranslationImpl(ConfigConstants.DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY); - } - private static ResourceTranslationBase getResourceTranslationImpl(String resourceImplKey) { - String resourceTranslationImplClassName = resourceTranslationImplMap - .get(resourceImplKey).getImplementationClass(); - return CommonMethods - .newInstance(resourceTranslationImplClassName, ResourceTranslationBase.class); - } + /** + * Gets resource translation instance. + * + * @param resource the resource + * @return the instance + */ + public static ResourceTranslationBase getInstance(Resource resource) { + if (isSupportedResource(resource.getType())) { + return getResourceTranslationImpl(resource.getType()); + } else if (HeatToToscaUtil.isYmlFileType(resource.getType())) { + return getResourceTranslationImpl(ConfigConstants.NESTED_RESOURCE_TRANSLATION_IMPL_KEY); + } + return getResourceTranslationImpl(ConfigConstants.DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY); + } - private static boolean isSupportedResource(String resourceType) { - if (resourceTranslationImplMap.containsKey(resourceType) - && resourceTranslationImplMap.get(resourceType).isEnable()) { - return true; + private static ResourceTranslationBase getResourceTranslationImpl(String resourceImplKey) { + String resourceTranslationImplClassName = resourceTranslationImplMap.get(resourceImplKey).getImplementationClass(); + return CommonMethods.newInstance(resourceTranslationImplClassName, ResourceTranslationBase.class); } - return false; - } + private static boolean isSupportedResource(String resourceType) { + if (resourceTranslationImplMap.containsKey(resourceType) && resourceTranslationImplMap.get(resourceType).isEnable()) { + return true; + } + return false; + } } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java index 6d22a3602c..0547ec730b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import java.util.ArrayList; @@ -24,10 +23,13 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.GroupDefinition; +import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; +import org.onap.sdc.tosca.datatypes.model.PropertyType; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.onap.sdc.tosca.datatypes.model.TopologyTemplate; import org.onap.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.core.translator.datatypes.TranslatorOutput; @@ -85,14 +87,13 @@ public class TranslationService { public TranslatorOutput translateHeatFiles(TranslationContext translationContext) { ServiceTemplate mainServiceTemplate = createMainServiceTemplate(translationContext); List fileDataList = translationContext.getManifest().getContent().getData(); - FileDataCollection fileDataCollection = HeatToToscaUtil.getFileCollectionsByFilter(fileDataList, - TranslationService.getTypesToProcessByTranslator(), translationContext); - FileDataCollection fileDataCollectionHelm = HeatToToscaUtil.getFileCollectionsByHelmFilter(fileDataList, - TranslationService.getTypesToProcessByHelmTranslator()); - + FileDataCollection fileDataCollection = HeatToToscaUtil + .getFileCollectionsByFilter(fileDataList, TranslationService.getTypesToProcessByTranslator(), translationContext); + FileDataCollection fileDataCollectionHelm = HeatToToscaUtil + .getFileCollectionsByHelmFilter(fileDataList, TranslationService.getTypesToProcessByHelmTranslator()); if (fileDataCollection.getBaseFile() != null) { for (FileData fileData : fileDataCollection.getBaseFile()) { - translateHeatFile(mainServiceTemplate, fileData, translationContext); + translateHeatFile(mainServiceTemplate, fileData, translationContext); } } if (fileDataCollection.getAddOnFiles() != null) { @@ -100,30 +101,24 @@ public class TranslationService { translateHeatFile(mainServiceTemplate, fileData, translationContext); } } - - if (fileDataCollectionHelm.getHelmFile() !=null) { + if (fileDataCollectionHelm.getHelmFile() != null) { for (FileData fileData : fileDataCollectionHelm.getHelmFile()) { translateHelmFile(mainServiceTemplate, fileData, translationContext); - } } - - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); - + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); TranslatorOutput translatorOutput = new TranslatorOutput(); //Keeping a copy of tosca service model after first stage of translation for extraction of + // composition data - translatorOutput.setNonUnifiedToscaServiceModel( - ToscaServiceModel.getClonedServiceModel(toscaServiceModel)); + translatorOutput.setNonUnifiedToscaServiceModel(ToscaServiceModel.getClonedServiceModel(toscaServiceModel)); translatorOutput.setToscaServiceModel(toscaServiceModel); return translatorOutput; } private ServiceTemplate createMainServiceTemplate(TranslationContext translationContext) { ServiceTemplate mainServiceTemplate = new ServiceTemplate(); - translationContext.getTranslatedServiceTemplates() - .put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); + translationContext.getTranslatedServiceTemplates().put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); Map templateMetadata = new HashMap<>(); templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); mainServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); @@ -140,50 +135,37 @@ public class TranslationService { * @param heatFileData the heat file data * @param context the context */ - public void translateHeatFile(ServiceTemplate serviceTemplate, FileData heatFileData, - TranslationContext context) { + public void translateHeatFile(ServiceTemplate serviceTemplate, FileData heatFileData, TranslationContext context) { String heatFileName = heatFileData.getFile(); HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFileContentAsStream(heatFileName), HeatOrchestrationTemplate.class); - - translateInputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, context, - heatFileName); - + .yamlToObject(context.getFileContentAsStream(heatFileName), HeatOrchestrationTemplate.class); + translateInputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, context, heatFileName); translateResources(heatFileName, serviceTemplate, heatOrchestrationTemplate, context); - translateOutputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, - heatFileName, context); + translateOutputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, heatFileName, context); createHeatStackGroup(serviceTemplate, heatFileData, heatOrchestrationTemplate, context); handleHeatPseudoParam(heatFileName, serviceTemplate, context); if (Objects.nonNull(heatFileData.getData())) { heatFileData.getData().stream().filter(data -> FileData.Type.canBeAssociated(data.getType())) - .forEach(data -> translateHeatFile(serviceTemplate, data, context)); + .forEach(data -> translateHeatFile(serviceTemplate, data, context)); } } - - public void translateHelmFile(ServiceTemplate serviceTemplate, FileData heatFileData, - TranslationContext context) { + public void translateHelmFile(ServiceTemplate serviceTemplate, FileData heatFileData, TranslationContext context) { String heatFileName = heatFileData.getFile(); Map inputs = serviceTemplate.getTopology_template().getInputs(); if (!Objects.isNull(inputs)) { - - inputs.entrySet().forEach( - stringParameterDefinitionEntry -> { - List inputParamVFModuleList = getVFModulesList( - inputs.get(stringParameterDefinitionEntry.getKey())); - if (!inputParamVFModuleList.contains(FileUtils.getFileWithoutExtention(heatFileName)) ){ - inputParamVFModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); - } - } - ); + inputs.entrySet().forEach(stringParameterDefinitionEntry -> { + List inputParamVFModuleList = getVFModulesList(inputs.get(stringParameterDefinitionEntry.getKey())); + if (!inputParamVFModuleList.contains(FileUtils.getFileWithoutExtention(heatFileName))) { + inputParamVFModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); + } + }); } inputs.putAll(inputs); } - private void handleHeatPseudoParam(String heatFileName, ServiceTemplate serviceTemplate, - TranslationContext context) { - Map translatedHeatPseudoParam = - context.getUsedHeatPseudoParams().get(heatFileName); + private void handleHeatPseudoParam(String heatFileName, ServiceTemplate serviceTemplate, TranslationContext context) { + Map translatedHeatPseudoParam = context.getUsedHeatPseudoParams().get(heatFileName); if (Objects.nonNull(translatedHeatPseudoParam)) { for (String heatPseudoParam : translatedHeatPseudoParam.keySet()) { if (!serviceTemplate.getTopology_template().getInputs().containsKey(heatPseudoParam)) { @@ -191,54 +173,41 @@ public class TranslationService { parameterDefinition.setType(PropertyType.STRING.getDisplayName()); parameterDefinition.setRequired(false); String parameterDefinitionId = translatedHeatPseudoParam.get(heatPseudoParam); - DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterDefinitionId, - parameterDefinition); + DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterDefinitionId, parameterDefinition); } } } } - private void createHeatStackGroup(ServiceTemplate serviceTemplate, FileData heatFileData, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void createHeatStackGroup(ServiceTemplate serviceTemplate, FileData heatFileData, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); final String fileName = heatFileData.getFile(); final String heatStackGroupId = FileUtils.getFileWithoutExtention(fileName) + "_group"; - GroupDefinition groupDefinition = new GroupDefinition(); groupDefinition.setType(ToscaGroupType.HEAT_STACK); groupDefinition.setProperties(new HashMap<>()); - groupDefinition.getProperties() - .put("heat_file", "../" + toscaFileOutputService.getArtifactsFolderName() + "/" + fileName); + groupDefinition.getProperties().put("heat_file", "../" + toscaFileOutputService.getArtifactsFolderName() + "/" + fileName); String hotDescription = heatOrchestrationTemplate.getDescription(); if (hotDescription != null && !hotDescription.isEmpty()) { groupDefinition.getProperties().put(Constants.DESCRIPTION_PROPERTY_NAME, hotDescription); } groupDefinition.setMembers(new ArrayList<>()); - Set heatStackGroupMembersIds = getHeatStackGroupMembers(fileName, - serviceTemplate, context); + Set heatStackGroupMembersIds = getHeatStackGroupMembers(fileName, serviceTemplate, context); if (CollectionUtils.isEmpty(heatStackGroupMembersIds)) { return; //not creating a group when no resources are present in the heat input } groupDefinition.getMembers().addAll(heatStackGroupMembersIds); - DataModelUtil - .addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupId, groupDefinition); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupId, groupDefinition); } - private Set getHeatStackGroupMembers(String heatFileName, - ServiceTemplate serviceTemplate, - TranslationContext context) { - + private Set getHeatStackGroupMembers(String heatFileName, ServiceTemplate serviceTemplate, TranslationContext context) { Map> heatStackGroupMembers = context.getHeatStackGroupMembers(); - Set groupMembers = MapUtils.isEmpty(heatStackGroupMembers) ? new HashSet<>() - : heatStackGroupMembers.get(heatFileName); - + Set groupMembers = MapUtils.isEmpty(heatStackGroupMembers) ? new HashSet<>() : heatStackGroupMembers.get(heatFileName); if (CollectionUtils.isEmpty(groupMembers)) { return new HashSet<>(); } - Set updatedMembersIds = new HashSet<>(); - groupMembers.forEach(member -> { if (Objects.nonNull(DataModelUtil.getNodeTemplate(serviceTemplate, member))) { updatedMembersIds.add(member); @@ -246,33 +215,24 @@ public class TranslationService { updateSubstitutableGroupMemberId(heatFileName, serviceTemplate, updatedMembersIds); } }); - return updatedMembersIds; } - private void updateSubstitutableGroupMemberId(String heatFileName, - ServiceTemplate serviceTemplate, - Set updatedMembersIds) { - Optional substitutableGroupMemberId = - ToscaUtil.getSubstitutableGroupMemberId(heatFileName, serviceTemplate); - + private void updateSubstitutableGroupMemberId(String heatFileName, ServiceTemplate serviceTemplate, Set updatedMembersIds) { + Optional substitutableGroupMemberId = ToscaUtil.getSubstitutableGroupMemberId(heatFileName, serviceTemplate); substitutableGroupMemberId.ifPresent(updatedMembersIds::add); } - private void translateInputParameters(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - FileData heatFileData, TranslationContext context, - String heatFileName) { + private void translateInputParameters(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, FileData heatFileData, + TranslationContext context, String heatFileName) { if (heatOrchestrationTemplate.getParameters() == null) { return; } - final Environment heatEnvFile = getHeatEnvFile(heatFileData, context); final Map parameters = heatEnvFile.getParameters(); - Map parameterDefinitionMap = - TranslatorHeatToToscaParameterConverter - .parameterConverter(serviceTemplate, heatOrchestrationTemplate.getParameters(), - heatOrchestrationTemplate, heatFileName, heatFileData.getParentFile(), context, parameters); + Map parameterDefinitionMap = TranslatorHeatToToscaParameterConverter + .parameterConverter(serviceTemplate, heatOrchestrationTemplate.getParameters(), heatOrchestrationTemplate, heatFileName, + heatFileData.getParentFile(), context, parameters); Object parameterValue; if (parameters != null) { for (Map.Entry entry : parameterDefinitionMap.entrySet()) { @@ -280,45 +240,35 @@ public class TranslationService { parameterValue = parameters.get(paramName); if (parameterValue != null) { entry.getValue().set_default(TranslatorHeatToToscaParameterConverter - .getToscaParameterDefaultValue(null, null, parameterValue, entry.getValue().getType(), - heatFileName, heatOrchestrationTemplate, context)); + .getToscaParameterDefaultValue(null, null, parameterValue, entry.getValue().getType(), heatFileName, + heatOrchestrationTemplate, context)); } } } - - Map inputs = serviceTemplate.getTopology_template().getInputs(); if (Objects.isNull(inputs)) { serviceTemplate.getTopology_template().setInputs(parameterDefinitionMap); } else { setInputs(inputs, parameterDefinitionMap); - } - } private void setInputs(Map inputs, Map newParameters) { - updateAnnotations(inputs, newParameters); inputs.putAll(newParameters); - } - private void updateAnnotations(Map inputParameters, Map newParameters) { - newParameters.entrySet().stream().filter(stringParameterDefinitionEntry -> - inputParameters.containsKey(stringParameterDefinitionEntry.getKey()) - && isHasAnnotation(inputParameters, stringParameterDefinitionEntry)) - .forEach(stringParameterDefinitionEntry -> { - List inputParamVFModuleList = getVFModulesList( - inputParameters.get(stringParameterDefinitionEntry.getKey())); - List newParamVFModuleList = getVFModulesList(stringParameterDefinitionEntry.getValue()); - if (inputParamVFModuleList.contains(newParamVFModuleList.get(0))) { - newParamVFModuleList.remove(0); - } - newParamVFModuleList.addAll(inputParamVFModuleList); - }); - + private void updateAnnotations(Map inputParameters, Map newParameters) { + newParameters.entrySet().stream().filter( + stringParameterDefinitionEntry -> inputParameters.containsKey(stringParameterDefinitionEntry.getKey()) && isHasAnnotation(inputParameters, + stringParameterDefinitionEntry)).forEach(stringParameterDefinitionEntry -> { + List inputParamVFModuleList = getVFModulesList(inputParameters.get(stringParameterDefinitionEntry.getKey())); + List newParamVFModuleList = getVFModulesList(stringParameterDefinitionEntry.getValue()); + if (inputParamVFModuleList.contains(newParamVFModuleList.get(0))) { + newParamVFModuleList.remove(0); + } + newParamVFModuleList.addAll(inputParamVFModuleList); + }); } private boolean isHasAnnotation(Map inputParameters, Map.Entry newParameterSet) { @@ -329,91 +279,74 @@ public class TranslationService { private List getVFModulesList(ParameterDefinition param) { ParameterDefinitionExt parameterDefinitionExt = (ParameterDefinitionExt) param; - return (List) parameterDefinitionExt.getAnnotations().get(ToscaConstants.SOURCE_ANNOTATION_ID).getProperties(). - get(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME); + return (List) parameterDefinitionExt.getAnnotations().get(ToscaConstants.SOURCE_ANNOTATION_ID).getProperties() + .get(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME); } - private void translateOutputParameters(ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - FileData heatFileData, String heatFileName, - TranslationContext context) { + private void translateOutputParameters(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, + FileData heatFileData, String heatFileName, TranslationContext context) { if (heatOrchestrationTemplate.getOutputs() == null) { return; } - Map parameterDefinitionMap = - TranslatorHeatToToscaParameterConverter - .parameterOutputConverter(serviceTemplate, heatOrchestrationTemplate.getOutputs(), - heatOrchestrationTemplate, heatFileName, context); + Map parameterDefinitionMap = TranslatorHeatToToscaParameterConverter + .parameterOutputConverter(serviceTemplate, heatOrchestrationTemplate.getOutputs(), heatOrchestrationTemplate, heatFileName, context); if (serviceTemplate.getTopology_template().getOutputs() != null) { serviceTemplate.getTopology_template().getOutputs().putAll(parameterDefinitionMap); } else { serviceTemplate.getTopology_template().setOutputs(parameterDefinitionMap); } - if (heatFileData.getBase() != null && heatFileData.getBase().equals(true)) { - updateSharedResources(serviceTemplate, heatFileName, heatOrchestrationTemplate, - heatOrchestrationTemplate.getOutputs(), context); + updateSharedResources(serviceTemplate, heatFileName, heatOrchestrationTemplate, heatOrchestrationTemplate.getOutputs(), context); } } - private void updateSharedResources(ServiceTemplate serviceTemplate, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void updateSharedResources(ServiceTemplate serviceTemplate, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Map outputs, TranslationContext context) { for (Map.Entry parameter : outputs.entrySet()) { Optional attachedSharedResourceId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, - parameter.getValue().getValue()); + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, parameter.getValue().getValue()); if (attachedSharedResourceId.isPresent() && attachedSharedResourceId.get().isGetResource() - && attachedSharedResourceId.get().getTranslatedId() != null) { - String sharedTranslatedResourceId = - attachedSharedResourceId.get().getTranslatedId().toString(); + && attachedSharedResourceId.get().getTranslatedId() != null) { + String sharedTranslatedResourceId = attachedSharedResourceId.get().getTranslatedId().toString(); updateSharedResource(serviceTemplate, context, parameter, sharedTranslatedResourceId, - heatOrchestrationTemplate.getResources() - .get(attachedSharedResourceId.get().getEntityId())); + heatOrchestrationTemplate.getResources().get(attachedSharedResourceId.get().getEntityId())); } else { Optional contrailSharedResourceId = HeatToToscaUtil - .extractContrailGetResourceAttachedHeatResourceId(parameter.getValue().getValue()); + .extractContrailGetResourceAttachedHeatResourceId(parameter.getValue().getValue()); if (contrailSharedResourceId.isPresent() - && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()) - != null) { - String sharedTranslatedResourceId = context.getTranslatedIds().get(heatFileName).get - (contrailSharedResourceId.get()); - ConsolidationDataUtil.removeSharedResource(serviceTemplate, heatOrchestrationTemplate, - context, parameter.getKey(), contrailSharedResourceId.get(), sharedTranslatedResourceId); + && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()) != null) { + String sharedTranslatedResourceId = context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()); + ConsolidationDataUtil + .removeSharedResource(serviceTemplate, heatOrchestrationTemplate, context, parameter.getKey(), contrailSharedResourceId.get(), + sharedTranslatedResourceId); updateSharedResource(serviceTemplate, context, parameter, sharedTranslatedResourceId, - heatOrchestrationTemplate.getResources().get(contrailSharedResourceId.get())); + heatOrchestrationTemplate.getResources().get(contrailSharedResourceId.get())); } } } - if (serviceTemplate.getTopology_template().getOutputs() != null - && serviceTemplate.getTopology_template().getOutputs().size() == 0) { + if (serviceTemplate.getTopology_template().getOutputs() != null && serviceTemplate.getTopology_template().getOutputs().size() == 0) { serviceTemplate.getTopology_template().setOutputs(null); } } - private void updateSharedResource(ServiceTemplate serviceTemplate, TranslationContext context, - Map.Entry paramName, + private void updateSharedResource(ServiceTemplate serviceTemplate, TranslationContext context, Map.Entry paramName, String sharedTranslatedResourceId, Resource resource) { context.addHeatSharedResourcesByParam(paramName.getKey(), sharedTranslatedResourceId, resource); serviceTemplate.getTopology_template().getOutputs().remove(paramName.getKey()); } - private void translateResources(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void translateResources(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { return; } - for (String resourceId : heatOrchestrationTemplate.getResources().keySet()) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } ResourceTranslationFactory.getInstance(resource) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, - resourceId, context); + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, resourceId, context); } } @@ -424,12 +357,9 @@ public class TranslationService { } for (FileData fileRelatedData : fileRelatedDataList) { if (fileRelatedData.getType().equals(FileData.Type.HEAT_ENV)) { - return new YamlUtil().yamlToObject(context.getFileContentAsStream(fileRelatedData.getFile()), - Environment.class); + return new YamlUtil().yamlToObject(context.getFileContentAsStream(fileRelatedData.getFile()), Environment.class); } } return new Environment(); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java index 40e88ebdd5..dfe549679c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca; +import java.util.List; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import java.util.List; - public interface UnifiedComposition { - void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedComposotionDataList, - TranslationContext context); - - + void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedComposotionDataList, TranslationContext context); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java index e057c7f17f..03bfd827cd 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java @@ -19,6 +19,9 @@ */ package org.openecomp.sdc.translator.services.heattotosca; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -29,97 +32,74 @@ import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class UnifiedCompositionManager { - private ConsolidationService consolidationService; - private TranslationService translationService = new TranslationService(); - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - public UnifiedCompositionManager(ConsolidationService consolidationService) { - this.consolidationService = consolidationService; - } + private ConsolidationService consolidationService; + private TranslationService translationService = new TranslationService(); + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - public UnifiedCompositionManager() { + public UnifiedCompositionManager(ConsolidationService consolidationService) { + this.consolidationService = consolidationService; + } - } + public UnifiedCompositionManager() { + } - /** - * Create unified composition. - * - * @param toscaServiceModel the tosca service model - * @param translationContext the translation context - * @return the tosca service model - */ - public ToscaServiceModel createUnifiedComposition(ToscaServiceModel toscaServiceModel, - TranslationContext translationContext) { - Map serviceTemplates = toscaServiceModel.getServiceTemplates(); - ServiceTemplate mainServiceTemplate = - serviceTemplates.get(toscaServiceModel.getEntryDefinitionServiceTemplate()); - createUnifiedComposition(toscaServiceModel, mainServiceTemplate, translationContext); - ToscaServiceModel unifiedToscaServiceModel = - HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); - return unifiedToscaServiceModel; - } + /** + * Create unified composition. + * + * @param toscaServiceModel the tosca service model + * @param translationContext the translation context + * @return the tosca service model + */ + public ToscaServiceModel createUnifiedComposition(ToscaServiceModel toscaServiceModel, TranslationContext translationContext) { + Map serviceTemplates = toscaServiceModel.getServiceTemplates(); + ServiceTemplate mainServiceTemplate = serviceTemplates.get(toscaServiceModel.getEntryDefinitionServiceTemplate()); + createUnifiedComposition(toscaServiceModel, mainServiceTemplate, translationContext); + ToscaServiceModel unifiedToscaServiceModel = HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); + return unifiedToscaServiceModel; + } - private void createUnifiedComposition(ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - handleNestedServiceTemplates(toscaServiceModel, serviceTemplate, translationContext); - consolidationService.serviceTemplateConsolidation(serviceTemplate, translationContext); - unifiedCompositionService - .updateUnifiedAbstractNodesConnectivity(serviceTemplate, translationContext); - translationContext.addUnifiedHandledServiceTeamplte(serviceTemplate); - } + private void createUnifiedComposition(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + TranslationContext translationContext) { + handleNestedServiceTemplates(toscaServiceModel, serviceTemplate, translationContext); + consolidationService.serviceTemplateConsolidation(serviceTemplate, translationContext); + unifiedCompositionService.updateUnifiedAbstractNodesConnectivity(serviceTemplate, translationContext); + translationContext.addUnifiedHandledServiceTeamplte(serviceTemplate); + } - private void handleNestedServiceTemplates(ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - TranslationContext translationContext) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - FileNestedConsolidationData fileNestedConsolidationData = - translationContext.getConsolidationData().getNestedConsolidationData() + private void handleNestedServiceTemplates(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + TranslationContext translationContext) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + FileNestedConsolidationData fileNestedConsolidationData = translationContext.getConsolidationData().getNestedConsolidationData() .getFileNestedConsolidationData(serviceTemplateFileName); - - if (Objects.nonNull(fileNestedConsolidationData)) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - for (String substitutedNodeTemplateId : fileNestedConsolidationData - .getAllNestedNodeTemplateIds()) { - NodeTemplate nestedNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, substitutedNodeTemplateId); - if (Objects.isNull(nestedNodeTemplate) || translationContext - .isNestedNodeWasHandled(serviceTemplateFileName, substitutedNodeTemplateId)) { - continue; + if (Objects.nonNull(fileNestedConsolidationData)) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + for (String substitutedNodeTemplateId : fileNestedConsolidationData.getAllNestedNodeTemplateIds()) { + NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, substitutedNodeTemplateId); + if (Objects.isNull(nestedNodeTemplate) || translationContext + .isNestedNodeWasHandled(serviceTemplateFileName, substitutedNodeTemplateId)) { + continue; + } + Optional substituteServiceTemplateName = toscaAnalyzerService + .getSubstituteServiceTemplateName(substitutedNodeTemplateId, nestedNodeTemplate); + if (substituteServiceTemplateName.isPresent()) { + ServiceTemplate substitutionServiceTemplate = toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateName.get()); + createUnifiedCompositionForNestedServiceTemplate(toscaServiceModel, serviceTemplate, substitutionServiceTemplate, + substitutedNodeTemplateId, translationContext); + } + translationContext.addNestedNodeAsHandled(serviceTemplateFileName, substitutedNodeTemplateId); + } } - Optional substituteServiceTemplateName = - toscaAnalyzerService.getSubstituteServiceTemplateName(substitutedNodeTemplateId, - nestedNodeTemplate); - if (substituteServiceTemplateName.isPresent()) { - ServiceTemplate substitutionServiceTemplate = - toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateName.get()); - createUnifiedCompositionForNestedServiceTemplate(toscaServiceModel, serviceTemplate, - substitutionServiceTemplate, substitutedNodeTemplateId, translationContext); - } - translationContext.addNestedNodeAsHandled(serviceTemplateFileName, - substitutedNodeTemplateId); - } } - } - private void createUnifiedCompositionForNestedServiceTemplate( - ToscaServiceModel toscaServiceModel, - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - String substitutedNodeTemplateId, - TranslationContext translationContext) { - handleNestedServiceTemplates(toscaServiceModel, substitutionServiceTemplate, - translationContext); - consolidationService.substitutionServiceTemplateConsolidation(substitutedNodeTemplateId, - serviceTemplate, substitutionServiceTemplate, translationContext); - unifiedCompositionService - .updateUnifiedAbstractNodesConnectivity(substitutionServiceTemplate, translationContext); - translationContext.addUnifiedHandledServiceTeamplte(substitutionServiceTemplate); - } + private void createUnifiedCompositionForNestedServiceTemplate(ToscaServiceModel toscaServiceModel, ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, String substitutedNodeTemplateId, + TranslationContext translationContext) { + handleNestedServiceTemplates(toscaServiceModel, substitutionServiceTemplate, translationContext); + consolidationService + .substitutionServiceTemplateConsolidation(substitutedNodeTemplateId, serviceTemplate, substitutionServiceTemplate, translationContext); + unifiedCompositionService.updateUnifiedAbstractNodesConnectivity(substitutionServiceTemplate, translationContext); + translationContext.addUnifiedHandledServiceTeamplte(substitutionServiceTemplate); + } } - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java index 77b5520a09..88f0b8f313 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import static org.openecomp.sdc.tosca.datatypes.ToscaFunctions.GET_INPUT; @@ -31,19 +30,18 @@ import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_I import static org.openecomp.sdc.translator.services.heattotosca.Constants.SUB_INTERFACE_PROPERTY_VALUE_PREFIX; import static org.openecomp.sdc.translator.services.heattotosca.Constants.SUB_INTERFACE_ROLE; import static org.openecomp.sdc.translator.services.heattotosca.Constants.VFC_PARENT_PORT_ROLE; -import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getPortTemplateConsolidationDataForPort; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getComputeTypeSuffix; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getConnectedComputeConsolidationData; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewComputeNodeTemplateId; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewPortNodeTemplateId; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getNewSubInterfaceNodeTemplateId; +import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getPortTemplateConsolidationDataForPort; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getSubInterfaceTemplateConsolidationDataList; import static org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionUtil.getSubInterfaceTypeSuffix; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Multimap; - import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; @@ -57,7 +55,6 @@ import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Collectors; - import org.apache.commons.collections.map.HashedMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; @@ -116,1177 +113,856 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida public class UnifiedCompositionService { - private static final Map unifiedCompositionImplMap; - - private static final EnumMap unifiedSubstitutionNodeTemplateIdGeneratorImplMap; - private static final String SUB_INTERFACE_INDICATOR_PROPERTY = "subinterface_indicator"; - private final ConsolidationService consolidationService = new ConsolidationService(); - - static { - Configuration config = ConfigurationManager.lookup(); - unifiedCompositionImplMap = - config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, - ConfigConstants.UNIFIED_COMPOSITION_IMPL_KEY, ImplementationConfiguration.class); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap = new EnumMap<>(UnifiedCompositionEntity.class); - initNodeTemplateIdGeneratorImplMap(); - } - - private static void initNodeTemplateIdGeneratorImplMap() { - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(COMPUTE, CommandImplNames - .COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(PORT, CommandImplNames - .PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(SUB_INTERFACE, CommandImplNames - .SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); - } - - private static List getPortConsolidationDataList( - List portIds, - List unifiedCompositionDataList) { - return unifiedCompositionDataList.stream() + private static final Map unifiedCompositionImplMap; + private static final EnumMap unifiedSubstitutionNodeTemplateIdGeneratorImplMap; + private static final String SUB_INTERFACE_INDICATOR_PROPERTY = "subinterface_indicator"; + + static { + Configuration config = ConfigurationManager.lookup(); + unifiedCompositionImplMap = config + .populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants.UNIFIED_COMPOSITION_IMPL_KEY, + ImplementationConfiguration.class); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap = new EnumMap<>(UnifiedCompositionEntity.class); + initNodeTemplateIdGeneratorImplMap(); + } + + private final ConsolidationService consolidationService = new ConsolidationService(); + + private static void initNodeTemplateIdGeneratorImplMap() { + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(COMPUTE, CommandImplNames.COMPUTE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(PORT, CommandImplNames.PORT_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + unifiedSubstitutionNodeTemplateIdGeneratorImplMap.put(SUB_INTERFACE, CommandImplNames.SUB_INTERFACE_NEW_NODE_TEMPLATE_ID_GENERATOR_IMPL); + } + + private static List getPortConsolidationDataList(List portIds, + List unifiedCompositionDataList) { + return unifiedCompositionDataList.stream() .flatMap(unifiedCompositionData -> unifiedCompositionData.getPortTemplateConsolidationDataList().stream()) .filter(portTemplateConsolidationData -> portIds.contains(portTemplateConsolidationData.getNodeTemplateId())) .collect(Collectors.toList()); - } - - /** - * Create unified composition. - * - * @param serviceTemplate the service template - * @param nestedServiceTemplate the nested service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param mode the mode - * @param context the context - */ - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedCompositionDataList, - UnifiedCompositionMode mode, TranslationContext context) { - Optional unifiedCompositionInstance = getUnifiedCompositionInstance(mode); - if (!unifiedCompositionInstance.isPresent()) { - return; - } - unifiedCompositionInstance.get() - .createUnifiedComposition(serviceTemplate, nestedServiceTemplate, - unifiedCompositionDataList, context); - } - - /** - * Create unified substitution service template according to the input service template, based on - * the unified composition data. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - * @return the substitution service template - */ - public Optional createUnifiedSubstitutionServiceTemplate( - ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - TranslationContext context, - String substitutionNodeTypeId, - Integer index) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { - return Optional.empty(); - } - String templateName = getTemplateName(substitutionNodeTypeId, index); - ServiceTemplate substitutionServiceTemplate = - HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); - - createIndexInputParameter(substitutionServiceTemplate); - - String computeNodeType = - handleCompute(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - context); - handlePorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, - computeNodeType, context); - - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, - substitutionServiceTemplate, unifiedCompositionDataList, context, null); - handleSubInterfaces(unifiedCompositionTo); - createOutputParameters(unifiedCompositionTo, computeNodeType); - NodeType substitutionGlobalNodeType = - handleSubstitutionGlobalNodeType(serviceTemplate, substitutionServiceTemplate, - context, substitutionNodeTypeId); - - HeatToToscaUtil.handleSubstitutionMapping(context, - substitutionNodeTypeId, - substitutionServiceTemplate, substitutionGlobalNodeType); - - context.getTranslatedServiceTemplates().put(templateName, substitutionServiceTemplate); - return Optional.of(substitutionServiceTemplate); - } - - - /** - * Create abstract substitute node template that can be substituted by the input - * substitutionServiceTemplate. - * - * @param serviceTemplate the service template - * @param substitutionServiceTemplate the subtitution service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - * @return the abstract substitute node template id - */ - public String createAbstractSubstituteNodeTemplate( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - String substituteNodeTypeId, - TranslationContext context, - Integer index) { - - NodeTemplate substitutionNodeTemplate = new NodeTemplate(); - List directiveList = new ArrayList<>(); - directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); - substitutionNodeTemplate.setDirectives(directiveList); - substitutionNodeTemplate.setType(substituteNodeTypeId); - Map substitutionTemplateInputs = DataModelUtil - .getInputParameters(substitutionServiceTemplate); - Optional> abstractSubstitutionProperties = Optional.empty(); - if (Objects.nonNull(substitutionTemplateInputs)) { - abstractSubstitutionProperties = createAbstractSubstitutionProperties(serviceTemplate, - substitutionTemplateInputs, unifiedCompositionDataList, context); - } - abstractSubstitutionProperties.ifPresent(substitutionNodeTemplate::setProperties); - - //Add substitution filtering property - String substitutionServiceTemplateName = ToscaUtil.getServiceTemplateFileName( - substitutionServiceTemplate); - int count = unifiedCompositionDataList.size(); - DataModelUtil.addSubstitutionFilteringProperty(substitutionServiceTemplateName, - substitutionNodeTemplate, count); - //Add index_value property - addIndexValueProperty(substitutionNodeTemplate); - String substituteNodeTemplateId = getSubstituteNodeTemplateId(substituteNodeTypeId, index); - //Add node template id and related abstract node template id in context - addUnifiedSubstitionData(context, serviceTemplate, unifiedCompositionDataList, - substituteNodeTemplateId); - DataModelUtil - .addNodeTemplate(serviceTemplate, substituteNodeTemplateId, substitutionNodeTemplate); - return substituteNodeTemplateId; - - } - - public void createVfcInstanceGroup(String abstractNodeTemplateId, - ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - if (!TranslationContext.isVfcInstanceGroupingEnabled()) { - return; - } - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, - unifiedCompositionDataList, context, null); - unifiedCompositionDataList.forEach(unifiedCompositionData -> - createSubInterfaceVfcInstanceGroup(abstractNodeTemplateId, unifiedCompositionTo, unifiedCompositionData)); - } - - private void createSubInterfaceVfcInstanceGroup(String abstractNodeTemplateId, - UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceTemplateConsolidationDataList) { - Optional parentPortNetworkRole; - if (Objects.isNull(unifiedCompositionTo.getSubstitutionServiceTemplate())) { - parentPortNetworkRole = subInterface.getParentPortNetworkRole(unifiedCompositionTo.getServiceTemplate(), + } + + /** + * Create unified composition. + * + * @param serviceTemplate the service template + * @param nestedServiceTemplate the nested service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param mode the mode + * @param context the context + */ + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, UnifiedCompositionMode mode, + TranslationContext context) { + Optional unifiedCompositionInstance = getUnifiedCompositionInstance(mode); + if (!unifiedCompositionInstance.isPresent()) { + return; + } + unifiedCompositionInstance.get().createUnifiedComposition(serviceTemplate, nestedServiceTemplate, unifiedCompositionDataList, context); + } + + /** + * Create unified substitution service template according to the input service template, based on the unified composition data. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + * @return the substitution service template + */ + public Optional createUnifiedSubstitutionServiceTemplate(ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context, String substitutionNodeTypeId, + Integer index) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return Optional.empty(); + } + String templateName = getTemplateName(substitutionNodeTypeId, index); + ServiceTemplate substitutionServiceTemplate = HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + createIndexInputParameter(substitutionServiceTemplate); + String computeNodeType = handleCompute(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, context); + handlePorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, computeNodeType, context); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + context, null); + handleSubInterfaces(unifiedCompositionTo); + createOutputParameters(unifiedCompositionTo, computeNodeType); + NodeType substitutionGlobalNodeType = handleSubstitutionGlobalNodeType(serviceTemplate, substitutionServiceTemplate, context, + substitutionNodeTypeId); + HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeId, substitutionServiceTemplate, substitutionGlobalNodeType); + context.getTranslatedServiceTemplates().put(templateName, substitutionServiceTemplate); + return Optional.of(substitutionServiceTemplate); + } + + /** + * Create abstract substitute node template that can be substituted by the input substitutionServiceTemplate. + * + * @param serviceTemplate the service template + * @param substitutionServiceTemplate the subtitution service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + * @return the abstract substitute node template id + */ + public String createAbstractSubstituteNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, String substituteNodeTypeId, + TranslationContext context, Integer index) { + NodeTemplate substitutionNodeTemplate = new NodeTemplate(); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutionNodeTemplate.setDirectives(directiveList); + substitutionNodeTemplate.setType(substituteNodeTypeId); + Map substitutionTemplateInputs = DataModelUtil.getInputParameters(substitutionServiceTemplate); + Optional> abstractSubstitutionProperties = Optional.empty(); + if (Objects.nonNull(substitutionTemplateInputs)) { + abstractSubstitutionProperties = createAbstractSubstitutionProperties(serviceTemplate, substitutionTemplateInputs, + unifiedCompositionDataList, context); + } + abstractSubstitutionProperties.ifPresent(substitutionNodeTemplate::setProperties); + //Add substitution filtering property + String substitutionServiceTemplateName = ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate); + int count = unifiedCompositionDataList.size(); + DataModelUtil.addSubstitutionFilteringProperty(substitutionServiceTemplateName, substitutionNodeTemplate, count); + //Add index_value property + addIndexValueProperty(substitutionNodeTemplate); + String substituteNodeTemplateId = getSubstituteNodeTemplateId(substituteNodeTypeId, index); + //Add node template id and related abstract node template id in context + addUnifiedSubstitionData(context, serviceTemplate, unifiedCompositionDataList, substituteNodeTemplateId); + DataModelUtil.addNodeTemplate(serviceTemplate, substituteNodeTemplateId, substitutionNodeTemplate); + return substituteNodeTemplateId; + } + + public void createVfcInstanceGroup(String abstractNodeTemplateId, ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + if (!TranslationContext.isVfcInstanceGroupingEnabled()) { + return; + } + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, unifiedCompositionDataList, context, null); + unifiedCompositionDataList.forEach( + unifiedCompositionData -> createSubInterfaceVfcInstanceGroup(abstractNodeTemplateId, unifiedCompositionTo, unifiedCompositionData)); + } + + private void createSubInterfaceVfcInstanceGroup(String abstractNodeTemplateId, UnifiedCompositionTo unifiedCompositionTo, + UnifiedCompositionData unifiedCompositionData) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterface : subInterfaceTemplateConsolidationDataList) { + Optional parentPortNetworkRole; + if (Objects.isNull(unifiedCompositionTo.getSubstitutionServiceTemplate())) { + parentPortNetworkRole = subInterface + .getParentPortNetworkRole(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); + } else { + parentPortNetworkRole = subInterface + .getParentPortNetworkRole(unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); + } + String subInterfaceNetworkRole = subInterface.getNetworkRole(); + if (Objects.nonNull(subInterfaceNetworkRole) && parentPortNetworkRole.isPresent()) { + createVfcInstanceGroupPerSubInterfaceNetworkRole(abstractNodeTemplateId, subInterfaceNetworkRole, parentPortNetworkRole.get(), + unifiedCompositionTo.getServiceTemplate()); + } + } + } + + private void createVfcInstanceGroupPerSubInterfaceNetworkRole(String abstractNodeTemplateId, String subInterfaceNetworkRole, + String parentPortNetworkRole, ServiceTemplate serviceTemplate) { + String vfcNetworkRoleGroupId = getVfcNetworkRoleGroupId(subInterfaceNetworkRole); + Map groups = DataModelUtil.getGroups(serviceTemplate); + if (!groups.containsKey(vfcNetworkRoleGroupId)) { + createNewVfcInstanceGroup(serviceTemplate, parentPortNetworkRole, subInterfaceNetworkRole, vfcNetworkRoleGroupId); + } + DataModelUtil.addGroupMember(serviceTemplate, vfcNetworkRoleGroupId, abstractNodeTemplateId); + } + + private void createNewVfcInstanceGroup(ServiceTemplate serviceTemplate, String parentPortNetworkRole, String subInterfaceNetworkRole, + String vfcNetworkRoleGroupId) { + Map properties = new HashMap<>(); + properties.put(SUB_INTERFACE_ROLE, subInterfaceNetworkRole); + properties.put(VFC_PARENT_PORT_ROLE, parentPortNetworkRole); + updateVfcInstanceGroupExposedProperties(subInterfaceNetworkRole, serviceTemplate, properties); + GroupDefinition groupDefinition = new GroupDefinition(); + groupDefinition.setType(GROUP_TYPE_PREFIX + VFC_INSTANCE_GROUP); + groupDefinition.setProperties(properties); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, vfcNetworkRoleGroupId, groupDefinition); + } + + private void updateVfcInstanceGroupExposedProperties(String subInterfaceNetworkRole, ServiceTemplate serviceTemplate, + Map properties) { + List exposedVfcInstanceGroupingProperties = TranslationContext.getExposedVfcInstanceGroupingProperties(); + if (CollectionUtils.isEmpty(exposedVfcInstanceGroupingProperties)) { + return; + } + for (String propertyName : exposedVfcInstanceGroupingProperties) { + Map getInputMap = new HashMap<>(); + String vfcGroupPropertyInputName = subInterfaceNetworkRole + "_" + propertyName; + getInputMap.put(GET_INPUT.getFunctionName(), vfcGroupPropertyInputName); + properties.put(propertyName, getInputMap); + addInputParameter(vfcGroupPropertyInputName, PropertyType.STRING.getDisplayName(), null, serviceTemplate); + } + } + + private String getVfcNetworkRoleGroupId(String subInterfaceNetworkRole) { + StringBuilder sb = new StringBuilder(); + sb.append(subInterfaceNetworkRole).append("_").append(GROUP); + return sb.toString(); + } + + /** + * Update the connectivity from/to the "moved" nodes from the original service template to the new substitution service template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + */ + public void updateCompositionConnectivity(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + updOutputParamGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedOutConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updVolumeConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updGroupsConnectivity(serviceTemplate, unifiedCompositionDataList, context); + } + + /** + * Delete the "moved" nodes from the original service template to the new substitution service template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, one entry will be in this list, in case of + * having consolidation, all entries in the list are the once which need to be consolidated. + * @param context the translation context + */ + public void cleanUnifiedCompositionEntities(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + //Clean compute node template data from top level service template + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + cleanServiceTemplate(serviceTemplate, computeTemplateConsolidationData, context); + //Clean port node template data from top level service template + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + cleanServiceTemplate(serviceTemplate, portTemplateConsolidationData, context); + } + //Clean sub-interface node template data from top level service template + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + cleanServiceTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, context); + } + } + } + + /** + * Clean node types. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list + * @param context the context + */ + public void cleanNodeTypes(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, TranslationContext context) { + for (UnifiedCompositionData unifiedData : unifiedCompositionDataList) { + removeCleanedNodeType(unifiedData.getComputeTemplateConsolidationData().getNodeTemplateId(), serviceTemplate, context); + } + if (MapUtils.isEmpty(serviceTemplate.getNode_types())) { + serviceTemplate.setNode_types(null); + } + } + + public void updateSubstitutionNodeTypePrefix(ServiceTemplate substitutionServiceTemplate) { + Map nodeTemplates = substitutionServiceTemplate.getTopology_template().getNode_templates(); + for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) { + String nodeTypeId = nodeTemplateEntry.getValue().getType(); + NodeType origNodeType = substitutionServiceTemplate.getNode_types().get(nodeTypeId); + if (Objects.nonNull(origNodeType) && nodeTypeId.startsWith(ToscaNodeType.VFC_TYPE_PREFIX) && origNodeType.getDerived_from() + .equals(ToscaNodeType.NOVA_SERVER)) { + substitutionServiceTemplate.getNode_types().remove(nodeTypeId); + String newNodeTypeId = nodeTypeId.replace(ToscaNodeType.VFC_TYPE_PREFIX, ToscaNodeType.COMPUTE_TYPE_PREFIX); + nodeTemplateEntry.getValue().setType(newNodeTypeId); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue()); + substitutionServiceTemplate.getNode_types().put(newNodeTypeId, origNodeType); + } + } + } + + /** + * Update unified abstract nodes connectivity. + * + * @param serviceTemplate the service template + * @param context the context + */ + public void updateUnifiedAbstractNodesConnectivity(ServiceTemplate serviceTemplate, TranslationContext context) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData().get(serviceTemplateFileName); + if (Objects.nonNull(unifiedSubstitutionData)) { + //Handle get attribute in connectivity for abstarct node to abstract node templates + Set abstractNodeIds = new HashSet<>(unifiedSubstitutionData.getAllRelatedAbstractNodeIds()); + handleGetAttrInConnectivity(serviceTemplate, abstractNodeIds, context); + //Handle get attribute in connectivity for abstract node templates to nested node template + Set nestedNodeIds = new HashSet<>(unifiedSubstitutionData.getAllUnifiedNestedNodeTemplateIds()); + handleGetAttrInConnectivity(serviceTemplate, nestedNodeIds, context); + } + } + + /** + * Handle unified nested definition. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void handleUnifiedNestedDefinition(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + handleUnifiedNestedNodeType(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - } else { - parentPortNetworkRole = subInterface.getParentPortNetworkRole(unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - } - String subInterfaceNetworkRole = subInterface.getNetworkRole(); - if (Objects.nonNull(subInterfaceNetworkRole) && parentPortNetworkRole.isPresent()) { - createVfcInstanceGroupPerSubInterfaceNetworkRole(abstractNodeTemplateId, subInterfaceNetworkRole, - parentPortNetworkRole.get(), unifiedCompositionTo.getServiceTemplate()); - } - } - } - - private void createVfcInstanceGroupPerSubInterfaceNetworkRole(String abstractNodeTemplateId, - String subInterfaceNetworkRole, - String parentPortNetworkRole, - ServiceTemplate serviceTemplate) { - String vfcNetworkRoleGroupId = getVfcNetworkRoleGroupId(subInterfaceNetworkRole); - Map groups = DataModelUtil.getGroups(serviceTemplate); - if (!groups.containsKey(vfcNetworkRoleGroupId)) { - createNewVfcInstanceGroup(serviceTemplate, parentPortNetworkRole, subInterfaceNetworkRole, vfcNetworkRoleGroupId); - } - DataModelUtil.addGroupMember(serviceTemplate, vfcNetworkRoleGroupId, abstractNodeTemplateId); - } - - private void createNewVfcInstanceGroup(ServiceTemplate serviceTemplate, - String parentPortNetworkRole, - String subInterfaceNetworkRole, - String vfcNetworkRoleGroupId) { - Map properties = new HashMap<>(); - properties.put(SUB_INTERFACE_ROLE, subInterfaceNetworkRole); - properties.put(VFC_PARENT_PORT_ROLE, parentPortNetworkRole); - - updateVfcInstanceGroupExposedProperties(subInterfaceNetworkRole, - serviceTemplate, properties); - - GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setType(GROUP_TYPE_PREFIX + VFC_INSTANCE_GROUP); - groupDefinition.setProperties(properties); - - DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, - vfcNetworkRoleGroupId, groupDefinition); - } - - private void updateVfcInstanceGroupExposedProperties(String subInterfaceNetworkRole, - ServiceTemplate serviceTemplate, - Map properties) { - List exposedVfcInstanceGroupingProperties = - TranslationContext.getExposedVfcInstanceGroupingProperties(); - - if (CollectionUtils.isEmpty(exposedVfcInstanceGroupingProperties)) { - return; - } - - for (String propertyName : exposedVfcInstanceGroupingProperties) { - Map getInputMap = new HashMap<>(); - String vfcGroupPropertyInputName = subInterfaceNetworkRole + "_" + propertyName; - getInputMap.put(GET_INPUT.getFunctionName(), vfcGroupPropertyInputName); - properties.put(propertyName, getInputMap); - - addInputParameter(vfcGroupPropertyInputName, PropertyType.STRING.getDisplayName(), null, - serviceTemplate); - } - } - - private String getVfcNetworkRoleGroupId(String subInterfaceNetworkRole) { - StringBuilder sb = new StringBuilder(); - sb.append(subInterfaceNetworkRole).append("_").append(GROUP); - return sb.toString(); - } - - /** - * Update the connectivity from/to the "moved" nodes from the original service template to the new - * substitution service template. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - */ - public void updateCompositionConnectivity(ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - updOutputParamGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesConnectedOutConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updVolumeConnectivity(serviceTemplate, unifiedCompositionDataList, context); - updGroupsConnectivity(serviceTemplate, unifiedCompositionDataList, context); - } - - /** - * Delete the "moved" nodes from the original service template to the new substitution service - * template. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, - * one entry will be in this list, in case of having - * consolidation, all entries in the list are the once which - * need to be consolidated. - * @param context the translation context - */ - public void cleanUnifiedCompositionEntities( - ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - //Clean compute node template data from top level service template - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - cleanServiceTemplate(serviceTemplate, computeTemplateConsolidationData, context); - - //Clean port node template data from top level service template - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - cleanServiceTemplate(serviceTemplate, portTemplateConsolidationData, context); - } - - //Clean sub-interface node template data from top level service template - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - cleanServiceTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, context); - } - } - } - - /** - * Clean node types. - * - * @param serviceTemplate the service template - * @param unifiedCompositionDataList the unified composition data list - * @param context the context - */ - public void cleanNodeTypes(ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedData : unifiedCompositionDataList) { - removeCleanedNodeType( - unifiedData.getComputeTemplateConsolidationData().getNodeTemplateId(), serviceTemplate, - context); - } - if (MapUtils.isEmpty(serviceTemplate.getNode_types())) { - serviceTemplate.setNode_types(null); - } - } - - public void updateSubstitutionNodeTypePrefix(ServiceTemplate substitutionServiceTemplate) { - Map nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); - - for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) { - String nodeTypeId = nodeTemplateEntry.getValue().getType(); - NodeType origNodeType = substitutionServiceTemplate.getNode_types().get(nodeTypeId); - if (Objects.nonNull(origNodeType) - && nodeTypeId.startsWith(ToscaNodeType.VFC_TYPE_PREFIX) - && origNodeType.getDerived_from().equals(ToscaNodeType.NOVA_SERVER)) { - substitutionServiceTemplate.getNode_types().remove(nodeTypeId); - - String newNodeTypeId = - nodeTypeId.replace(ToscaNodeType.VFC_TYPE_PREFIX, ToscaNodeType.COMPUTE_TYPE_PREFIX); - nodeTemplateEntry.getValue().setType(newNodeTypeId); - DataModelUtil - .addNodeTemplate(substitutionServiceTemplate, nodeTemplateEntry.getKey(), - nodeTemplateEntry.getValue()); - substitutionServiceTemplate.getNode_types().put(newNodeTypeId, origNodeType); - } - } - } - - /** - * Update unified abstract nodes connectivity. - * - * @param serviceTemplate the service template - * @param context the context - */ - public void updateUnifiedAbstractNodesConnectivity(ServiceTemplate serviceTemplate, - TranslationContext context) { + updateUnifiedNestedTemplates(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), + unifiedCompositionData, unifiedCompositionTo.getContext()); + } + + private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, Set unifiedNodeIds, TranslationContext context) { + Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (String unifiedNodeId : unifiedNodeIds) { + NodeTemplate nodeTemplate = nodeTemplates.get(unifiedNodeId); + handleGetAttrInAbstractNodeTemplate(serviceTemplate, context, serviceTemplateFileName, nodeTemplate); + } + } + private void handleUnifiedNestedNodeType(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMappings = nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + String nodeTypeId = substitutionMappings.getNode_type(); + Optional newNestedNodeTypeId = getNewNestedNodeTypeId(nestedServiceTemplate, context); + ServiceTemplate globalSubstitutionServiceTemplate = context.getGlobalSubstitutionServiceTemplate(); + if (isNestedServiceTemplateWasHandled(globalSubstitutionServiceTemplate, nestedServiceTemplate, context, newNestedNodeTypeId)) { + context.updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), newNestedNodeTypeId.get(), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + return; + } + newNestedNodeTypeId.ifPresent( + newNestedNodeTypeIdVal -> handleNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, nestedServiceTemplate, mainServiceTemplate, + globalSubstitutionServiceTemplate, context)); + } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData() - .get(serviceTemplateFileName); - - if (Objects.nonNull(unifiedSubstitutionData)) { - //Handle get attribute in connectivity for abstarct node to abstract node templates - Set abstractNodeIds = - new HashSet<>(unifiedSubstitutionData.getAllRelatedAbstractNodeIds()); - handleGetAttrInConnectivity(serviceTemplate, abstractNodeIds, context); - //Handle get attribute in connectivity for abstract node templates to nested node template - Set nestedNodeIds = - new HashSet<>(unifiedSubstitutionData.getAllUnifiedNestedNodeTemplateIds()); - handleGetAttrInConnectivity(serviceTemplate, nestedNodeIds, context); - } - } - - /** - * Handle unified nested definition. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void handleUnifiedNestedDefinition(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - handleUnifiedNestedNodeType(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionTo.getContext()); - updateUnifiedNestedTemplates(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo - .getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo.getContext()); - } - - private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, - Set unifiedNodeIds, - TranslationContext context) { - Map nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - for (String unifiedNodeId : unifiedNodeIds) { - NodeTemplate nodeTemplate = nodeTemplates.get(unifiedNodeId); - handleGetAttrInAbstractNodeTemplate(serviceTemplate, context, serviceTemplateFileName, - nodeTemplate); - } - } - - private void handleUnifiedNestedNodeType(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - - - SubstitutionMapping substitutionMappings = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); - String nodeTypeId = substitutionMappings.getNode_type(); - - Optional newNestedNodeTypeId = getNewNestedNodeTypeId(nestedServiceTemplate, context); - - ServiceTemplate globalSubstitutionServiceTemplate = - context.getGlobalSubstitutionServiceTemplate(); - - if (isNestedServiceTemplateWasHandled(globalSubstitutionServiceTemplate, nestedServiceTemplate, - context, - newNestedNodeTypeId)) { - context - .updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), - newNestedNodeTypeId.get(), - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - return; - } - - - newNestedNodeTypeId.ifPresent( - newNestedNodeTypeIdVal -> handleNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, - nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, - context)); - - } - - private boolean isNestedServiceTemplateWasHandled(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context, - Optional newNestedNodeTypeId) { - return newNestedNodeTypeId.isPresent() - && context.isNestedServiceTemplateWasHandled( - ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + private boolean isNestedServiceTemplateWasHandled(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, + TranslationContext context, Optional newNestedNodeTypeId) { + return newNestedNodeTypeId.isPresent() && context.isNestedServiceTemplateWasHandled(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - } + } + + private void handleNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + updateNestedServiceTemplate(nestedServiceTemplate, context); + updateNestedNodeType(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, context); + } + + private void updateNestedServiceTemplate(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + enrichPortProperties(nestedServiceTemplate, context); + } + + private void enrichPortProperties(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + String nestedServiceTemplateFileName = ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); + FilePortConsolidationData filePortConsolidationData = context.getConsolidationData().getPortConsolidationData() + .getFilePortConsolidationData(nestedServiceTemplateFileName); + if (Objects.nonNull(filePortConsolidationData)) { + Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + if (Objects.nonNull(portNodeTemplateIds)) { + for (String portNodeTemplateId : portNodeTemplateIds) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(nestedServiceTemplate, portNodeTemplateId); + List portEntityConsolidationDataList = new ArrayList<>(); + portEntityConsolidationDataList.add(filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); + handleNodeTypeProperties(nestedServiceTemplate, portEntityConsolidationDataList, portNodeTemplate, UnifiedCompositionEntity.PORT, + null, context); + //Add subinterface_indicator property to PORT + addPortSubInterfaceIndicatorProperty(portNodeTemplate.getProperties(), + filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); + } + } + } + } + + private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + String indexedNewNestedNodeTypeId = updateNodeTypeId(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, mainServiceTemplate, + globalSubstitutionServiceTemplate, context); + updateNodeTypeProperties(nestedServiceTemplate, globalSubstitutionServiceTemplate, indexedNewNestedNodeTypeId); + } + + private void updateNodeTypeProperties(ServiceTemplate nestedServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, + String nodeTypeId) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Map nodeTypePropertiesDefinition = toscaAnalyzerService + .manageSubstitutionNodeTypeProperties(nestedServiceTemplate); + NodeType nestedNodeType = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, nodeTypeId); + nestedNodeType.setProperties(nodeTypePropertiesDefinition); + } - private void handleNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, + private String updateNodeTypeId(String nodeTypeId, String newNestedNodeTypeId, ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { - updateNestedServiceTemplate(nestedServiceTemplate, context); - updateNestedNodeType(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, - mainServiceTemplate, + String indexedNewNestedNodeTypeId = handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, globalSubstitutionServiceTemplate, context); + handleSubstitutionMappingInNestedServiceTemplate(indexedNewNestedNodeTypeId, nestedServiceTemplate, context); + context.updateHandledComputeType(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), newNestedNodeTypeId); + return indexedNewNestedNodeTypeId; + } + private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, String newNestedNodeTypeId, + ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { + String indexedNodeType = getIndexedGlobalNodeTypeId(newNestedNodeTypeId, context); + context.updateUsedTimesForNestedComputeNodeType(ToscaUtil.getServiceTemplateFileName(globalSubstitutionServiceTemplate), newNestedNodeTypeId); + handleNestedNodeTypesInGlobalSubstituteServiceTemplate(nodeTypeId, indexedNodeType, globalSubstitutionServiceTemplate, context); + return indexedNodeType; + } - } + private String getIndexedGlobalNodeTypeId(String newNestedNodeTypeId, TranslationContext context) { + int globalNodeTypeIndex = context + .getGlobalNodeTypeIndex(ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), newNestedNodeTypeId); + return globalNodeTypeIndex > 0 ? newNestedNodeTypeId + "_" + globalNodeTypeIndex : newNestedNodeTypeId; + } - private void updateNestedServiceTemplate(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - enrichPortProperties(nestedServiceTemplate, context); - } + private void updateUnifiedNestedTemplates(ServiceTemplate mainServiceTemplate, ServiceTemplate nestedServiceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + handleNestedNodeTemplateInMainServiceTemplate(nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, nestedServiceTemplate, + context); + } - private void enrichPortProperties(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - String nestedServiceTemplateFileName = - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); - FilePortConsolidationData filePortConsolidationData = - context.getConsolidationData().getPortConsolidationData().getFilePortConsolidationData - (nestedServiceTemplateFileName); - - if (Objects.nonNull(filePortConsolidationData)) { - Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); - if (Objects.nonNull(portNodeTemplateIds)) { - for (String portNodeTemplateId : portNodeTemplateIds) { - NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(nestedServiceTemplate, - portNodeTemplateId); - List portEntityConsolidationDataList = new ArrayList<>(); - portEntityConsolidationDataList.add(filePortConsolidationData - .getPortTemplateConsolidationData(portNodeTemplateId)); - - handleNodeTypeProperties(nestedServiceTemplate, - portEntityConsolidationDataList, portNodeTemplate, UnifiedCompositionEntity.PORT, - null, context); - //Add subinterface_indicator property to PORT - addPortSubInterfaceIndicatorProperty(portNodeTemplate.getProperties(), - filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId)); - } - } - } - } - - private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNewNestedNodeTypeId = - updateNodeTypeId(nodeTypeId, newNestedNodeTypeId, nestedServiceTemplate, - mainServiceTemplate, - globalSubstitutionServiceTemplate, context); - - updateNodeTypeProperties(nestedServiceTemplate, globalSubstitutionServiceTemplate, - indexedNewNestedNodeTypeId); - } - - private void updateNodeTypeProperties(ServiceTemplate nestedServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - String nodeTypeId) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Map nodeTypePropertiesDefinition = - toscaAnalyzerService.manageSubstitutionNodeTypeProperties(nestedServiceTemplate); - NodeType nestedNodeType = - DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, nodeTypeId); - nestedNodeType.setProperties(nodeTypePropertiesDefinition); - } - - private String updateNodeTypeId(String nodeTypeId, String newNestedNodeTypeId, - ServiceTemplate nestedServiceTemplate, - ServiceTemplate mainServiceTemplate, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNewNestedNodeTypeId = - handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, - globalSubstitutionServiceTemplate, context); - - handleSubstitutionMappingInNestedServiceTemplate(indexedNewNestedNodeTypeId, - nestedServiceTemplate, context); - - context - .updateHandledComputeType( - ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), - newNestedNodeTypeId); - return indexedNewNestedNodeTypeId; - } - - private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, - String newNestedNodeTypeId, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - String indexedNodeType = - getIndexedGlobalNodeTypeId(newNestedNodeTypeId, context); - context.updateUsedTimesForNestedComputeNodeType( - ToscaUtil.getServiceTemplateFileName(globalSubstitutionServiceTemplate), - newNestedNodeTypeId); - handleNestedNodeTypesInGlobalSubstituteServiceTemplate(nodeTypeId, indexedNodeType, - globalSubstitutionServiceTemplate, context); - return indexedNodeType; - } + /** + * Update connectivity for unified nested patterns. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void updateUnifiedNestedConnectivity(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + updNestedCompositionNodesConnectedInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + updNestedCompositionNodesConnectedOutConnectivity(unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo.getContext()); + updNestedCompositionNodesGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + updNestedCompositionOutputParamGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, + unifiedCompositionTo.getContext()); + } - private String getIndexedGlobalNodeTypeId(String newNestedNodeTypeId, - TranslationContext context) { - int globalNodeTypeIndex = - context.getGlobalNodeTypeIndex( - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), - newNestedNodeTypeId); - return globalNodeTypeIndex > 0 ? newNestedNodeTypeId + "_" - + globalNodeTypeIndex : newNestedNodeTypeId; - } - - private void updateUnifiedNestedTemplates(ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { + /** + * Clean unified nested entities. Update the heat stack group with the new node template ids. + * + * @param unifiedCompositionTo the unified composition data transfer object + * @param unifiedCompositionData the unified composition data + */ + public void cleanUnifiedNestedEntities(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionData unifiedCompositionData) { + EntityConsolidationData entityConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + updateHeatStackGroupNestedComposition(unifiedCompositionTo.getServiceTemplate(), entityConsolidationData, unifiedCompositionTo.getContext()); + } - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - handleNestedNodeTemplateInMainServiceTemplate( - nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, - nestedServiceTemplate, context); - } - - /** - * Update connectivity for unified nested patterns. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void updateUnifiedNestedConnectivity(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - - updNestedCompositionNodesConnectedInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, - unifiedCompositionTo.getContext()); - updNestedCompositionNodesConnectedOutConnectivity(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionData, unifiedCompositionTo - .getContext()); - updNestedCompositionNodesGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionData, - unifiedCompositionTo.getContext()); - updNestedCompositionOutputParamGetAttrInConnectivity(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionData, unifiedCompositionTo.getContext()); - } - - - /** - * Clean unified nested entities. Update the heat stack group with the new node template ids. - * - * @param unifiedCompositionTo the unified composition data transfer object - * @param unifiedCompositionData the unified composition data - */ - public void cleanUnifiedNestedEntities(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - EntityConsolidationData entityConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - updateHeatStackGroupNestedComposition(unifiedCompositionTo.getServiceTemplate(), entityConsolidationData, - unifiedCompositionTo.getContext()); - - } - - public void createNestedVfcInstanceGroup(String nestedNodeTemplateId, - UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionData unifiedCompositionData) { - if (!TranslationContext.isVfcInstanceGroupingEnabled()) { - return; - } - createSubInterfaceVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); - } - - public void handleComplexVfcType(ServiceTemplate serviceTemplate, TranslationContext context) { - SubstitutionMapping substitutionMapping = - serviceTemplate.getTopology_template().getSubstitution_mappings(); - - if (Objects.isNull(substitutionMapping)) { - return; - } - - ServiceTemplate globalSubstitutionServiceTemplate = - context.getGlobalSubstitutionServiceTemplate(); - - String substitutionNT = substitutionMapping.getNode_type(); - if (globalSubstitutionServiceTemplate.getNode_types().containsKey(substitutionNT)) { - //This needs to be done when catalog is ready for complex VFC - } - } - - - protected void updNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, - List - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for nodes connected out for computes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - Multimap computeNodesConnectedOut = - computeTemplateConsolidationData.getNodesConnectedOut(); - if (computeNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, computeNodesConnectedOut, context); - } - String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData - .getNodeTemplateId()); - //Add requirements in the abstract node template for nodes connected out for ports - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), computeType, computeTemplateConsolidationData); - Multimap portNodesConnectedOut = - portTemplateConsolidationData.getNodesConnectedOut(); - if (portNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, portTemplateConsolidationData, - newPortNodeTemplateId, portNodesConnectedOut, context); - } - } - //For sub-interface - //Add requirements in the abstract node template for nodes connected out for ports - updateSubInterfaceNodesConnectedOut(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updateSubInterfaceNodesConnectedOut(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - TranslationContext context) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - Multimap subInterfaceNodesConnectedOut = - subInterfaceTemplateConsolidationData.getNodesConnectedOut(); - if (subInterfaceNodesConnectedOut != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, - newSubInterfaceNodeTemplateId, subInterfaceNodesConnectedOut, context); - } - } - } - - private void updNestedCompositionNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - Multimap nodesConnectedOut = - Objects.isNull(nestedTemplateConsolidationData) ? ArrayListMultimap.create() - : nestedTemplateConsolidationData.getNodesConnectedOut(); + public void createNestedVfcInstanceGroup(String nestedNodeTemplateId, UnifiedCompositionTo unifiedCompositionTo, + UnifiedCompositionData unifiedCompositionData) { + if (!TranslationContext.isVfcInstanceGroupingEnabled()) { + return; + } + createSubInterfaceVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); + } + + public void handleComplexVfcType(ServiceTemplate serviceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMapping = serviceTemplate.getTopology_template().getSubstitution_mappings(); + if (Objects.isNull(substitutionMapping)) { + return; + } + ServiceTemplate globalSubstitutionServiceTemplate = context.getGlobalSubstitutionServiceTemplate(); + String substitutionNT = substitutionMapping.getNode_type(); + if (globalSubstitutionServiceTemplate.getNode_types().containsKey(substitutionNT)) { + //This needs to be done when catalog is ready for complex VFC + } + } - FileComputeConsolidationData nestedFileComputeConsolidationData = - context.getConsolidationData().getComputeConsolidationData().getFileComputeConsolidationData - (ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + protected void updNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected out for computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + Multimap computeNodesConnectedOut = computeTemplateConsolidationData.getNodesConnectedOut(); + if (computeNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, + computeNodesConnectedOut, context); + } + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Add requirements in the abstract node template for nodes connected out for ports + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + Multimap portNodesConnectedOut = portTemplateConsolidationData.getNodesConnectedOut(); + if (portNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, portTemplateConsolidationData, newPortNodeTemplateId, + portNodesConnectedOut, context); + } + } + //For sub-interface - if (Objects.isNull(nestedFileComputeConsolidationData)) { - return; + //Add requirements in the abstract node template for nodes connected out for ports + updateSubInterfaceNodesConnectedOut(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } } - TypeComputeConsolidationData computeType = - nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); - if (Objects.isNull(computeType)) { - return; + private void updateSubInterfaceNodesConnectedOut(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + Multimap subInterfaceNodesConnectedOut = subInterfaceTemplateConsolidationData.getNodesConnectedOut(); + if (subInterfaceNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, + subInterfaceNodesConnectedOut, context); + } + } } - String singleComputeId = computeType.getAllComputeNodeTemplateIds().iterator().next(); - if (Objects.nonNull(singleComputeId) && (Objects.nonNull(nestedTemplateConsolidationData))) { - updateRequirementInNestedNodeTemplate(serviceTemplate, nestedTemplateConsolidationData, - singleComputeId, nodesConnectedOut); + private void updNestedCompositionNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + Multimap nodesConnectedOut = + Objects.isNull(nestedTemplateConsolidationData) ? ArrayListMultimap.create() : nestedTemplateConsolidationData.getNodesConnectedOut(); + FileComputeConsolidationData nestedFileComputeConsolidationData = context.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + if (Objects.isNull(nestedFileComputeConsolidationData)) { + return; + } + TypeComputeConsolidationData computeType = nestedFileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next(); + if (Objects.isNull(computeType)) { + return; + } + String singleComputeId = computeType.getAllComputeNodeTemplateIds().iterator().next(); + if (Objects.nonNull(singleComputeId) && (Objects.nonNull(nestedTemplateConsolidationData))) { + updateRequirementInNestedNodeTemplate(serviceTemplate, nestedTemplateConsolidationData, singleComputeId, nodesConnectedOut); + } } - } - private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, - List - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Update requirements in the node template which pointing to the computes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - updNodesConnectedInConnectivity(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, context, false); - - String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData - .getNodeTemplateId()); - //Update requirements in the node template which pointing to the ports - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), computeType, computeTemplateConsolidationData); - updNodesConnectedInConnectivity(serviceTemplate, portTemplateConsolidationData, - newPortNodeTemplateId, context, false); - } - - //Update requirements in the node template which pointing to the sub-interface - updateSubInterfaceNodesConnectedIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - TranslationContext context, - boolean isNested) { - Multimap nodesConnectedIn = - entityConsolidationData.getNodesConnectedIn(); + private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Update requirements in the node template which pointing to the computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updNodesConnectedInConnectivity(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, context, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Update requirements in the node template which pointing to the ports + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updNodesConnectedInConnectivity(serviceTemplate, portTemplateConsolidationData, newPortNodeTemplateId, context, false); + } + //Update requirements in the node template which pointing to the sub-interface + updateSubInterfaceNodesConnectedIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } + } + + private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, TranslationContext context, boolean isNested) { + Multimap nodesConnectedIn = entityConsolidationData.getNodesConnectedIn(); if (nodesConnectedIn == null) { //No nodes connected in info return; } - for (String key : nodesConnectedIn.keySet()) { Collection requirementAssignmentDataList = nodesConnectedIn.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - if (!requirementAssignment.getNode().equals(entityConsolidationData - .getNodeTemplateId())) { + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + if (!requirementAssignment.getNode().equals(entityConsolidationData.getNodeTemplateId())) { //The requirement assignment target node should be the one which we are handling in the + //consolidation object continue; } //Update the requirement assignment object in the original node template if (isNested) { - updateRequirementForNestedCompositionNodesConnectedIn(serviceTemplate, - requirementAssignmentData, newNodeTemplateId); + updateRequirementForNestedCompositionNodesConnectedIn(serviceTemplate, requirementAssignmentData, newNodeTemplateId); } else { - updateRequirementForNodesConnectedIn(serviceTemplate, requirementAssignmentData, - entityConsolidationData, key, newNodeTemplateId, context); + updateRequirementForNodesConnectedIn(serviceTemplate, requirementAssignmentData, entityConsolidationData, key, newNodeTemplateId, + context); + } + } + } + } + + private void updateSubInterfaceNodesConnectedIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updNodesConnectedInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, context, false); + } + } + + protected void updNestedCompositionNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + //Update requirements in the node template which pointing to the nested nodes + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updNodesConnectedInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + newNestedNodeTemplateIdVal, context, true)); + } + + private void updVolumeConnectivity(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for compute volumes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + Multimap computeVolumes = computeTemplateConsolidationData.getVolumes(); + if (computeVolumes != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, newComputeNodeTemplateId, computeVolumes, + context); + } + } + } + + private void updGroupsConnectivity(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected in for computes + updGroupsConnectivity(serviceTemplate, computeTemplateConsolidationData, context); + //Add requirements in the abstract node template for nodes connected in for ports + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + updGroupsConnectivity(serviceTemplate, portTemplateConsolidationData, context); + } + //Add requirements in the abstract node template for nodes connected in for subInterface + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + updGroupsConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, context); + } + } + } + + private void updGroupsConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, TranslationContext context) { + List groupIds = entityConsolidationData.getGroupIds(); + if (groupIds == null) { + return; + } + String oldNodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + Map groups = serviceTemplate.getTopology_template().getGroups(); + if (groups == null) { + return; + } + for (String groupId : groupIds) { + GroupDefinition groupDefinition = groups.get(groupId); + if (groupDefinition == null) { + continue; + } + List groupMembers = groupDefinition.getMembers(); + if (groupMembers.contains(oldNodeTemplateId)) { + //Replace the old node template id + groupMembers.remove(oldNodeTemplateId); + if (!groupMembers.contains(abstractNodeTemplateId)) { + //Add the abstract node template id if not already present + groupMembers.add(abstractNodeTemplateId); } + } + } + } + + private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, List unifiedComposotionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updOutputParamGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, + computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId, context, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updOutputParamGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, portTemplateConsolidationData.getNodeTemplateId(), + newPortNodeTemplateId, context, false); + } + updateSubInterfaceOutputParamGetAttrIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, context); + } + } + + private void updateSubInterfaceOutputParamGetAttrIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + TranslationContext context) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updOutputParamGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, + subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, false); + } + } + private void updNodesGetAttrInConnectivity(ServiceTemplate serviceTemplate, List unifiedComposotionDataList, + TranslationContext context) { + Map consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedComposotionDataList); + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + updNodeGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, computeTemplateConsolidationData.getNodeTemplateId(), + newComputeNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPotNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + updNodeGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, portTemplateConsolidationData.getNodeTemplateId(), + newPotNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); } + updateSubInterfaceNodesGetAttrIn(serviceTemplate, unifiedCompositionData, computeTemplateConsolidationData, computeType, + consolidationNodeTemplateIdAndType, context); } } - private void updateSubInterfaceNodesConnectedIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, + private void updateSubInterfaceNodesGetAttrIn(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + ComputeTemplateConsolidationData computeTemplateConsolidationData, String computeType, + Map consolidationNodeTemplateIdAndType, TranslationContext context) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updNodesConnectedInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - newSubInterfaceNodeTemplateId, context, false); - } - } - - protected void updNestedCompositionNodesConnectedInConnectivity( - ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData - .getNestedTemplateConsolidationData(); - //Update requirements in the node template which pointing to the nested nodes - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updNodesConnectedInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, - newNestedNodeTemplateIdVal, context, true)); - - } - - private void updVolumeConnectivity(ServiceTemplate serviceTemplate, - List - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for compute volumes - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - Multimap computeVolumes = - computeTemplateConsolidationData.getVolumes(); - if (computeVolumes != null) { - updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, - newComputeNodeTemplateId, computeVolumes, context); - } - } - } - - private void updGroupsConnectivity(ServiceTemplate serviceTemplate, - List - unifiedCompositionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - //Add requirements in the abstract node template for nodes connected in for computes - updGroupsConnectivity(serviceTemplate, computeTemplateConsolidationData, context); - - //Add requirements in the abstract node template for nodes connected in for ports - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - updGroupsConnectivity(serviceTemplate, portTemplateConsolidationData, context); - } - - //Add requirements in the abstract node template for nodes connected in for subInterface - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - updGroupsConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, context); - } - } - } - - private void updGroupsConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData - entityConsolidationData, TranslationContext context) { - List groupIds = entityConsolidationData.getGroupIds(); - if (groupIds == null) { - return; - } - String oldNodeTemplateId = entityConsolidationData.getNodeTemplateId(); - String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - Map groups = serviceTemplate.getTopology_template().getGroups(); - if (groups == null) { - return; - } - for (String groupId : groupIds) { - GroupDefinition groupDefinition = groups.get(groupId); - if (groupDefinition == null) { - continue; - } - List groupMembers = groupDefinition.getMembers(); - if (groupMembers.contains(oldNodeTemplateId)) { - //Replace the old node template id - groupMembers.remove(oldNodeTemplateId); - if (!groupMembers.contains(abstractNodeTemplateId)) { - //Add the abstract node template id if not already present - groupMembers.add(abstractNodeTemplateId); - } - } - } - } - - private void updOutputParamGetAttrInConnectivity( - ServiceTemplate serviceTemplate, List unifiedComposotionDataList, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - updOutputParamGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, - computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId, - context, false); - - String computeType = - getComputeTypeSuffix(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, - computeTemplateConsolidationData); - - updOutputParamGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, - portTemplateConsolidationData.getNodeTemplateId(), newPortNodeTemplateId, context, + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, computeTemplateConsolidationData, + subInterfaceTemplateConsolidationData, context); + updNodeGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, + subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - } - - updateSubInterfaceOutputParamGetAttrIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, context); - } - } - - private void updateSubInterfaceOutputParamGetAttrIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - TranslationContext context) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updOutputParamGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), newSubInterfaceNodeTemplateId, context, - false); - } - } - - private void updNodesGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - List unifiedComposotionDataList, - TranslationContext context) { - Map consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedComposotionDataList); - for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - updNodeGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, - computeTemplateConsolidationData.getNodeTemplateId(), - newComputeNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - - String computeType = - getComputeTypeSuffix(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPotNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, - computeTemplateConsolidationData); - - updNodeGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, - portTemplateConsolidationData.getNodeTemplateId(), - newPotNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); - } - - updateSubInterfaceNodesGetAttrIn(serviceTemplate, unifiedCompositionData, - computeTemplateConsolidationData, computeType, consolidationNodeTemplateIdAndType, context); - } - } - - private void updateSubInterfaceNodesGetAttrIn(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - String computeType, - Map consolidationNodeTemplateIdAndType, - TranslationContext context) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(serviceTemplate, computeType, - computeTemplateConsolidationData, subInterfaceTemplateConsolidationData, context); - updNodeGetAttrInConnectivity(serviceTemplate, subInterfaceTemplateConsolidationData, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), - newSubInterfaceNodeTemplateId, context, - consolidationNodeTemplateIdAndType, false); - } - } - - protected void updNestedCompositionOutputParamGetAttrInConnectivity( - ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updOutputParamGetAttrInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), - newNestedNodeTemplateIdVal, context, true)); - } - - protected void updNestedCompositionNodesGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - TranslationContext context) { - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.isNull(nestedTemplateConsolidationData)) { - return; - } - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( - serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); - - newNestedNodeTemplateId.ifPresent( - newNestedNodeTemplateIdVal -> updNodeGetAttrInConnectivity(serviceTemplate, - nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), - newNestedNodeTemplateIdVal, context, null, true)); - } - - private void updateRequirementForNodesConnectedIn( - ServiceTemplate serviceTemplate, - RequirementAssignmentData requirementAssignmentData, - EntityConsolidationData entityConsolidationData, - String originalNodeTemplateId, - String newNodeTemplateId, - TranslationContext context) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - String newAbstractUnifiedNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - NodeTemplate abstractUnifiedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - newAbstractUnifiedNodeTemplateId); - Optional newCapabilityId = getNewCapabilityForNodesConnectedIn(serviceTemplate, - abstractUnifiedNodeTemplate, requirementAssignment, newNodeTemplateId, context); - if (newCapabilityId.isPresent()) { - //Creating a copy of the requirement object and checking if it already exists in the - // original node template - RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( - requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); - NodeTemplate originalNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - originalNodeTemplateId); - requirementAssignmentCopy.setCapability(newCapabilityId.get()); - requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(originalNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { - //Update the existing requirement - requirementAssignmentData.getRequirementAssignment().setCapability(newCapabilityId - .get()); - requirementAssignmentData.getRequirementAssignment() - .setNode(newAbstractUnifiedNodeTemplateId); - } else { - //The updated requirement already exists in the node template so simply remove the - // current one - DataModelUtil.removeRequirementAssignment(originalNodeTemplate, requirementAssignmentData - .getRequirementId(), requirementAssignmentData.getRequirementAssignment()); - } - } - } - - private void updateRequirementForNestedCompositionNodesConnectedIn( - ServiceTemplate serviceTemplate, - RequirementAssignmentData requirementAssignmentData, - String newNodeTemplateId) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - String newAbstractUnifiedNodeTemplateId = newNodeTemplateId; - RequirementAssignment requirementAssignment = requirementAssignmentData - .getRequirementAssignment(); - //Creating a copy of the requirement object and checking if it already exists in the - // original node template - RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + } + } + + protected void updNestedCompositionOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, + UnifiedCompositionData unifiedCompositionData, TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updOutputParamGetAttrInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + nestedTemplateConsolidationData.getNodeTemplateId(), newNestedNodeTemplateIdVal, context, true)); + } + + protected void updNestedCompositionNodesGetAttrInConnectivity(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, + TranslationContext context) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + return; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent(newNestedNodeTemplateIdVal -> updNodeGetAttrInConnectivity(serviceTemplate, nestedTemplateConsolidationData, + nestedTemplateConsolidationData.getNodeTemplateId(), newNestedNodeTemplateIdVal, context, null, true)); + } + + private void updateRequirementForNodesConnectedIn(ServiceTemplate serviceTemplate, RequirementAssignmentData requirementAssignmentData, + EntityConsolidationData entityConsolidationData, String originalNodeTemplateId, + String newNodeTemplateId, TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + String newAbstractUnifiedNodeTemplateId = context + .getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractUnifiedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); + Optional newCapabilityId = getNewCapabilityForNodesConnectedIn(serviceTemplate, abstractUnifiedNodeTemplate, requirementAssignment, + newNodeTemplateId, context); + if (newCapabilityId.isPresent()) { + //Creating a copy of the requirement object and checking if it already exists in the + + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); + NodeTemplate originalNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, originalNodeTemplateId); + requirementAssignmentCopy.setCapability(newCapabilityId.get()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService + .isRequirementExistInNodeTemplate(originalNodeTemplate, requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment().setCapability(newCapabilityId.get()); + requirementAssignmentData.getRequirementAssignment().setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + + // current one + DataModelUtil.removeRequirementAssignment(originalNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentData.getRequirementAssignment()); + } + } + } + + private void updateRequirementForNestedCompositionNodesConnectedIn(ServiceTemplate serviceTemplate, + RequirementAssignmentData requirementAssignmentData, + String newNodeTemplateId) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + String newAbstractUnifiedNodeTemplateId = newNodeTemplateId; + RequirementAssignment requirementAssignment = requirementAssignmentData.getRequirementAssignment(); + //Creating a copy of the requirement object and checking if it already exists in the + + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); - NodeTemplate unifiedAbstractNestedNodeTemplate = DataModelUtil - .getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); - requirementAssignmentCopy.setCapability(requirementAssignment.getCapability()); - requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(unifiedAbstractNestedNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { - //Update the existing requirement - requirementAssignmentData.getRequirementAssignment() - .setNode(newAbstractUnifiedNodeTemplateId); - } else { - //The updated requirement already exists in the node template so simply remove the - // current one - DataModelUtil.removeRequirementAssignment(unifiedAbstractNestedNodeTemplate, - requirementAssignmentData.getRequirementId(), requirementAssignmentData - .getRequirementAssignment()); - } - } - - private Optional getNewCapabilityForNodesConnectedIn(ServiceTemplate serviceTemplate, - NodeTemplate unifiedNodeTemplate, - RequirementAssignment - requirementAssignment, - String newNodeTemplateId, - TranslationContext context) { - ServiceTemplate globalSubstitutionServiceTemplate = - HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); - Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); - String unifiedNodeTemplateType = unifiedNodeTemplate.getType(); - NodeType unifiedNodeType = nodeTypes.get(unifiedNodeTemplateType); - Map abstractNodeTypeCapabilities = unifiedNodeType - .getCapabilities(); - for (Map.Entry entry : abstractNodeTypeCapabilities.entrySet()) { - String capabilityId = entry.getKey(); - CapabilityDefinition capabilityDefinition = entry.getValue(); - String capabilityType = capabilityDefinition.getType(); - if (capabilityType.equals(requirementAssignment.getCapability()) - && capabilityId.endsWith(newNodeTemplateId)) { - //Matching capability type found..Check if the id ends with new node template id - return Optional.ofNullable(capabilityId); - } - } - return Optional.empty(); - } - - - private void updateRequirementInAbstractNodeTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData - entityConsolidationData, + NodeTemplate unifiedAbstractNestedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); + requirementAssignmentCopy.setCapability(requirementAssignment.getCapability()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(unifiedAbstractNestedNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment().setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + + // current one + DataModelUtil.removeRequirementAssignment(unifiedAbstractNestedNodeTemplate, requirementAssignmentData.getRequirementId(), + requirementAssignmentData.getRequirementAssignment()); + } + } + + private Optional getNewCapabilityForNodesConnectedIn(ServiceTemplate serviceTemplate, NodeTemplate unifiedNodeTemplate, + RequirementAssignment requirementAssignment, String newNodeTemplateId, + TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + String unifiedNodeTemplateType = unifiedNodeTemplate.getType(); + NodeType unifiedNodeType = nodeTypes.get(unifiedNodeTemplateType); + Map abstractNodeTypeCapabilities = unifiedNodeType.getCapabilities(); + for (Map.Entry entry : abstractNodeTypeCapabilities.entrySet()) { + String capabilityId = entry.getKey(); + CapabilityDefinition capabilityDefinition = entry.getValue(); + String capabilityType = capabilityDefinition.getType(); + if (capabilityType.equals(requirementAssignment.getCapability()) && capabilityId.endsWith(newNodeTemplateId)) { + //Matching capability type found..Check if the id ends with new node template id + return Optional.ofNullable(capabilityId); + } + } + return Optional.empty(); + } + + private void updateRequirementInAbstractNodeTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, String newNodeTemplateId, - Multimap - requirementAssignmentDataMap, + Multimap requirementAssignmentDataMap, TranslationContext context) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); for (String key : requirementAssignmentDataMap.keySet()) { - String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( - serviceTemplate, entityConsolidationData.getNodeTemplateId()); - NodeTemplate abstractNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - abstractNodeTemplateId); + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, abstractNodeTemplateId); if (abstractNodeTemplate == null) { //The abstract node template is not found from id in the context return; @@ -1294,35 +970,28 @@ public class UnifiedCompositionService { Collection requirementAssignmentDataList = requirementAssignmentDataMap.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { String oldRequirementId = requirementAssignmentData.getRequirementId(); - RequirementAssignment abstractRequirementAssignment = (RequirementAssignment) - getClonedObject(requirementAssignmentData.getRequirementAssignment(), - RequirementAssignment.class); + RequirementAssignment abstractRequirementAssignment = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); String newRequirementId = oldRequirementId + "_" + newNodeTemplateId; //Check if the requirement is not already present in the list of requirements of the + // abstract node template - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(abstractNodeTemplate, - newRequirementId, abstractRequirementAssignment)) { - DataModelUtil.addRequirementAssignment(abstractNodeTemplate, newRequirementId, - abstractRequirementAssignment); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(abstractNodeTemplate, newRequirementId, abstractRequirementAssignment)) { + DataModelUtil.addRequirementAssignment(abstractNodeTemplate, newRequirementId, abstractRequirementAssignment); //Update the volume relationship template if required - updateVolumeRelationshipTemplate(serviceTemplate, abstractRequirementAssignment - .getRelationship(), context); + updateVolumeRelationshipTemplate(serviceTemplate, abstractRequirementAssignment.getRelationship(), context); } } } } - private void updateRequirementInNestedNodeTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, + private void updateRequirementInNestedNodeTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, String newNodeTemplateId, - Multimap - requirementAssignmentDataMap) { + Multimap requirementAssignmentDataMap) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - if (CommonUtil.isMultimapEmpty(requirementAssignmentDataMap)) { return; } - for (String key : requirementAssignmentDataMap.keySet()) { String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); @@ -1333,2472 +1002,1817 @@ public class UnifiedCompositionService { Collection requirementAssignmentDataList = requirementAssignmentDataMap.get(key); for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { String oldRequirementId = requirementAssignmentData.getRequirementId(); - RequirementAssignment clonedRequirementAssignment = (RequirementAssignment) - getClonedObject(requirementAssignmentData.getRequirementAssignment(), - RequirementAssignment.class); + RequirementAssignment clonedRequirementAssignment = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); String newRequirementId = oldRequirementId + "_" + newNodeTemplateId; //Check if the requirement is not already present in the list of requirements of the + // node template - if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(nodeTemplate, - newRequirementId, clonedRequirementAssignment)) { - DataModelUtil.removeRequirementAssignment(nodeTemplate, oldRequirementId, - requirementAssignmentData.getRequirementAssignment()); - DataModelUtil.addRequirementAssignment(nodeTemplate, newRequirementId, - clonedRequirementAssignment); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(nodeTemplate, newRequirementId, clonedRequirementAssignment)) { + DataModelUtil.removeRequirementAssignment(nodeTemplate, oldRequirementId, requirementAssignmentData.getRequirementAssignment()); + DataModelUtil.addRequirementAssignment(nodeTemplate, newRequirementId, clonedRequirementAssignment); } } } } - private void updNodeGetAttrInConnectivity( - ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String oldNodeTemplateId, String newNodeTemplateId, - TranslationContext context, - Map consolidationNodeTemplateIdAndType, - boolean isNested) { - Map> nodesGetAttrIn = entityConsolidationData.getNodesGetAttrIn(); - if (MapUtils.isEmpty(nodesGetAttrIn)) { - return; - } - - for (Map.Entry> nodesGetAttrInEntry : nodesGetAttrIn.entrySet()) { - String sourceNodeTemplateId = nodesGetAttrInEntry.getKey(); - NodeTemplate sourceNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, sourceNodeTemplateId); - if (!isNested && consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { - continue; - } - List getAttrFuncDataList = nodesGetAttrInEntry.getValue(); - for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { - Object propertyValue = - DataModelUtil.getPropertyValue(sourceNodeTemplate, getAttrFuncData.getFieldName()); - String newAttrName = null; - String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; - if (!isNested) { - newGetAttrAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); - newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData - .getAttributeName()); - } - List> getAttrFuncValueList = extractGetAttrFunction(propertyValue); - updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, - newAttrName, getAttrFuncValueList, isNested); - } - } - } - - private void updateGetAttrValue(String oldNodeTemplateId, GetAttrFuncData getAttrFuncData, - String newNodeTemplateId, String newAttrName, - List> getAttrFuncValueList, boolean isNested) { - for (List getAttrFuncValue : getAttrFuncValueList) { - if (oldNodeTemplateId.equals(getAttrFuncValue.get(0)) - && getAttrFuncData.getAttributeName().equals(getAttrFuncValue.get(1))) { - getAttrFuncValue.set(0, newNodeTemplateId); - if (!isNested) { - getAttrFuncValue.set(1, newAttrName); - } - } - } - } - - private String getTemplateName(String nodeTypeId, - Integer index) { - String computeType = getComputeTypeSuffix(nodeTypeId); - String templateName = "Nested_" + computeType; - if (Objects.nonNull(index)) { - templateName = templateName + "_" + index.toString(); - } - return templateName; - } - - private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, - EntityConsolidationData entityConsolidationData, - String oldNodeTemplateId, - String newNodeTemplateId, - TranslationContext context, - boolean isNested) { - List outputParametersGetAttrIn = - entityConsolidationData.getOutputParametersGetAttrIn(); - if (CollectionUtils.isEmpty(outputParametersGetAttrIn)) { - return; - } - for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { - Object outputParamValue = - DataModelUtil.getOuputParameter(serviceTemplate, getAttrFuncData.getFieldName()) - .getValue(); - String newAttrName = null; - String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; - if (!isNested) { - newGetAttrAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); - newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData - .getAttributeName()); - } - List> getAttrFuncValueList = extractGetAttrFunction(outputParamValue); - updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, - newAttrName, - getAttrFuncValueList, isNested); - } - - } - - private List> extractGetAttrFunction(Object valueObject) { - - List> getAttrValueList = new ArrayList<>(); - - if (valueObject instanceof Map) { - if (((Map) valueObject).containsKey(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())) { - getAttrValueList.add( - (List) ((Map) valueObject).get(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())); - } - - for (Object key : ((Map) valueObject).keySet()) { - getAttrValueList.addAll(extractGetAttrFunction(((Map) valueObject).get(key))); - } - - - } else if (valueObject instanceof List) { - for (Object valueEntity : (List) valueObject) { - getAttrValueList.addAll(extractGetAttrFunction(valueEntity)); - } - } - return getAttrValueList; - } - - private boolean isIncludeToscaFunc(Object valueObject, ToscaFunctions toscaFunction) { - if (valueObject instanceof Map) { - if (((Map) valueObject).containsKey(toscaFunction.getFunctionName())) { - return true; - } - - Set> entries = ((Map) valueObject).entrySet(); - for (Map.Entry valueObjectEntry : entries) { - if (isIncludeToscaFunc(valueObjectEntry.getValue(), toscaFunction)) { - return true; - } - } - } else if (valueObject instanceof List) { - for (Object valueEntity : (List) valueObject) { - if (isIncludeToscaFunc(valueEntity, toscaFunction)) { - return true; - } - } - } - return false; - } - - private void createOutputParameters(UnifiedCompositionTo unifiedCompositionTo, - String computeNodeType) { - - createOutputParametersForCompute(unifiedCompositionTo.getServiceTemplate(), - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - createOutputParameterForPorts(unifiedCompositionTo.getSubstitutionServiceTemplate(), - unifiedCompositionTo.getUnifiedCompositionDataList(), computeNodeType, unifiedCompositionTo.getContext()); - createOutputParameterForSubInterfaces(unifiedCompositionTo, computeNodeType); - } - - private void createOutputParameterForPorts( - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { - return; - } - - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), - connectedComputeNodeType, - unifiedCompositionData.getComputeTemplateConsolidationData()); - addOutputParameters(portTemplateConsolidationData, newPortNodeTemplateId, - substitutionServiceTemplate, unifiedCompositionDataList, context); - } - } - } - - private void createOutputParameterForSubInterfaces(UnifiedCompositionTo unifiedCompositionTo, - String connectedComputeNodeType) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionTo.getUnifiedCompositionDataList()) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(subInterfaceTemplateConsolidationDataList)) { - return; - } - - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo - .getServiceTemplate(), connectedComputeNodeType, unifiedCompositionData - .getComputeTemplateConsolidationData(), subInterfaceTemplateConsolidationData, - unifiedCompositionTo.getContext()); - addOutputParameters(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, - unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - } - } - } - - private void createOutputParametersForCompute( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List - unifiedCompositionDataList, - TranslationContext context) { - List computeConsolidationDataList = - getComputeConsolidationDataList(unifiedCompositionDataList); - - for (EntityConsolidationData computeTemplateConsolidationData : computeConsolidationDataList) { - String newComputeNodeTemplateId = - getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - addOutputParameters(computeTemplateConsolidationData, newComputeNodeTemplateId, - substitutionServiceTemplate, unifiedCompositionDataList, context); - } - } - - private void addOutputParameters(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - handleNodesGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, - unifiedCompositionDataList, context); - - handleOutputParamGetAttrIn(entityConsolidationData, newNodeTemplateId, - substitutionServiceTemplate, context); - } - - private void handleOutputParamGetAttrIn(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context) { - List outputParametersGetAttrIn = - entityConsolidationData.getOutputParametersGetAttrIn(); - if (!CollectionUtils.isEmpty(outputParametersGetAttrIn)) { - for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { - createAndAddOutputParameter(newNodeTemplateId, - substitutionServiceTemplate, getAttrFuncData, context); - } - } - } - - private void handleNodesGetAttrIn(EntityConsolidationData entityConsolidationData, - String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - Map> getAttrIn = entityConsolidationData.getNodesGetAttrIn(); - if (MapUtils.isEmpty(getAttrIn)) { - return; - } - Map consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); - for (Map.Entry> getAttrInEntry : getAttrIn.entrySet()) { - String sourceNodeTemplateId = getAttrInEntry.getKey(); - if (!consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { - List getAttrFuncDataList = getAttrInEntry.getValue(); - for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { - createAndAddOutputParameter(newNodeTemplateId, - substitutionServiceTemplate, getAttrFuncData, context); - } - } - } - } - - private void createAndAddOutputParameter(String newNodeTemplateId, - ServiceTemplate substitutionServiceTemplate, - GetAttrFuncData getAttrFuncData, - TranslationContext context) { - Map> parameterValue = new HashMap<>(); - List valueList = new ArrayList<>(); - valueList.add(newNodeTemplateId); - valueList.add(getAttrFuncData.getAttributeName()); - parameterValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), valueList); - ParameterDefinition outputParameter = new ParameterDefinition(); - outputParameter.setValue(parameterValue); - setOutputParameterType(substitutionServiceTemplate, newNodeTemplateId, getAttrFuncData - .getAttributeName(), outputParameter, context); - DataModelUtil.addOutputParameterToTopologyTemplate(substitutionServiceTemplate, - getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()), - outputParameter); - } - - private void setOutputParameterType(ServiceTemplate substitutionServiceTemplate, - String newNodeTemplateId, - String outputParameterName, - ParameterDefinition outputParameter, - TranslationContext context) { - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(substitutionServiceTemplate, - newNodeTemplateId); - //Get the type and entry schema of the output parameter from the node type flat hierarchy - String outputParameterType; - EntrySchema outputParameterEntrySchema; - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), - substitutionServiceTemplate, context); - //Check if the parameter is present in the attributes - AttributeDefinition outputParameterDefinitionFromAttributes = - getOutputParameterDefinitionFromAttributes(nodeTypeWithFlatHierarchy, outputParameterName); - if (Objects.nonNull(outputParameterDefinitionFromAttributes)) { - outputParameterType = outputParameterDefinitionFromAttributes.getType(); - outputParameterEntrySchema = outputParameterDefinitionFromAttributes.getEntry_schema(); - } else { - //If the below fails due to null pointer then we need to check if the heatToToscaMapping - // properties and global types are in sync. Ideally the parameter should be found in either - // properties or attributes collected from global types - PropertyDefinition outputParameterDefinitionFromProperties = - nodeTypeWithFlatHierarchy.getProperties().get(outputParameterName); - outputParameterType = outputParameterDefinitionFromProperties.getType(); - outputParameterEntrySchema = outputParameterDefinitionFromProperties.getEntry_schema(); - } - //Set the type and entry schema for the output param obtained from the node type hierarchy - outputParameter.setType(outputParameterType); - outputParameter.setEntry_schema(outputParameterEntrySchema); - } - - private AttributeDefinition getOutputParameterDefinitionFromAttributes(NodeType - nodeTypeWithFlatHierarchy, - String outputParameterName) { - AttributeDefinition outputParameterDefinition = null; - if ((Objects.nonNull(nodeTypeWithFlatHierarchy.getAttributes())) - && (nodeTypeWithFlatHierarchy.getAttributes().containsKey(outputParameterName))) { - outputParameterDefinition = - nodeTypeWithFlatHierarchy.getAttributes().get(outputParameterName); - } - return outputParameterDefinition; - } - - private String getNewSubstitutionOutputParameterId(String newNodeTemplateId, - String attributeName) { - return newNodeTemplateId + "_" + attributeName; - } - - private void addUnifiedSubstitionData(TranslationContext context, ServiceTemplate - serviceTemplate, List unifiedCompositionDataList, String - substituteNodeTemplateId) { - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - //Add compute node template mapping information - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - String computeNodeTemplateId = computeTemplateConsolidationData.getNodeTemplateId(); - context.addUnifiedSubstitutionData(serviceTemplateFileName, computeNodeTemplateId, - substituteNodeTemplateId); - //Add Port template mapping information - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - - if (CollectionUtils.isNotEmpty(portTemplateConsolidationDataList)) { - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - String oldPortNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); - context.addUnifiedSubstitutionData(serviceTemplateFileName, oldPortNodeTemplateId, - substituteNodeTemplateId); - } - } - //Add Sub-interface template mapping information - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - context.addUnifiedSubstitutionData(serviceTemplateFileName, - subInterfaceTemplateConsolidationData.getNodeTemplateId(), substituteNodeTemplateId); - } - } - } - } - - private void addIndexValueProperty(NodeTemplate nodeTemplate) { - List indexValueGetPropertyValue = new ArrayList<>(); - indexValueGetPropertyValue.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); - indexValueGetPropertyValue.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - indexValueGetPropertyValue.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); - - Map indexPropertyValue = new HashMap<>(); - Map properties = nodeTemplate.getProperties(); - indexPropertyValue.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), - indexValueGetPropertyValue); - properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, - indexPropertyValue); - nodeTemplate.setProperties(properties); - } - - private String getSubstituteNodeTemplateId(String nodeTypeId, - Integer index) { - String nodeTemplateId = ABSTRACT_NODE_TEMPLATE_ID_PREFIX + DataModelUtil - .getNamespaceSuffix(nodeTypeId); - if (Objects.nonNull(index)) { - nodeTemplateId = nodeTemplateId + "_" + index.toString(); - } - return nodeTemplateId; - } - - /** - * Gets substitution node type id. - * - * @param serviceTemplate the service template - * @param unifiedCompositionData the unified composition data - * @param index the index - * @return the substitution node type id - */ - public String getSubstitutionNodeTypeId(ServiceTemplate serviceTemplate, - UnifiedCompositionData unifiedCompositionData, - Integer index, - TranslationContext context) { - String computeNodeTemplateId = - unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); - NodeTemplate computeNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); - String computeType = computeNodeTemplate.getType(); - String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - - String nodeTypeId = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX - + DataModelUtil.getNamespaceSuffix(getIndexedGlobalNodeTypeId(computeType, context)); - - context.updateUsedTimesForNestedComputeNodeType(globalSTName, computeType); - - if (Objects.nonNull(index)) { - nodeTypeId = nodeTypeId + "_" + index.toString(); - } - return nodeTypeId; - } - - private NodeType handleSubstitutionGlobalNodeType(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - TranslationContext context, - String substitutionNodeTypeId) { - NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() - .createInitSubstitutionNodeType(substitutionServiceTemplate, - ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - ServiceTemplate globalSubstitutionServiceTemplate = - HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, - substitutionNodeType); - - return substitutionNodeType; - } - - private void handlePorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - - if (unifiedCompositionDataList.size() > 1) { - handleConsolidationPorts(serviceTemplate, substitutionServiceTemplate, - unifiedCompositionDataList, connectedComputeNodeType, context); - } else { - handleSinglePorts(serviceTemplate, substitutionServiceTemplate, connectedComputeNodeType, - unifiedCompositionDataList, context); - } - } - - private void handleSinglePorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - String connectedComputeNodeType, - List unifiedCompositionDataList, - TranslationContext context) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { - return; - } - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - List portConsolidationDataList = new ArrayList<>(); - portConsolidationDataList.add(portTemplateConsolidationData); - handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, - portConsolidationDataList, connectedComputeNodeType, - unifiedCompositionData.getComputeTemplateConsolidationData(), - unifiedCompositionDataList, context); - } - } - - private void handleConsolidationPorts(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - String connectedComputeNodeType, - TranslationContext context) { - Map> portIdsPerPortType = - UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes(unifiedCompositionDataList); - - for (Map.Entry> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { - List portTemplateConsolidationDataList = - getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), unifiedCompositionDataList); - if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + private void updNodeGetAttrInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, String newNodeTemplateId, TranslationContext context, + Map consolidationNodeTemplateIdAndType, boolean isNested) { + Map> nodesGetAttrIn = entityConsolidationData.getNodesGetAttrIn(); + if (MapUtils.isEmpty(nodesGetAttrIn)) { + return; + } + for (Map.Entry> nodesGetAttrInEntry : nodesGetAttrIn.entrySet()) { + String sourceNodeTemplateId = nodesGetAttrInEntry.getKey(); + NodeTemplate sourceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, sourceNodeTemplateId); + if (!isNested && consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { continue; } - - handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portTemplateConsolidationDataList, - connectedComputeNodeType, unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(), - unifiedCompositionDataList, context); + List getAttrFuncDataList = nodesGetAttrInEntry.getValue(); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + Object propertyValue = DataModelUtil.getPropertyValue(sourceNodeTemplate, getAttrFuncData.getFieldName()); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()); + } + List> getAttrFuncValueList = extractGetAttrFunction(propertyValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, newAttrName, getAttrFuncValueList, isNested); + } } } - private void handlePortNodeTemplate( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List portTemplateConsolidationDataList, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List unifiedCompositionDataList, - TranslationContext context) { - EntityConsolidationData portTemplateConsolidationData = - portTemplateConsolidationDataList.get(0); - NodeTemplate newPortNodeTemplate = getNodeTemplate( - portTemplateConsolidationData.getNodeTemplateId(), serviceTemplate, context).clone(); - - removeConnectivityOut(portTemplateConsolidationData, newPortNodeTemplate); - handleProperties(serviceTemplate, newPortNodeTemplate, - substitutionServiceTemplate, UnifiedCompositionEntity.PORT, - portTemplateConsolidationDataList, computeTemplateConsolidationData, - unifiedCompositionDataList, context); - - //Add subinterface_indicator property to PORT - portTemplateConsolidationDataList.forEach(entity -> - addPortSubInterfaceIndicatorProperty(newPortNodeTemplate.getProperties(), entity)); - - String newPortNodeTemplateId = - getNewPortNodeTemplateId(portTemplateConsolidationData - .getNodeTemplateId(), connectedComputeNodeType, - computeTemplateConsolidationData); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity(newPortNodeTemplate, - serviceTemplate, context); - DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newPortNodeTemplateId, - newPortNodeTemplate); - - //Add the node template mapping in the context for handling requirement updation - for (EntityConsolidationData data : portTemplateConsolidationDataList) { - String newPortTemplateId = getNewPortNodeTemplateId(data.getNodeTemplateId(), - connectedComputeNodeType, computeTemplateConsolidationData); - context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), data.getNodeTemplateId(), - newPortTemplateId); - } - - } - - private void handleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - if (unifiedCompositionTo.getUnifiedCompositionDataList().size() > 1) { - handleConsolidationSubInterfaces(unifiedCompositionTo); - } else { - handleSingleSubInterfaces(unifiedCompositionTo); - } - } - - private void handleSingleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - List subInterfaceDataList = new ArrayList<>(); - subInterfaceDataList.add(subInterfaceTemplateConsolidationData); - createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceDataList); - } - } - - private void handleConsolidationSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { - Map> portIdsPerPortType = - UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes( - unifiedCompositionTo.getUnifiedCompositionDataList()); - - for (Map.Entry> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { - List portEntityConsolidationDataList = - getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), - unifiedCompositionTo.getUnifiedCompositionDataList()); - if (CollectionUtils.isEmpty(portEntityConsolidationDataList)) { - continue; + private void updateGetAttrValue(String oldNodeTemplateId, GetAttrFuncData getAttrFuncData, String newNodeTemplateId, String newAttrName, + List> getAttrFuncValueList, boolean isNested) { + for (List getAttrFuncValue : getAttrFuncValueList) { + if (oldNodeTemplateId.equals(getAttrFuncValue.get(0)) && getAttrFuncData.getAttributeName().equals(getAttrFuncValue.get(1))) { + getAttrFuncValue.set(0, newNodeTemplateId); + if (!isNested) { + getAttrFuncValue.set(1, newAttrName); + } } - - List portTemplateConsolidationDataList = - portEntityConsolidationDataList.stream().map(data -> (PortTemplateConsolidationData) data) - .collect(Collectors.toList()); - - ListMultimap subInterfacesByType = - UnifiedCompositionUtil.collectAllSubInterfacesOfEachTypesFromPorts( - portTemplateConsolidationDataList); - Set subInterfaceTypes = subInterfacesByType.keySet(); - for (String subInterfaceType : subInterfaceTypes) { - List subInterfaceTemplateConsolidationDataList = - subInterfacesByType.get(subInterfaceType); - createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, - subInterfaceTemplateConsolidationDataList); - } - } - } - - private void createSubInterfaceSubstitutionNodeTemplate(UnifiedCompositionTo unifiedCompositionTo, - List - subInterfaceTemplateConsolidationDataList) { - SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = - subInterfaceTemplateConsolidationDataList.get(0); - Optional portTemplateConsolidationDataOptional = - subInterfaceTemplateConsolidationData.getParentPortTemplateConsolidationData(unifiedCompositionTo - .getServiceTemplate(), unifiedCompositionTo.getContext()); - if (!portTemplateConsolidationDataOptional.isPresent()) { - return; - } - PortTemplateConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataOptional.get(); - String originalSubInterfaceNodeTemplateId = subInterfaceTemplateConsolidationDataList.get(0) - .getNodeTemplateId(); - NodeTemplate originalSubInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), originalSubInterfaceNodeTemplateId); - if (Objects.isNull(originalSubInterfaceNodeTemplate)) { - return; - } - NodeTemplate newSubInterfaceNodeTemplate = originalSubInterfaceNodeTemplate.clone(); - ComputeTemplateConsolidationData connectedComputeConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionTo.getUnifiedCompositionDataList(), - portTemplateConsolidationData.getNodeTemplateId()); - if (Objects.nonNull(connectedComputeConsolidationData)) { - NodeTemplate connectedComputeNodeTemplate = DataModelUtil.getNodeTemplate(unifiedCompositionTo - .getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); - String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo - .getServiceTemplate(), connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, - subInterfaceTemplateConsolidationData, unifiedCompositionTo.getContext()); - DataModelUtil.addNodeTemplate(unifiedCompositionTo.getSubstitutionServiceTemplate(), - newSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate); - List entityConsolidationDataList = - new ArrayList<>(subInterfaceTemplateConsolidationDataList); - //Remove all the existing properties as we are going to create new based on the - // naming convention for the substitution - handleSubInterfaceProperties(unifiedCompositionTo, originalSubInterfaceNodeTemplateId, - newSubInterfaceNodeTemplate, entityConsolidationDataList, portTemplateConsolidationData); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity(newSubInterfaceNodeTemplate, unifiedCompositionTo - .getServiceTemplate(), unifiedCompositionTo.getContext()); - removeConnectivityOut(subInterfaceTemplateConsolidationData,newSubInterfaceNodeTemplate); - } - } - - private void handleSubInterfaceProperties(UnifiedCompositionTo unifiedCompositionTo, - String subInterfaceNodeTemplateId, - NodeTemplate newSubInterfaceNodeTemplate, - List - entityConsolidationDataList, - PortTemplateConsolidationData - portTemplateConsolidationData) { - UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); - ServiceTemplate serviceTemplate = unifiedCompositionTo.getServiceTemplate(); - TranslationContext context = unifiedCompositionTo.getContext(); - newSubInterfaceNodeTemplate.setProperties(new HashMap<>()); - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - Optional> indexVarProperties = - context.getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateId); - Map properties = - DataModelUtil.getNodeTemplateProperties(serviceTemplate, nodeTemplateId); - if (MapUtils.isEmpty(properties)) { - continue; - } - - for (Map.Entry propertyEntry : properties.entrySet()) { - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(newSubInterfaceNodeTemplate.getType(), - serviceTemplate, context); - PropertyDefinition propertyDefinition = - nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); - String propertyType = propertyDefinition.getType(); - //Handle service_template_filter property for subinterface as we should not create inputs - // for this property - if (propertyEntry.getKey().equals(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { - handleSubInterfaceServiceTemplateFilterProperty(subInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, - propertyEntry.getKey(), propertyEntry.getValue(), portTemplateConsolidationData, - unifiedCompositionTo.getSubstitutionServiceTemplate()); - } else if (indexVarProperties.isPresent() - && indexVarProperties.get().contains(propertyEntry.getKey())) { - //Handle index property - handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), - newSubInterfaceNodeTemplate); - } else { - Optional parameterId = - updateProperty(serviceTemplate, nodeTemplateId, newSubInterfaceNodeTemplate, - propertyEntry, UnifiedCompositionEntity.SUB_INTERFACE, unifiedCompositionData - .getComputeTemplateConsolidationData(), portTemplateConsolidationData, - unifiedCompositionTo.getUnifiedCompositionDataList(), context); - parameterId.ifPresent( - parameterIdValue -> addPropertyInputParameter(propertyType, - unifiedCompositionTo.getSubstitutionServiceTemplate(), - propertyDefinition.getEntry_schema(), parameterIdValue)); } - } } - } - - private NodeTemplate getNodeTemplate(String nodeTemplateId, ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); + private String getTemplateName(String nodeTypeId, Integer index) { + String computeType = getComputeTypeSuffix(nodeTypeId); + String templateName = "Nested_" + computeType; + if (Objects.nonNull(index)) { + templateName = templateName + "_" + index.toString(); + } + return templateName; + } - if (Objects.isNull(nodeTemplate)) { - nodeTemplate = context - .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateId); + private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, String newNodeTemplateId, TranslationContext context, + boolean isNested) { + List outputParametersGetAttrIn = entityConsolidationData.getOutputParametersGetAttrIn(); + if (CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + return; + } + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + Object outputParamValue = DataModelUtil.getOuputParameter(serviceTemplate, getAttrFuncData.getFieldName()).getValue(); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()); + } + List> getAttrFuncValueList = extractGetAttrFunction(outputParamValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, newAttrName, getAttrFuncValueList, isNested); + } + } + private List> extractGetAttrFunction(Object valueObject) { + List> getAttrValueList = new ArrayList<>(); + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())) { + getAttrValueList.add((List) ((Map) valueObject).get(ToscaFunctions.GET_ATTRIBUTE.getFunctionName())); + } + for (Object key : ((Map) valueObject).keySet()) { + getAttrValueList.addAll(extractGetAttrFunction(((Map) valueObject).get(key))); + } + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + getAttrValueList.addAll(extractGetAttrFunction(valueEntity)); + } + } + return getAttrValueList; } - return nodeTemplate; - } + private boolean isIncludeToscaFunc(Object valueObject, ToscaFunctions toscaFunction) { + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(toscaFunction.getFunctionName())) { + return true; + } + Set> entries = ((Map) valueObject).entrySet(); + for (Map.Entry valueObjectEntry : entries) { + if (isIncludeToscaFunc(valueObjectEntry.getValue(), toscaFunction)) { + return true; + } + } + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + if (isIncludeToscaFunc(valueEntity, toscaFunction)) { + return true; + } + } + } + return false; + } + + private void createOutputParameters(UnifiedCompositionTo unifiedCompositionTo, String computeNodeType) { + createOutputParametersForCompute(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getSubstitutionServiceTemplate(), + unifiedCompositionTo.getUnifiedCompositionDataList(), unifiedCompositionTo.getContext()); + createOutputParameterForPorts(unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), + computeNodeType, unifiedCompositionTo.getContext()); + createOutputParameterForSubInterfaces(unifiedCompositionTo, computeNodeType); + } + + private void createOutputParameterForPorts(ServiceTemplate substitutionServiceTemplate, List unifiedCompositionDataList, + String connectedComputeNodeType, TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + return; + } + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData()); + addOutputParameters(portTemplateConsolidationData, newPortNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, + context); + } + } + } + + private void createOutputParameterForSubInterfaces(UnifiedCompositionTo unifiedCompositionTo, String connectedComputeNodeType) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionTo.getUnifiedCompositionDataList()) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + if (CollectionUtils.isEmpty(subInterfaceTemplateConsolidationDataList)) { + return; + } + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), + connectedComputeNodeType, unifiedCompositionData.getComputeTemplateConsolidationData(), subInterfaceTemplateConsolidationData, + unifiedCompositionTo.getContext()); + addOutputParameters(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplateId, + unifiedCompositionTo.getSubstitutionServiceTemplate(), unifiedCompositionTo.getUnifiedCompositionDataList(), + unifiedCompositionTo.getContext()); + } + } + } + + private void createOutputParametersForCompute(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + List computeConsolidationDataList = getComputeConsolidationDataList(unifiedCompositionDataList); + for (EntityConsolidationData computeTemplateConsolidationData : computeConsolidationDataList) { + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + addOutputParameters(computeTemplateConsolidationData, newComputeNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, + context); + } + } - private String handleCompute(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); - handleComputeNodeTemplate(serviceTemplate, substitutionServiceTemplate, - unifiedCompositionDataList, context); - return handleComputeNodeType(serviceTemplate, substitutionServiceTemplate, + private void addOutputParameters(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + handleNodesGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, unifiedCompositionDataList, context); + handleOutputParamGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, context); + } + + private void handleOutputParamGetAttrIn(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, TranslationContext context) { + List outputParametersGetAttrIn = entityConsolidationData.getOutputParametersGetAttrIn(); + if (!CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + createAndAddOutputParameter(newNodeTemplateId, substitutionServiceTemplate, getAttrFuncData, context); + } + } + } + + private void handleNodesGetAttrIn(EntityConsolidationData entityConsolidationData, String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, List unifiedCompositionDataList, + TranslationContext context) { + Map> getAttrIn = entityConsolidationData.getNodesGetAttrIn(); + if (MapUtils.isEmpty(getAttrIn)) { + return; + } + Map consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedCompositionDataList); + for (Map.Entry> getAttrInEntry : getAttrIn.entrySet()) { + String sourceNodeTemplateId = getAttrInEntry.getKey(); + if (!consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { + List getAttrFuncDataList = getAttrInEntry.getValue(); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + createAndAddOutputParameter(newNodeTemplateId, substitutionServiceTemplate, getAttrFuncData, context); + } + } + } + } + + private void createAndAddOutputParameter(String newNodeTemplateId, ServiceTemplate substitutionServiceTemplate, GetAttrFuncData getAttrFuncData, + TranslationContext context) { + Map> parameterValue = new HashMap<>(); + List valueList = new ArrayList<>(); + valueList.add(newNodeTemplateId); + valueList.add(getAttrFuncData.getAttributeName()); + parameterValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), valueList); + ParameterDefinition outputParameter = new ParameterDefinition(); + outputParameter.setValue(parameterValue); + setOutputParameterType(substitutionServiceTemplate, newNodeTemplateId, getAttrFuncData.getAttributeName(), outputParameter, context); + DataModelUtil.addOutputParameterToTopologyTemplate(substitutionServiceTemplate, + getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()), outputParameter); + } + + private void setOutputParameterType(ServiceTemplate substitutionServiceTemplate, String newNodeTemplateId, String outputParameterName, + ParameterDefinition outputParameter, TranslationContext context) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(substitutionServiceTemplate, newNodeTemplateId); + //Get the type and entry schema of the output parameter from the node type flat hierarchy + String outputParameterType; + EntrySchema outputParameterEntrySchema; + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), substitutionServiceTemplate, context); + //Check if the parameter is present in the attributes + AttributeDefinition outputParameterDefinitionFromAttributes = getOutputParameterDefinitionFromAttributes(nodeTypeWithFlatHierarchy, + outputParameterName); + if (Objects.nonNull(outputParameterDefinitionFromAttributes)) { + outputParameterType = outputParameterDefinitionFromAttributes.getType(); + outputParameterEntrySchema = outputParameterDefinitionFromAttributes.getEntry_schema(); + } else { + //If the below fails due to null pointer then we need to check if the heatToToscaMapping + + // properties and global types are in sync. Ideally the parameter should be found in either + + // properties or attributes collected from global types + PropertyDefinition outputParameterDefinitionFromProperties = nodeTypeWithFlatHierarchy.getProperties().get(outputParameterName); + outputParameterType = outputParameterDefinitionFromProperties.getType(); + outputParameterEntrySchema = outputParameterDefinitionFromProperties.getEntry_schema(); + } + //Set the type and entry schema for the output param obtained from the node type hierarchy + outputParameter.setType(outputParameterType); + outputParameter.setEntry_schema(outputParameterEntrySchema); + } + + private AttributeDefinition getOutputParameterDefinitionFromAttributes(NodeType nodeTypeWithFlatHierarchy, String outputParameterName) { + AttributeDefinition outputParameterDefinition = null; + if ((Objects.nonNull(nodeTypeWithFlatHierarchy.getAttributes())) && (nodeTypeWithFlatHierarchy.getAttributes() + .containsKey(outputParameterName))) { + outputParameterDefinition = nodeTypeWithFlatHierarchy.getAttributes().get(outputParameterName); + } + return outputParameterDefinition; + } + + private String getNewSubstitutionOutputParameterId(String newNodeTemplateId, String attributeName) { + return newNodeTemplateId + "_" + attributeName; + } + + private void addUnifiedSubstitionData(TranslationContext context, ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, String substituteNodeTemplateId) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + //Add compute node template mapping information + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + String computeNodeTemplateId = computeTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, computeNodeTemplateId, substituteNodeTemplateId); + //Add Port template mapping information + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isNotEmpty(portTemplateConsolidationDataList)) { + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + String oldPortNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, oldPortNodeTemplateId, substituteNodeTemplateId); + } + } + //Add Sub-interface template mapping information + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + if (CollectionUtils.isNotEmpty(subInterfaceTemplateConsolidationDataList)) { + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + context.addUnifiedSubstitutionData(serviceTemplateFileName, subInterfaceTemplateConsolidationData.getNodeTemplateId(), + substituteNodeTemplateId); + } + } + } + } + + private void addIndexValueProperty(NodeTemplate nodeTemplate) { + List indexValueGetPropertyValue = new ArrayList<>(); + indexValueGetPropertyValue.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); + indexValueGetPropertyValue.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + indexValueGetPropertyValue.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + Map indexPropertyValue = new HashMap<>(); + Map properties = nodeTemplate.getProperties(); + indexPropertyValue.put(ToscaFunctions.GET_PROPERTY.getFunctionName(), indexValueGetPropertyValue); + properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexPropertyValue); + nodeTemplate.setProperties(properties); + } + + private String getSubstituteNodeTemplateId(String nodeTypeId, Integer index) { + String nodeTemplateId = ABSTRACT_NODE_TEMPLATE_ID_PREFIX + DataModelUtil.getNamespaceSuffix(nodeTypeId); + if (Objects.nonNull(index)) { + nodeTemplateId = nodeTemplateId + "_" + index.toString(); + } + return nodeTemplateId; + } + + /** + * Gets substitution node type id. + * + * @param serviceTemplate the service template + * @param unifiedCompositionData the unified composition data + * @param index the index + * @return the substitution node type id + */ + public String getSubstitutionNodeTypeId(ServiceTemplate serviceTemplate, UnifiedCompositionData unifiedCompositionData, Integer index, + TranslationContext context) { + String computeNodeTemplateId = unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + String computeType = computeNodeTemplate.getType(); + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + String nodeTypeId = + ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + DataModelUtil.getNamespaceSuffix(getIndexedGlobalNodeTypeId(computeType, context)); + context.updateUsedTimesForNestedComputeNodeType(globalSTName, computeType); + if (Objects.nonNull(index)) { + nodeTypeId = nodeTypeId + "_" + index.toString(); + } + return nodeTypeId; + } + + private NodeType handleSubstitutionGlobalNodeType(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + TranslationContext context, String substitutionNodeTypeId) { + NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() + .createInitSubstitutionNodeType(substitutionServiceTemplate, ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, substitutionNodeType); + return substitutionNodeType; + } + + private void handlePorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, String connectedComputeNodeType, TranslationContext context) { + if (unifiedCompositionDataList.size() > 1) { + handleConsolidationPorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, connectedComputeNodeType, context); + } else { + handleSinglePorts(serviceTemplate, substitutionServiceTemplate, connectedComputeNodeType, unifiedCompositionDataList, context); + } + } + + private void handleSinglePorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, String connectedComputeNodeType, + List unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + return; + } + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + List portConsolidationDataList = new ArrayList<>(); + portConsolidationDataList.add(portTemplateConsolidationData); + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portConsolidationDataList, connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData(), unifiedCompositionDataList, context); + } + } + + private void handleConsolidationPorts(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, String connectedComputeNodeType, + TranslationContext context) { + Map> portIdsPerPortType = UnifiedCompositionUtil.collectAllPortsOfEachTypeFromComputes(unifiedCompositionDataList); + for (Map.Entry> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { + List portTemplateConsolidationDataList = getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), + unifiedCompositionDataList); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + continue; + } + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, portTemplateConsolidationDataList, connectedComputeNodeType, + unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(), unifiedCompositionDataList, context); + } + } + + private void handlePortNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List portTemplateConsolidationDataList, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List unifiedCompositionDataList, TranslationContext context) { + EntityConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataList.get(0); + NodeTemplate newPortNodeTemplate = getNodeTemplate(portTemplateConsolidationData.getNodeTemplateId(), serviceTemplate, context).clone(); + removeConnectivityOut(portTemplateConsolidationData, newPortNodeTemplate); + handleProperties(serviceTemplate, newPortNodeTemplate, substitutionServiceTemplate, UnifiedCompositionEntity.PORT, + portTemplateConsolidationDataList, computeTemplateConsolidationData, unifiedCompositionDataList, context); + //Add subinterface_indicator property to PORT + portTemplateConsolidationDataList.forEach(entity -> addPortSubInterfaceIndicatorProperty(newPortNodeTemplate.getProperties(), entity)); + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), connectedComputeNodeType, computeTemplateConsolidationData); - } - - private String handleComputeNodeType( - ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - String computeNodeTypeId = computeNodeTemplate.getType(); - NodeType computeNodeType = - DataModelUtil.getNodeType(serviceTemplate, computeNodeTypeId); - DataModelUtil - .addNodeType(substitutionServiceTemplate, computeNodeTypeId, computeNodeType); - - return computeNodeTypeId; - } - - private void handleComputeNodeTemplate(ServiceTemplate serviceTemplate, - ServiceTemplate substitutionServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); - NodeTemplate newComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()).clone(); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newPortNodeTemplate, serviceTemplate, context); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newPortNodeTemplateId, newPortNodeTemplate); + //Add the node template mapping in the context for handling requirement updation + for (EntityConsolidationData data : portTemplateConsolidationDataList) { + String newPortTemplateId = getNewPortNodeTemplateId(data.getNodeTemplateId(), connectedComputeNodeType, computeTemplateConsolidationData); + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + data.getNodeTemplateId(), newPortTemplateId); + } + } - removeConnectivityOut(computeTemplateConsolidationData, newComputeNodeTemplate); - removeVolumeConnectivity(computeTemplateConsolidationData, newComputeNodeTemplate); + private void handleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + if (unifiedCompositionTo.getUnifiedCompositionDataList().size() > 1) { + handleConsolidationSubInterfaces(unifiedCompositionTo); + } else { + handleSingleSubInterfaces(unifiedCompositionTo); + } + } - List computeConsolidationDataList = - getComputeConsolidationDataList(unifiedCompositionDataList); + private void handleSingleSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + List subInterfaceDataList = new ArrayList<>(); + subInterfaceDataList.add(subInterfaceTemplateConsolidationData); + createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceDataList); + } + } - handleProperties(serviceTemplate, newComputeNodeTemplate, - substitutionServiceTemplate, COMPUTE, - computeConsolidationDataList, computeTemplateConsolidationData, unifiedCompositionDataList, - context); + private void handleConsolidationSubInterfaces(UnifiedCompositionTo unifiedCompositionTo) { + Map> portIdsPerPortType = UnifiedCompositionUtil + .collectAllPortsOfEachTypeFromComputes(unifiedCompositionTo.getUnifiedCompositionDataList()); + for (Map.Entry> portIdsPerPortTypeEntry : portIdsPerPortType.entrySet()) { + List portEntityConsolidationDataList = getPortConsolidationDataList(portIdsPerPortTypeEntry.getValue(), + unifiedCompositionTo.getUnifiedCompositionDataList()); + if (CollectionUtils.isEmpty(portEntityConsolidationDataList)) { + continue; + } + List portTemplateConsolidationDataList = portEntityConsolidationDataList.stream() + .map(data -> (PortTemplateConsolidationData) data).collect(Collectors.toList()); + ListMultimap subInterfacesByType = UnifiedCompositionUtil + .collectAllSubInterfacesOfEachTypesFromPorts(portTemplateConsolidationDataList); + Set subInterfaceTypes = subInterfacesByType.keySet(); + for (String subInterfaceType : subInterfaceTypes) { + List subInterfaceTemplateConsolidationDataList = subInterfacesByType.get(subInterfaceType); + createSubInterfaceSubstitutionNodeTemplate(unifiedCompositionTo, subInterfaceTemplateConsolidationDataList); + } + } + } - String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - //Update requirements for relationships between the consolidation entities - handleConsolidationEntitiesRequirementConnectivity( - newComputeNodeTemplate, - serviceTemplate, context); - DataModelUtil - .addNodeTemplate(substitutionServiceTemplate, - newComputeNodeTemplateId, newComputeNodeTemplate); - //Add the node template mapping in the context for handling requirement updation - for (EntityConsolidationData data : computeConsolidationDataList) { - String newComputeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), data.getNodeTemplateId(), - newComputeTemplateId); - } - } - - private List getComputeConsolidationDataList( - List unifiedCompositionDataList) { - return unifiedCompositionDataList.stream() - .map(UnifiedCompositionData::getComputeTemplateConsolidationData) - .collect(Collectors.toList()); - } - - - private void handleProperties(ServiceTemplate serviceTemplate, - NodeTemplate nodeTemplate, - ServiceTemplate substitutionServiceTemplate, - UnifiedCompositionEntity unifiedCompositionEntity, - List entityConsolidationDataList, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List unifiedCompositionDataList, - TranslationContext context) { - nodeTemplate.setProperties(new HashedMap()); - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate,unifiedCompositionDataList, context, nodeTemplate); - handleNodeTemplateProperties(unifiedCompositionTo, unifiedCompositionEntity, entityConsolidationDataList, computeTemplateConsolidationData); - //Add enrich properties from openecomp node type as input to global and substitution ST - handleNodeTypeProperties(substitutionServiceTemplate, - entityConsolidationDataList, nodeTemplate, unifiedCompositionEntity, + private void createSubInterfaceSubstitutionNodeTemplate(UnifiedCompositionTo unifiedCompositionTo, + List subInterfaceTemplateConsolidationDataList) { + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData = subInterfaceTemplateConsolidationDataList.get(0); + Optional portTemplateConsolidationDataOptional = subInterfaceTemplateConsolidationData + .getParentPortTemplateConsolidationData(unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); + if (!portTemplateConsolidationDataOptional.isPresent()) { + return; + } + PortTemplateConsolidationData portTemplateConsolidationData = portTemplateConsolidationDataOptional.get(); + String originalSubInterfaceNodeTemplateId = subInterfaceTemplateConsolidationDataList.get(0).getNodeTemplateId(); + NodeTemplate originalSubInterfaceNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), originalSubInterfaceNodeTemplateId); + if (Objects.isNull(originalSubInterfaceNodeTemplate)) { + return; + } + NodeTemplate newSubInterfaceNodeTemplate = originalSubInterfaceNodeTemplate.clone(); + ComputeTemplateConsolidationData connectedComputeConsolidationData = getConnectedComputeConsolidationData( + unifiedCompositionTo.getUnifiedCompositionDataList(), portTemplateConsolidationData.getNodeTemplateId()); + if (Objects.nonNull(connectedComputeConsolidationData)) { + NodeTemplate connectedComputeNodeTemplate = DataModelUtil + .getNodeTemplate(unifiedCompositionTo.getServiceTemplate(), connectedComputeConsolidationData.getNodeTemplateId()); + String newSubInterfaceNodeTemplateId = getNewSubInterfaceNodeTemplateId(unifiedCompositionTo.getServiceTemplate(), + connectedComputeNodeTemplate.getType(), connectedComputeConsolidationData, subInterfaceTemplateConsolidationData, + unifiedCompositionTo.getContext()); + DataModelUtil + .addNodeTemplate(unifiedCompositionTo.getSubstitutionServiceTemplate(), newSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate); + List entityConsolidationDataList = new ArrayList<>(subInterfaceTemplateConsolidationDataList); + //Remove all the existing properties as we are going to create new based on the + + // naming convention for the substitution + handleSubInterfaceProperties(unifiedCompositionTo, originalSubInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, + entityConsolidationDataList, portTemplateConsolidationData); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newSubInterfaceNodeTemplate, unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getContext()); + removeConnectivityOut(subInterfaceTemplateConsolidationData, newSubInterfaceNodeTemplate); + } + } + + private void handleSubInterfaceProperties(UnifiedCompositionTo unifiedCompositionTo, String subInterfaceNodeTemplateId, + NodeTemplate newSubInterfaceNodeTemplate, List entityConsolidationDataList, + PortTemplateConsolidationData portTemplateConsolidationData) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionTo.getUnifiedCompositionDataList().get(0); + ServiceTemplate serviceTemplate = unifiedCompositionTo.getServiceTemplate(); + TranslationContext context = unifiedCompositionTo.getContext(); + newSubInterfaceNodeTemplate.setProperties(new HashMap<>()); + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + Optional> indexVarProperties = context + .getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateId); + Map properties = DataModelUtil.getNodeTemplateProperties(serviceTemplate, nodeTemplateId); + if (MapUtils.isEmpty(properties)) { + continue; + } + for (Map.Entry propertyEntry : properties.entrySet()) { + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(newSubInterfaceNodeTemplate.getType(), serviceTemplate, context); + PropertyDefinition propertyDefinition = nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); + String propertyType = propertyDefinition.getType(); + //Handle service_template_filter property for subinterface as we should not create inputs + + // for this property + if (propertyEntry.getKey().equals(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { + handleSubInterfaceServiceTemplateFilterProperty(subInterfaceNodeTemplateId, newSubInterfaceNodeTemplate, propertyEntry.getKey(), + propertyEntry.getValue(), portTemplateConsolidationData, unifiedCompositionTo.getSubstitutionServiceTemplate()); + } else if (indexVarProperties.isPresent() && indexVarProperties.get().contains(propertyEntry.getKey())) { + //Handle index property + handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), newSubInterfaceNodeTemplate); + } else { + Optional parameterId = updateProperty(serviceTemplate, nodeTemplateId, newSubInterfaceNodeTemplate, propertyEntry, + UnifiedCompositionEntity.SUB_INTERFACE, unifiedCompositionData.getComputeTemplateConsolidationData(), + portTemplateConsolidationData, unifiedCompositionTo.getUnifiedCompositionDataList(), context); + parameterId.ifPresent( + parameterIdValue -> addPropertyInputParameter(propertyType, unifiedCompositionTo.getSubstitutionServiceTemplate(), + propertyDefinition.getEntry_schema(), parameterIdValue)); + } + } + } + } + + private NodeTemplate getNodeTemplate(String nodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); + if (Objects.isNull(nodeTemplate)) { + nodeTemplate = context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateId); + } + return nodeTemplate; + } + + private String handleCompute(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + handleComputeNodeTemplate(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, context); + return handleComputeNodeType(serviceTemplate, substitutionServiceTemplate, computeTemplateConsolidationData); + } + + private String handleComputeNodeType(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + String computeNodeTypeId = computeNodeTemplate.getType(); + NodeType computeNodeType = DataModelUtil.getNodeType(serviceTemplate, computeNodeTypeId); + DataModelUtil.addNodeType(substitutionServiceTemplate, computeNodeTypeId, computeNodeType); + return computeNodeTypeId; + } + + private void handleComputeNodeTemplate(ServiceTemplate serviceTemplate, ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + NodeTemplate newComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()) + .clone(); + removeConnectivityOut(computeTemplateConsolidationData, newComputeNodeTemplate); + removeVolumeConnectivity(computeTemplateConsolidationData, newComputeNodeTemplate); + List computeConsolidationDataList = getComputeConsolidationDataList(unifiedCompositionDataList); + handleProperties(serviceTemplate, newComputeNodeTemplate, substitutionServiceTemplate, COMPUTE, computeConsolidationDataList, + computeTemplateConsolidationData, unifiedCompositionDataList, context); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newComputeNodeTemplate, serviceTemplate, context); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newComputeNodeTemplateId, newComputeNodeTemplate); + //Add the node template mapping in the context for handling requirement updation + for (EntityConsolidationData data : computeConsolidationDataList) { + String newComputeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + data.getNodeTemplateId(), newComputeTemplateId); + } + } + + private List getComputeConsolidationDataList(List unifiedCompositionDataList) { + return unifiedCompositionDataList.stream().map(UnifiedCompositionData::getComputeTemplateConsolidationData).collect(Collectors.toList()); + } + + private void handleProperties(ServiceTemplate serviceTemplate, NodeTemplate nodeTemplate, ServiceTemplate substitutionServiceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, List entityConsolidationDataList, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List unifiedCompositionDataList, TranslationContext context) { + nodeTemplate.setProperties(new HashedMap()); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + context, nodeTemplate); + handleNodeTemplateProperties(unifiedCompositionTo, unifiedCompositionEntity, entityConsolidationDataList, computeTemplateConsolidationData); + //Add enrich properties from openecomp node type as input to global and substitution ST + handleNodeTypeProperties(substitutionServiceTemplate, entityConsolidationDataList, nodeTemplate, unifiedCompositionEntity, computeTemplateConsolidationData, context); - } - - private void addPortSubInterfaceIndicatorProperty(Map properties, - EntityConsolidationData entityConsolidationData) { - properties.put(SUB_INTERFACE_INDICATOR_PROPERTY, - ((PortTemplateConsolidationData) entityConsolidationData).isPortBoundToSubInterface()); - } - - private void handleNodeTemplateProperties(UnifiedCompositionTo unifiedCompositionTo, - UnifiedCompositionEntity unifiedCompositionEntity, - List - entityConsolidationDataList, - ComputeTemplateConsolidationData - computeTemplateConsolidationData - ) { - List propertiesWithIdenticalVal = - consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); - - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - Optional> indexVarProperties = - unifiedCompositionTo.getContext().getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(unifiedCompositionTo.getServiceTemplate()), - nodeTemplateId); - Map properties = - DataModelUtil.getNodeTemplateProperties(unifiedCompositionTo.getServiceTemplate(), - nodeTemplateId); - if (MapUtils.isEmpty(properties)) { - continue; - } - - for (Map.Entry propertyEntry : properties.entrySet()) { - NodeType nodeTypeWithFlatHierarchy = - HeatToToscaUtil.getNodeTypeWithFlatHierarchy(unifiedCompositionTo.getNodeTemplate().getType(), - unifiedCompositionTo.getServiceTemplate(), unifiedCompositionTo.getContext()); - PropertyDefinition propertyDefinition = - nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); - String propertyType = propertyDefinition.getType(); - - if (propertiesWithIdenticalVal.contains(propertyEntry.getKey())) { - String parameterId = - updateIdenticalProperty(nodeTemplateId, propertyEntry.getKey(), - unifiedCompositionTo.getNodeTemplate(),unifiedCompositionEntity, unifiedCompositionTo.getUnifiedCompositionDataList()); - - addInputParameter( - parameterId, propertyType, - propertyType.equals(PropertyType.LIST.getDisplayName()) ? propertyDefinition - .getEntry_schema() : null, - unifiedCompositionTo.getSubstitutionServiceTemplate()); - } else if (indexVarProperties.isPresent() - && indexVarProperties.get().contains(propertyEntry.getKey())) { - //Handle index property - handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), - unifiedCompositionTo.getNodeTemplate()); - } else { - Optional parameterId = - updateProperty(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId, unifiedCompositionTo.getNodeTemplate(), propertyEntry, - unifiedCompositionEntity, computeTemplateConsolidationData, - getPortTemplateConsolidationDataForPort(unifiedCompositionTo.getUnifiedCompositionDataList(), nodeTemplateId), - unifiedCompositionTo.getUnifiedCompositionDataList(), - unifiedCompositionTo.getContext()); - parameterId.ifPresent( - parameterIdValue -> addPropertyInputParameter(propertyType, - unifiedCompositionTo.getSubstitutionServiceTemplate(), - propertyDefinition.getEntry_schema(), parameterIdValue)); - } - } - } - } - - private void handleIndexVarProperty(String propertyKey, Object propertyValue, - NodeTemplate nodeTemplate) { - //Retain properties translated from %index% value in heat - nodeTemplate.getProperties().put(propertyKey, propertyValue); - } - - private void handleSubInterfaceServiceTemplateFilterProperty(String subInterfaceNodeTemplateId, - NodeTemplate nodeTemplate, - String propertyKey, - Object propertyValue, - PortTemplateConsolidationData - portTemplateConsolidationData, - ServiceTemplate substitutionServiceTemplate) { - //Retain service_template_filter (Can be present in a sub-interface resource-def) - if (propertyValue instanceof Map) { - Map serviceTemplateFilterPropertyMap = new HashMap<>((Map) propertyValue); - handleCountProperty(subInterfaceNodeTemplateId, nodeTemplate, portTemplateConsolidationData, - substitutionServiceTemplate, serviceTemplateFilterPropertyMap); - DataModelUtil.addNodeTemplateProperty(nodeTemplate, propertyKey, serviceTemplateFilterPropertyMap); - } - } - - private void handleCountProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, - PortTemplateConsolidationData portTemplateConsolidationData, - ServiceTemplate substitutionServiceTemplate, - Map serviceTemplatePropertyMap) { - String countInputParameterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), subInterfaceNodeTemplateId, + } + + private void addPortSubInterfaceIndicatorProperty(Map properties, EntityConsolidationData entityConsolidationData) { + properties.put(SUB_INTERFACE_INDICATOR_PROPERTY, ((PortTemplateConsolidationData) entityConsolidationData).isPortBoundToSubInterface()); + } + + private void handleNodeTemplateProperties(UnifiedCompositionTo unifiedCompositionTo, UnifiedCompositionEntity unifiedCompositionEntity, + List entityConsolidationDataList, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + List propertiesWithIdenticalVal = consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + Optional> indexVarProperties = unifiedCompositionTo.getContext() + .getIndexVarProperties(ToscaUtil.getServiceTemplateFileName(unifiedCompositionTo.getServiceTemplate()), nodeTemplateId); + Map properties = DataModelUtil.getNodeTemplateProperties(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId); + if (MapUtils.isEmpty(properties)) { + continue; + } + for (Map.Entry propertyEntry : properties.entrySet()) { + NodeType nodeTypeWithFlatHierarchy = HeatToToscaUtil + .getNodeTypeWithFlatHierarchy(unifiedCompositionTo.getNodeTemplate().getType(), unifiedCompositionTo.getServiceTemplate(), + unifiedCompositionTo.getContext()); + PropertyDefinition propertyDefinition = nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()); + String propertyType = propertyDefinition.getType(); + if (propertiesWithIdenticalVal.contains(propertyEntry.getKey())) { + String parameterId = updateIdenticalProperty(nodeTemplateId, propertyEntry.getKey(), unifiedCompositionTo.getNodeTemplate(), + unifiedCompositionEntity, unifiedCompositionTo.getUnifiedCompositionDataList()); + addInputParameter(parameterId, propertyType, + propertyType.equals(PropertyType.LIST.getDisplayName()) ? propertyDefinition.getEntry_schema() : null, + unifiedCompositionTo.getSubstitutionServiceTemplate()); + } else if (indexVarProperties.isPresent() && indexVarProperties.get().contains(propertyEntry.getKey())) { + //Handle index property + handleIndexVarProperty(propertyEntry.getKey(), propertyEntry.getValue(), unifiedCompositionTo.getNodeTemplate()); + } else { + Optional parameterId = updateProperty(unifiedCompositionTo.getServiceTemplate(), nodeTemplateId, + unifiedCompositionTo.getNodeTemplate(), propertyEntry, unifiedCompositionEntity, computeTemplateConsolidationData, + getPortTemplateConsolidationDataForPort(unifiedCompositionTo.getUnifiedCompositionDataList(), nodeTemplateId), + unifiedCompositionTo.getUnifiedCompositionDataList(), unifiedCompositionTo.getContext()); + parameterId.ifPresent( + parameterIdValue -> addPropertyInputParameter(propertyType, unifiedCompositionTo.getSubstitutionServiceTemplate(), + propertyDefinition.getEntry_schema(), parameterIdValue)); + } + } + } + } + + private void handleIndexVarProperty(String propertyKey, Object propertyValue, NodeTemplate nodeTemplate) { + //Retain properties translated from %index% value in heat + nodeTemplate.getProperties().put(propertyKey, propertyValue); + } + + private void handleSubInterfaceServiceTemplateFilterProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, String propertyKey, + Object propertyValue, PortTemplateConsolidationData portTemplateConsolidationData, + ServiceTemplate substitutionServiceTemplate) { + //Retain service_template_filter (Can be present in a sub-interface resource-def) + if (propertyValue instanceof Map) { + Map serviceTemplateFilterPropertyMap = new HashMap<>((Map) propertyValue); + handleCountProperty(subInterfaceNodeTemplateId, nodeTemplate, portTemplateConsolidationData, substitutionServiceTemplate, + serviceTemplateFilterPropertyMap); + DataModelUtil.addNodeTemplateProperty(nodeTemplate, propertyKey, serviceTemplateFilterPropertyMap); + } + } + + private void handleCountProperty(String subInterfaceNodeTemplateId, NodeTemplate nodeTemplate, + PortTemplateConsolidationData portTemplateConsolidationData, ServiceTemplate substitutionServiceTemplate, + Map serviceTemplatePropertyMap) { + String countInputParameterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), subInterfaceNodeTemplateId, ToscaConstants.SERVICE_TEMPLATE_FILTER_COUNT, portTemplateConsolidationData); - EntrySchema entrySchema = new EntrySchema(); - entrySchema.setType(PropertyType.FLOAT.getDisplayName()); - addInputParameter(countInputParameterId, PropertyType.LIST.getDisplayName(), entrySchema, - substitutionServiceTemplate); - Map> countPropertyValueInputParam = getPropertyValueInputParam(countInputParameterId); - serviceTemplatePropertyMap.remove(ToscaConstants.COUNT_PROPERTY_NAME); - serviceTemplatePropertyMap.put(ToscaConstants.COUNT_PROPERTY_NAME, countPropertyValueInputParam); - } - - private void handleNodeTypeProperties(ServiceTemplate substitutionServiceTemplate, - List entityConsolidationDataList, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData - computeTemplateConsolidationData, - TranslationContext context) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional enrichNodeType; - List enrichProperties; - - if (compositionEntity.equals(UnifiedCompositionEntity.PORT)) { - enrichNodeType = - toscaAnalyzerService.fetchNodeType(ToscaNodeType.NETWORK_PORT, - context.getGlobalServiceTemplates().values()); - enrichProperties = TranslationContext.getEnrichPortResourceProperties(); - if (!enrichNodeType.isPresent() || Objects.isNull(enrichProperties)) { - return; - } - } else { - return; - } - - Map nodeTemplateProperties = nodeTemplate.getProperties(); - Map enrichNodeTypeProperties = enrichNodeType.get().getProperties(); - if (Objects.nonNull(enrichNodeTypeProperties)) { - for (String enrichPropertyName : enrichProperties) { - handleEntityConsolidationDataNodeTypeProperties( - enrichPropertyName, substitutionServiceTemplate, - enrichNodeType.get(), nodeTemplate, compositionEntity, computeTemplateConsolidationData, - entityConsolidationDataList, nodeTemplateProperties, context); - } - } - } - - private void handleEntityConsolidationDataNodeTypeProperties(String enrichPropertyName, - ServiceTemplate substitutionServiceTemplate, - NodeType enrichNodeType, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - List entityConsolidationDataList, - Map nodeTemplateProperties, - TranslationContext context) { - - String propertyType; - - for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { - String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); - - String inputParamId = - getParameterId(nodeTemplateId, nodeTemplate, enrichPropertyName, - compositionEntity, computeTemplateConsolidationData, - (PortTemplateConsolidationData) entityConsolidationData); - Map propertyValMap = new HashMap<>(); - - context - .addNewPropertyIdToNodeTemplate( - ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate), - inputParamId, nodeTemplateProperties.get(enrichPropertyName)); - - if (nodeTemplateProperties.containsKey(enrichPropertyName)) { - handleExistingEnrichedProperty(enrichPropertyName, nodeTemplateProperties, inputParamId); - } else { - propertyValMap.put(GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(enrichPropertyName, propertyValMap); - } - propertyType = - enrichNodeType.getProperties().get(enrichPropertyName).getType(); - - addPropertyInputParameter(propertyType, substitutionServiceTemplate, enrichNodeType - .getProperties().get(enrichPropertyName).getEntry_schema(), - inputParamId); - - } - } - - private void handleExistingEnrichedProperty(String enrichPropertyName, - Map nodeTemplateProperties, - String inputParamId) { - Object enrichedProperty = nodeTemplateProperties.get(enrichPropertyName); - if (!isPropertyContainsToscaFunction(enrichedProperty)) { - Map propertyWithGetInput = new HashMap<>(); - propertyWithGetInput.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplateProperties.put(enrichPropertyName, propertyWithGetInput); - } - } - - - private boolean isPropertyContainsToscaFunction(Object propertyValue) { - ToscaFunctions[] values = ToscaFunctions.values(); - for (ToscaFunctions toscaFunction : values) { - if (isIncludeToscaFunc(propertyValue, toscaFunction)) { - return true; - } - } - - return false; - } - - - private void addPropertyInputParameter(String propertyType, - ServiceTemplate substitutionServiceTemplate, - EntrySchema entrySchema, String parameterId) { - if (Objects.isNull(propertyType)) { - return; - } - if (isParameterBelongsToEnrichedPortProperties(parameterId)) { - addInputParameter(parameterId, - propertyType, - propertyType.equals(PropertyType.LIST.getDisplayName()) ? entrySchema : null, - substitutionServiceTemplate); - } else if (isPropertySimpleType(propertyType)) { - addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), - DataModelUtil.createEntrySchema(propertyType.toLowerCase(), null, null), - substitutionServiceTemplate); - - } else if (propertyType.equals(PropertyTypeExt.JSON.getDisplayName()) || - (Objects.nonNull(entrySchema) && isPropertySimpleType(entrySchema.getType()))) { - addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), - DataModelUtil.createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), - substitutionServiceTemplate); - } else { - addInputParameter(parameterId, analyzeParameterType(propertyType), DataModelUtil - .createEntrySchema(analyzeEntrySchemaType(propertyType, entrySchema), null, null), - substitutionServiceTemplate); - } - } - - private boolean isParameterBelongsToEnrichedPortProperties(String parameterId) { - List enrichPortResourceProperties = TranslationContext.getEnrichPortResourceProperties(); - - for (int i = 0; i < enrichPortResourceProperties.size(); i++) { - if (parameterId.contains((CharSequence) enrichPortResourceProperties.get(i))) { - return true; - } - } - - return false; - } - - private boolean isPropertySimpleType(String propertyType) { - return !Objects.isNull(propertyType) - && (PropertyType.getSimplePropertyTypes().contains(propertyType.toLowerCase())); - } - - private String analyzeParameterType(String propertyType) { - return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) ? PropertyType.LIST - .getDisplayName() : propertyType; - } - - private String analyzeEntrySchemaType(String propertyType, EntrySchema entrySchema) { - return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) && entrySchema != null ? - entrySchema.getType() : null; - } - - private void handleConsolidationEntitiesRequirementConnectivity(NodeTemplate nodeTemplate, - ServiceTemplate serviceTemplate, - TranslationContext context) { - List> nodeTemplateRequirements = DataModelUtil - .getNodeTemplateRequirementList(nodeTemplate); - if (CollectionUtils.isEmpty(nodeTemplateRequirements)) { - return; - } - - for (Map requirement : nodeTemplateRequirements) { - for (Map.Entry entry : requirement.entrySet()) { - RequirementAssignment requirementAssignment = entry.getValue(); - String requirementNode = requirementAssignment.getNode(); - String unifiedNodeTemplateId = - context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, - requirementNode); - if (unifiedNodeTemplateId != null) { - //Update the node id in the requirement - requirementAssignment.setNode(unifiedNodeTemplateId); - } - } - } - nodeTemplate.setRequirements(nodeTemplateRequirements); - } - - /** - * Update the node references in the volume relationship templates. - * - * @param serviceTemplate the service template - * @param context the context - */ - private void updateVolumeRelationshipTemplate(ServiceTemplate serviceTemplate, - String relationshipId, - TranslationContext context) { - Map relationshipTemplates = DataModelUtil - .getRelationshipTemplates(serviceTemplate); - if (relationshipTemplates != null) { - RelationshipTemplate relationshipTemplate = relationshipTemplates.get(relationshipId); - if (relationshipTemplate != null) { - String relationshipTemplateType = relationshipTemplate.getType(); - if (relationshipTemplateType.equals(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO)) { - handleCinderVolumeAttachmentRelationshipTemplate(serviceTemplate, - relationshipTemplate, context); - } - } - } - } - - - private void handleCinderVolumeAttachmentRelationshipTemplate(ServiceTemplate - substitutionServiceTemplate, - RelationshipTemplate - relationshipTemplate, - TranslationContext context) { - Map properties = relationshipTemplate.getProperties(); - properties.computeIfPresent(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, (key, value) -> - context.getUnifiedAbstractNodeTemplateId(substitutionServiceTemplate, - (String) value)); - } - - private String updateIdenticalProperty(String nodeTemplateId, String propertyId, - NodeTemplate nodeTemplate, - UnifiedCompositionEntity unifiedCompositionEntity, - List unifiedCompositionDataList) { - - String inputParamId = null; - Map propertyVal = new HashMap<>(); - - switch (unifiedCompositionEntity) { - case COMPUTE: - inputParamId = COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX + propertyId - + COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(propertyId, propertyVal); - break; - case PORT: - PortTemplateConsolidationData portTemplateConsolidationData = - getPortTemplateConsolidationDataForPort(unifiedCompositionDataList, - nodeTemplateId); - String portType = null; - if (Objects.nonNull(portTemplateConsolidationData)) { - portType = portTemplateConsolidationData.getPortType(); - } - ComputeTemplateConsolidationData computeTemplateConsolidationData = - getConnectedComputeConsolidationData(unifiedCompositionDataList, nodeTemplateId); - inputParamId = getInputParamIdForPort(nodeTemplateId, propertyId, portType, computeTemplateConsolidationData); - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); - nodeTemplate.getProperties().put(propertyId, propertyVal); - break; - default: - break; - } - return inputParamId; - } - - private String getInputParamIdForPort(String nodeTemplateId, String propertyId, String portType, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - String inputParamId; - if (Objects.isNull(computeTemplateConsolidationData) - || computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { - inputParamId = - UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + - propertyId; - - } else { - inputParamId = - UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" - + propertyId; - } - return inputParamId; - } - - private void addInputParameter(String parameterId, - String parameterType, - EntrySchema entrySchema, - ServiceTemplate serviceTemplate) { - - ParameterDefinition parameterDefinition = DataModelUtil.createParameterDefinition(parameterType, null, true, - null, entrySchema, null); - - - DataModelUtil - .addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); - } - - // Return the input parameter Id which is used in the new property value if there is one - private Optional updateProperty( - ServiceTemplate serviceTemplate, - String nodeTemplateId, NodeTemplate nodeTemplate, - Map.Entry propertyEntry, - UnifiedCompositionEntity compositionEntity, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - PortTemplateConsolidationData portTemplateConsolidationData, - List unifiedCompositionDataList, - TranslationContext context) { - - if (handleGetAttrFromConsolidationNodes(serviceTemplate, nodeTemplateId, nodeTemplate, - propertyEntry, unifiedCompositionDataList, context)) { - return Optional.empty(); - } - - - String inputParamId = - getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, - computeTemplateConsolidationData, portTemplateConsolidationData); - Map> propertyVal = getPropertyValueInputParam(inputParamId); - nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); - return Optional.of(inputParamId); - } - - private Map> getPropertyValueInputParam(String inputParamId) { - Map> propertyVal = new HashMap<>(); - List getInputFuncParams = new ArrayList<>(); - getInputFuncParams.add(inputParamId); - getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); - propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), getInputFuncParams); - return propertyVal; - } - - private boolean handleGetAttrFromConsolidationNodes( - ServiceTemplate serviceTemplate, - String nodeTemplateId, NodeTemplate nodeTemplate, - Map.Entry propertyEntry, - List unifiedCompositionDataList, - TranslationContext context) { - Map consolidationNodeTemplateIdAndType = - getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); - - Set consolidationNodeTemplateIds = consolidationNodeTemplateIdAndType.keySet(); - Map entityIdToType = ConsolidationService.getConsolidationEntityIdToType( - serviceTemplate, context.getConsolidationData()); - boolean includeGetAttrFromConsolidationNodes = false; - boolean includeGetAttrFromOutsideNodes = false; - boolean isGetAttrFromConsolidationIsFromSameType = false; - List> getAttrFunctionList = extractGetAttrFunction(propertyEntry.getValue()); - for (List getAttrFunc : getAttrFunctionList) { - String getAttrNodeId = (String) getAttrFunc.get(0); - if (consolidationNodeTemplateIds.contains(getAttrNodeId)) { - includeGetAttrFromConsolidationNodes = true; - if (isGetAttrNodeTemplateFromSameType(nodeTemplateId, getAttrNodeId, entityIdToType)) { - isGetAttrFromConsolidationIsFromSameType = true; - } - } else { - includeGetAttrFromOutsideNodes = true; - } - } - if ((includeGetAttrFromConsolidationNodes && includeGetAttrFromOutsideNodes) - || - (includeGetAttrFromConsolidationNodes && isIncludeToscaFunc(propertyEntry.getValue(), - ToscaFunctions.GET_INPUT))) { - //This case is currently not supported - this property will be ignored - return true; - } else if (includeGetAttrFromConsolidationNodes && !isGetAttrFromConsolidationIsFromSameType) { - Object clonedPropertyValue = getClonedPropertyValue(propertyEntry); - List> clonedGetAttrFuncList = extractGetAttrFunction(clonedPropertyValue); - for (List getAttrFunc : clonedGetAttrFuncList) { - String targetNodeTemplateId = (String) getAttrFunc.get(0); - if (consolidationNodeTemplateIds.contains(targetNodeTemplateId)) { - updatePropertyGetAttrFunc(serviceTemplate, unifiedCompositionDataList, - consolidationNodeTemplateIdAndType, targetNodeTemplateId, getAttrFunc, context); - } - } - nodeTemplate.getProperties().put(propertyEntry.getKey(), clonedPropertyValue); - return true; - } - return false; - } - - private boolean isGetAttrNodeTemplateFromSameType(String sourceNodeTemplateId, - String targetNodeTemplateId, - Map nodeTemplateIdToType) { - - if (Objects.isNull(nodeTemplateIdToType.get(sourceNodeTemplateId)) - || Objects.isNull(nodeTemplateIdToType.get(targetNodeTemplateId))) { - return false; - } - - return nodeTemplateIdToType.get(sourceNodeTemplateId).equals(nodeTemplateIdToType - .get(targetNodeTemplateId)); - } - - private void updatePropertyGetAttrFunc( - ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - Map consolidationNodeTemplateIdAndType, - String targetNodeTemplateId, - List getAttrFunc, TranslationContext context) { - UnifiedCompositionEntity targetCompositionEntity = - consolidationNodeTemplateIdAndType.get(targetNodeTemplateId); - String targetNewNodeTemplateId = - getNewNodeTemplateId(serviceTemplate, unifiedCompositionDataList, targetNodeTemplateId, - targetCompositionEntity, context); - getAttrFunc.set(0, targetNewNodeTemplateId); - } - - private String getNewNodeTemplateId(ServiceTemplate serviceTemplate, - List unifiedCompositionDataList, - String nodeTemplateId, - UnifiedCompositionEntity compositionEntity, - TranslationContext context) { - String newNodeTemplateId = nodeTemplateId; - String nodeTemplateIdGeneratorImpl = unifiedSubstitutionNodeTemplateIdGeneratorImplMap.get(compositionEntity); - UnifiedSubstitutionNodeTemplateIdGenerator nodeTemplateIdGenerator = - CommonMethods.newInstance(nodeTemplateIdGeneratorImpl, UnifiedSubstitutionNodeTemplateIdGenerator.class); - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, - unifiedCompositionDataList, context, null); - Optional generatedNodeTemplateId = nodeTemplateIdGenerator.generate(unifiedCompositionTo, nodeTemplateId); - if (generatedNodeTemplateId.isPresent()) { - newNodeTemplateId = generatedNodeTemplateId.get(); - } - return newNodeTemplateId; - } - - private String getNewNodeTemplateId(String origNodeTemplateId, - String serviceTemplateFileName, - ServiceTemplate serviceTemplate, - TranslationContext context) { - ConsolidationData consolidationData = context.getConsolidationData(); - - if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.PORT, - serviceTemplateFileName, - context)) { - return handleIdOfPort(origNodeTemplateId, serviceTemplateFileName, consolidationData); - } else if (isIdIsOfExpectedType(origNodeTemplateId, COMPUTE, - serviceTemplateFileName, context)) { - NodeTemplate nodeTemplate = - getComputeNodeTemplate(origNodeTemplateId, serviceTemplate, context); - return getComputeTypeSuffix(nodeTemplate.getType()); - } - - return null; - } - - private Object getClonedPropertyValue(Map.Entry propertyEntry) { - if (propertyEntry.getValue() instanceof Map) { - return getClonedObject(propertyEntry.getValue(), Map.class); - } else if (propertyEntry.getValue() instanceof List) { - return getClonedObject(propertyEntry.getValue(), List.class); - } - return propertyEntry.getValue(); - } - - - private String getParameterId(String nodeTemplateId, NodeTemplate nodeTemplate, String propertyId, - UnifiedCompositionEntity unifiedCompositionEntity, - ComputeTemplateConsolidationData - computeTemplateConsolidationData, - PortTemplateConsolidationData portTemplateConsolidationData) { - String paramterId = propertyId; - switch (unifiedCompositionEntity) { - case COMPUTE: - paramterId = COMPUTE.getDisplayName().toLowerCase() + "_" - + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; - break; - case PORT: - String portType = portTemplateConsolidationData.getPortType(); - if (Objects.isNull(computeTemplateConsolidationData) - || (computeTemplateConsolidationData.getPorts().get(portType) != null - && computeTemplateConsolidationData.getPorts().get(portType).size() > 1)) { - paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" - + nodeTemplateId + "_" + propertyId; + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(PropertyType.FLOAT.getDisplayName()); + addInputParameter(countInputParameterId, PropertyType.LIST.getDisplayName(), entrySchema, substitutionServiceTemplate); + Map> countPropertyValueInputParam = getPropertyValueInputParam(countInputParameterId); + serviceTemplatePropertyMap.remove(ToscaConstants.COUNT_PROPERTY_NAME); + serviceTemplatePropertyMap.put(ToscaConstants.COUNT_PROPERTY_NAME, countPropertyValueInputParam); + } + + private void handleNodeTypeProperties(ServiceTemplate substitutionServiceTemplate, List entityConsolidationDataList, + NodeTemplate nodeTemplate, UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Optional enrichNodeType; + List enrichProperties; + if (compositionEntity.equals(UnifiedCompositionEntity.PORT)) { + enrichNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType.NETWORK_PORT, context.getGlobalServiceTemplates().values()); + enrichProperties = TranslationContext.getEnrichPortResourceProperties(); + if (!enrichNodeType.isPresent() || Objects.isNull(enrichProperties)) { + return; + } } else { - paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" - + propertyId; - } - break; - case SUB_INTERFACE: - paramterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), nodeTemplateId, propertyId, - portTemplateConsolidationData); - break; - default: - break; - } - return paramterId; - } - - private String getSubInterfaceInputParameterId(String type, - String nodeTemplateId, - String propertyId, - PortTemplateConsolidationData portTemplateConsolidationData) { - String subInterfaceType = getSubInterfaceTypeSuffix(type); - if (Objects.isNull(portTemplateConsolidationData) - || portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(type)) { - return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" - + nodeTemplateId + "_" + propertyId; - } - return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" - + subInterfaceType + "_" + propertyId; - } - - private void removeConnectivityOut(EntityConsolidationData entityConsolidationData, - NodeTemplate nodeTemplate) { + return; + } + Map nodeTemplateProperties = nodeTemplate.getProperties(); + Map enrichNodeTypeProperties = enrichNodeType.get().getProperties(); + if (Objects.nonNull(enrichNodeTypeProperties)) { + for (String enrichPropertyName : enrichProperties) { + handleEntityConsolidationDataNodeTypeProperties(enrichPropertyName, substitutionServiceTemplate, enrichNodeType.get(), nodeTemplate, + compositionEntity, computeTemplateConsolidationData, entityConsolidationDataList, nodeTemplateProperties, context); + } + } + } - Multimap nodesConnectedOut = entityConsolidationData.getNodesConnectedOut(); + private void handleEntityConsolidationDataNodeTypeProperties(String enrichPropertyName, ServiceTemplate substitutionServiceTemplate, + NodeType enrichNodeType, NodeTemplate nodeTemplate, + UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List entityConsolidationDataList, + Map nodeTemplateProperties, TranslationContext context) { + String propertyType; + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String inputParamId = getParameterId(nodeTemplateId, nodeTemplate, enrichPropertyName, compositionEntity, + computeTemplateConsolidationData, (PortTemplateConsolidationData) entityConsolidationData); + Map propertyValMap = new HashMap<>(); + context.addNewPropertyIdToNodeTemplate(ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate), inputParamId, + nodeTemplateProperties.get(enrichPropertyName)); + if (nodeTemplateProperties.containsKey(enrichPropertyName)) { + handleExistingEnrichedProperty(enrichPropertyName, nodeTemplateProperties, inputParamId); + } else { + propertyValMap.put(GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(enrichPropertyName, propertyValMap); + } + propertyType = enrichNodeType.getProperties().get(enrichPropertyName).getType(); + addPropertyInputParameter(propertyType, substitutionServiceTemplate, + enrichNodeType.getProperties().get(enrichPropertyName).getEntry_schema(), inputParamId); + } + } - if (CommonUtil.isMultimapEmpty(nodesConnectedOut)) { + private void handleExistingEnrichedProperty(String enrichPropertyName, Map nodeTemplateProperties, String inputParamId) { + Object enrichedProperty = nodeTemplateProperties.get(enrichPropertyName); + if (!isPropertyContainsToscaFunction(enrichedProperty)) { + Map propertyWithGetInput = new HashMap<>(); + propertyWithGetInput.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplateProperties.put(enrichPropertyName, propertyWithGetInput); + } + } + + private boolean isPropertyContainsToscaFunction(Object propertyValue) { + ToscaFunctions[] values = ToscaFunctions.values(); + for (ToscaFunctions toscaFunction : values) { + if (isIncludeToscaFunc(propertyValue, toscaFunction)) { + return true; + } + } + return false; + } + + private void addPropertyInputParameter(String propertyType, ServiceTemplate substitutionServiceTemplate, EntrySchema entrySchema, + String parameterId) { + if (Objects.isNull(propertyType)) { return; } + if (isParameterBelongsToEnrichedPortProperties(parameterId)) { + addInputParameter(parameterId, propertyType, propertyType.equals(PropertyType.LIST.getDisplayName()) ? entrySchema : null, + substitutionServiceTemplate); + } else if (isPropertySimpleType(propertyType)) { + addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), + DataModelUtil.createEntrySchema(propertyType.toLowerCase(), null, null), substitutionServiceTemplate); + } else if (propertyType.equals(PropertyTypeExt.JSON.getDisplayName()) || (Objects.nonNull(entrySchema) && isPropertySimpleType( + entrySchema.getType()))) { + addInputParameter(parameterId, PropertyType.LIST.getDisplayName(), + DataModelUtil.createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), substitutionServiceTemplate); + } else { + addInputParameter(parameterId, analyzeParameterType(propertyType), + DataModelUtil.createEntrySchema(analyzeEntrySchemaType(propertyType, entrySchema), null, null), substitutionServiceTemplate); + } + } + + private boolean isParameterBelongsToEnrichedPortProperties(String parameterId) { + List enrichPortResourceProperties = TranslationContext.getEnrichPortResourceProperties(); + for (int i = 0; i < enrichPortResourceProperties.size(); i++) { + if (parameterId.contains((CharSequence) enrichPortResourceProperties.get(i))) { + return true; + } + } + return false; + } + + private boolean isPropertySimpleType(String propertyType) { + return !Objects.isNull(propertyType) && (PropertyType.getSimplePropertyTypes().contains(propertyType.toLowerCase())); + } + + private String analyzeParameterType(String propertyType) { + return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) ? PropertyType.LIST.getDisplayName() : propertyType; + } + + private String analyzeEntrySchemaType(String propertyType, EntrySchema entrySchema) { + return propertyType.equalsIgnoreCase(PropertyType.LIST.getDisplayName()) && entrySchema != null ? entrySchema.getType() : null; + } + + private void handleConsolidationEntitiesRequirementConnectivity(NodeTemplate nodeTemplate, ServiceTemplate serviceTemplate, + TranslationContext context) { + List> nodeTemplateRequirements = DataModelUtil.getNodeTemplateRequirementList(nodeTemplate); + if (CollectionUtils.isEmpty(nodeTemplateRequirements)) { + return; + } + for (Map requirement : nodeTemplateRequirements) { + for (Map.Entry entry : requirement.entrySet()) { + RequirementAssignment requirementAssignment = entry.getValue(); + String requirementNode = requirementAssignment.getNode(); + String unifiedNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, requirementNode); + if (unifiedNodeTemplateId != null) { + //Update the node id in the requirement + requirementAssignment.setNode(unifiedNodeTemplateId); + } + } + } + nodeTemplate.setRequirements(nodeTemplateRequirements); + } + + /** + * Update the node references in the volume relationship templates. + * + * @param serviceTemplate the service template + * @param context the context + */ + private void updateVolumeRelationshipTemplate(ServiceTemplate serviceTemplate, String relationshipId, TranslationContext context) { + Map relationshipTemplates = DataModelUtil.getRelationshipTemplates(serviceTemplate); + if (relationshipTemplates != null) { + RelationshipTemplate relationshipTemplate = relationshipTemplates.get(relationshipId); + if (relationshipTemplate != null) { + String relationshipTemplateType = relationshipTemplate.getType(); + if (relationshipTemplateType.equals(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO)) { + handleCinderVolumeAttachmentRelationshipTemplate(serviceTemplate, relationshipTemplate, context); + } + } + } + } + + private void handleCinderVolumeAttachmentRelationshipTemplate(ServiceTemplate substitutionServiceTemplate, + RelationshipTemplate relationshipTemplate, TranslationContext context) { + Map properties = relationshipTemplate.getProperties(); + properties.computeIfPresent(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, + (key, value) -> context.getUnifiedAbstractNodeTemplateId(substitutionServiceTemplate, (String) value)); + } + + private String updateIdenticalProperty(String nodeTemplateId, String propertyId, NodeTemplate nodeTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + List unifiedCompositionDataList) { + String inputParamId = null; + Map propertyVal = new HashMap<>(); + switch (unifiedCompositionEntity) { + case COMPUTE: + inputParamId = COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX + propertyId + COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(propertyId, propertyVal); + break; + case PORT: + PortTemplateConsolidationData portTemplateConsolidationData = getPortTemplateConsolidationDataForPort(unifiedCompositionDataList, + nodeTemplateId); + String portType = null; + if (Objects.nonNull(portTemplateConsolidationData)) { + portType = portTemplateConsolidationData.getPortType(); + } + ComputeTemplateConsolidationData computeTemplateConsolidationData = getConnectedComputeConsolidationData(unifiedCompositionDataList, + nodeTemplateId); + inputParamId = getInputParamIdForPort(nodeTemplateId, propertyId, portType, computeTemplateConsolidationData); + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), inputParamId); + nodeTemplate.getProperties().put(propertyId, propertyVal); + break; + default: + break; + } + return inputParamId; + } + + private String getInputParamIdForPort(String nodeTemplateId, String propertyId, String portType, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + String inputParamId; + if (Objects.isNull(computeTemplateConsolidationData) || computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + inputParamId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } else { + inputParamId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" + propertyId; + } + return inputParamId; + } + + private void addInputParameter(String parameterId, String parameterType, EntrySchema entrySchema, ServiceTemplate serviceTemplate) { + ParameterDefinition parameterDefinition = DataModelUtil.createParameterDefinition(parameterType, null, true, null, entrySchema, null); + DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); + } + + // Return the input parameter Id which is used in the new property value if there is one + private Optional updateProperty(ServiceTemplate serviceTemplate, String nodeTemplateId, NodeTemplate nodeTemplate, + Map.Entry propertyEntry, UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData, + List unifiedCompositionDataList, TranslationContext context) { + if (handleGetAttrFromConsolidationNodes(serviceTemplate, nodeTemplateId, nodeTemplate, propertyEntry, unifiedCompositionDataList, context)) { + return Optional.empty(); + } + String inputParamId = getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, + computeTemplateConsolidationData, portTemplateConsolidationData); + Map> propertyVal = getPropertyValueInputParam(inputParamId); + nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); + return Optional.of(inputParamId); + } + + private Map> getPropertyValueInputParam(String inputParamId) { + Map> propertyVal = new HashMap<>(); + List getInputFuncParams = new ArrayList<>(); + getInputFuncParams.add(inputParamId); + getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + propertyVal.put(ToscaFunctions.GET_INPUT.getFunctionName(), getInputFuncParams); + return propertyVal; + } + + private boolean handleGetAttrFromConsolidationNodes(ServiceTemplate serviceTemplate, String nodeTemplateId, NodeTemplate nodeTemplate, + Map.Entry propertyEntry, + List unifiedCompositionDataList, TranslationContext context) { + Map consolidationNodeTemplateIdAndType = getAllConsolidationNodeTemplateIdAndType( + unifiedCompositionDataList); + Set consolidationNodeTemplateIds = consolidationNodeTemplateIdAndType.keySet(); + Map entityIdToType = ConsolidationService.getConsolidationEntityIdToType(serviceTemplate, context.getConsolidationData()); + boolean includeGetAttrFromConsolidationNodes = false; + boolean includeGetAttrFromOutsideNodes = false; + boolean isGetAttrFromConsolidationIsFromSameType = false; + List> getAttrFunctionList = extractGetAttrFunction(propertyEntry.getValue()); + for (List getAttrFunc : getAttrFunctionList) { + String getAttrNodeId = (String) getAttrFunc.get(0); + if (consolidationNodeTemplateIds.contains(getAttrNodeId)) { + includeGetAttrFromConsolidationNodes = true; + if (isGetAttrNodeTemplateFromSameType(nodeTemplateId, getAttrNodeId, entityIdToType)) { + isGetAttrFromConsolidationIsFromSameType = true; + } + } else { + includeGetAttrFromOutsideNodes = true; + } + } + if ((includeGetAttrFromConsolidationNodes && includeGetAttrFromOutsideNodes) || (includeGetAttrFromConsolidationNodes && isIncludeToscaFunc( + propertyEntry.getValue(), ToscaFunctions.GET_INPUT))) { + //This case is currently not supported - this property will be ignored + return true; + } else if (includeGetAttrFromConsolidationNodes && !isGetAttrFromConsolidationIsFromSameType) { + Object clonedPropertyValue = getClonedPropertyValue(propertyEntry); + List> clonedGetAttrFuncList = extractGetAttrFunction(clonedPropertyValue); + for (List getAttrFunc : clonedGetAttrFuncList) { + String targetNodeTemplateId = (String) getAttrFunc.get(0); + if (consolidationNodeTemplateIds.contains(targetNodeTemplateId)) { + updatePropertyGetAttrFunc(serviceTemplate, unifiedCompositionDataList, consolidationNodeTemplateIdAndType, targetNodeTemplateId, + getAttrFunc, context); + } + } + nodeTemplate.getProperties().put(propertyEntry.getKey(), clonedPropertyValue); + return true; + } + return false; + } + + private boolean isGetAttrNodeTemplateFromSameType(String sourceNodeTemplateId, String targetNodeTemplateId, + Map nodeTemplateIdToType) { + if (Objects.isNull(nodeTemplateIdToType.get(sourceNodeTemplateId)) || Objects.isNull(nodeTemplateIdToType.get(targetNodeTemplateId))) { + return false; + } + return nodeTemplateIdToType.get(sourceNodeTemplateId).equals(nodeTemplateIdToType.get(targetNodeTemplateId)); + } + + private void updatePropertyGetAttrFunc(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + Map consolidationNodeTemplateIdAndType, String targetNodeTemplateId, + List getAttrFunc, TranslationContext context) { + UnifiedCompositionEntity targetCompositionEntity = consolidationNodeTemplateIdAndType.get(targetNodeTemplateId); + String targetNewNodeTemplateId = getNewNodeTemplateId(serviceTemplate, unifiedCompositionDataList, targetNodeTemplateId, + targetCompositionEntity, context); + getAttrFunc.set(0, targetNewNodeTemplateId); + } + + private String getNewNodeTemplateId(ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + String nodeTemplateId, UnifiedCompositionEntity compositionEntity, TranslationContext context) { + String newNodeTemplateId = nodeTemplateId; + String nodeTemplateIdGeneratorImpl = unifiedSubstitutionNodeTemplateIdGeneratorImplMap.get(compositionEntity); + UnifiedSubstitutionNodeTemplateIdGenerator nodeTemplateIdGenerator = CommonMethods + .newInstance(nodeTemplateIdGeneratorImpl, UnifiedSubstitutionNodeTemplateIdGenerator.class); + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, null, unifiedCompositionDataList, context, null); + Optional generatedNodeTemplateId = nodeTemplateIdGenerator.generate(unifiedCompositionTo, nodeTemplateId); + if (generatedNodeTemplateId.isPresent()) { + newNodeTemplateId = generatedNodeTemplateId.get(); + } + return newNodeTemplateId; + } - nodesConnectedOut.values().forEach(requirementAssignmentData -> - DataModelUtil.removeRequirementsAssignment(nodeTemplate.getRequirements(), - requirementAssignmentData.getRequirementId()) - ); + private String getNewNodeTemplateId(String origNodeTemplateId, String serviceTemplateFileName, ServiceTemplate serviceTemplate, + TranslationContext context) { + ConsolidationData consolidationData = context.getConsolidationData(); + if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.PORT, serviceTemplateFileName, context)) { + return handleIdOfPort(origNodeTemplateId, serviceTemplateFileName, consolidationData); + } else if (isIdIsOfExpectedType(origNodeTemplateId, COMPUTE, serviceTemplateFileName, context)) { + NodeTemplate nodeTemplate = getComputeNodeTemplate(origNodeTemplateId, serviceTemplate, context); + return getComputeTypeSuffix(nodeTemplate.getType()); + } + return null; + } + private Object getClonedPropertyValue(Map.Entry propertyEntry) { + if (propertyEntry.getValue() instanceof Map) { + return getClonedObject(propertyEntry.getValue(), Map.class); + } else if (propertyEntry.getValue() instanceof List) { + return getClonedObject(propertyEntry.getValue(), List.class); + } + return propertyEntry.getValue(); + } + + private String getParameterId(String nodeTemplateId, NodeTemplate nodeTemplate, String propertyId, + UnifiedCompositionEntity unifiedCompositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData) { + String paramterId = propertyId; + switch (unifiedCompositionEntity) { + case COMPUTE: + paramterId = COMPUTE.getDisplayName().toLowerCase() + "_" + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; + break; + case PORT: + String portType = portTemplateConsolidationData.getPortType(); + if (Objects.isNull(computeTemplateConsolidationData) || (computeTemplateConsolidationData.getPorts().get(portType) != null + && computeTemplateConsolidationData.getPorts().get(portType).size() > 1)) { + paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } else { + paramterId = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_" + portType + "_" + propertyId; + } + break; + case SUB_INTERFACE: + paramterId = getSubInterfaceInputParameterId(nodeTemplate.getType(), nodeTemplateId, propertyId, portTemplateConsolidationData); + break; + default: + break; + } + return paramterId; + } + + private String getSubInterfaceInputParameterId(String type, String nodeTemplateId, String propertyId, + PortTemplateConsolidationData portTemplateConsolidationData) { + String subInterfaceType = getSubInterfaceTypeSuffix(type); + if (Objects.isNull(portTemplateConsolidationData) || portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(type)) { + return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" + nodeTemplateId + "_" + propertyId; + } + return UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_" + subInterfaceType + "_" + propertyId; + } + + private void removeConnectivityOut(EntityConsolidationData entityConsolidationData, NodeTemplate nodeTemplate) { + Multimap nodesConnectedOut = entityConsolidationData.getNodesConnectedOut(); + if (CommonUtil.isMultimapEmpty(nodesConnectedOut)) { + return; + } + nodesConnectedOut.values().forEach(requirementAssignmentData -> DataModelUtil + .removeRequirementsAssignment(nodeTemplate.getRequirements(), requirementAssignmentData.getRequirementId())); if (nodeTemplate.getRequirements().isEmpty()) { nodeTemplate.setRequirements(null); } } - private void removeVolumeConnectivity(ComputeTemplateConsolidationData computeTemplateConsolidationData, - NodeTemplate computeNodeTemplate) { + private void removeVolumeConnectivity(ComputeTemplateConsolidationData computeTemplateConsolidationData, NodeTemplate computeNodeTemplate) { if (CommonUtil.isMultimapEmpty(computeTemplateConsolidationData.getVolumes())) { return; } - - computeTemplateConsolidationData.getVolumes().values().forEach(requirementAssignmentData -> - DataModelUtil.removeRequirementsAssignment(computeNodeTemplate.getRequirements(), - requirementAssignmentData.getRequirementId()) - ); - + computeTemplateConsolidationData.getVolumes().values().forEach(requirementAssignmentData -> DataModelUtil + .removeRequirementsAssignment(computeNodeTemplate.getRequirements(), requirementAssignmentData.getRequirementId())); if (computeNodeTemplate.getRequirements().isEmpty()) { computeNodeTemplate.setRequirements(null); } } - private void createIndexInputParameter(ServiceTemplate substitutionServiceTemplate) { - ParameterDefinition indexParameterDefinition = - DataModelUtil.createParameterDefinition(PropertyType.INTEGER.getDisplayName(), - "Index value of this substitution service template runtime instance", - false, createIndexValueConstraint(), null, 0); - DataModelUtil.addInputParameterToTopologyTemplate(substitutionServiceTemplate, - ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexParameterDefinition); - } - - - private List createIndexValueConstraint() { - List constraints; - constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setGreater_or_equal(0); - constraints.add(constraint); - return constraints; - } - - private Optional getUnifiedCompositionInstance(UnifiedCompositionMode mode) { - String unifiedCompositionImplClassName = - unifiedCompositionImplMap.get(mode.name()).getImplementationClass(); - if (StringUtils.isEmpty(unifiedCompositionImplClassName)) { - return Optional.empty(); - } - return Optional - .of(CommonMethods.newInstance(unifiedCompositionImplClassName, UnifiedComposition.class)); - } - - private Optional> createAbstractSubstitutionProperties( - ServiceTemplate serviceTemplate, - Map substitutionTemplateInputs, - List unifiedCompositionDataList, - TranslationContext context) { - Map abstractSubstituteProperties = new LinkedHashMap<>(); - //Since all the computes have the same type fetching the type from the first entry - NodeTemplate firstComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - unifiedCompositionDataList.get(0) - .getComputeTemplateConsolidationData().getNodeTemplateId()); - String computeType = getComputeTypeSuffix(firstComputeNodeTemplate.getType()); - for (Map.Entry input : substitutionTemplateInputs.entrySet()) { - String substitutionTemplateInputName = input.getKey(); - ParameterDefinition inputParameterDefinition = input.getValue(); - String inputType = inputParameterDefinition.getType(); - UnifiedCompositionEntity inputUnifiedCompositionEntity = - getInputCompositionEntity(substitutionTemplateInputName); - - if (isIdenticalValueProperty(substitutionTemplateInputName, inputUnifiedCompositionEntity) - || !inputType.equalsIgnoreCase(PropertyType.LIST.getDisplayName())) { - //Handle identical value properties - Optional identicalValuePropertyName = - getIdenticalValuePropertyName(substitutionTemplateInputName, - inputUnifiedCompositionEntity); - - identicalValuePropertyName.ifPresent(propertyName -> updateIdenticalPropertyValue(propertyName, - substitutionTemplateInputName, inputUnifiedCompositionEntity, - unifiedCompositionDataList.get(0), serviceTemplate, abstractSubstituteProperties, - context)); - continue; - } - - //Check if the input is of type compute, port or sub interface - List abstractPropertyValue = new ArrayList<>(); - switch (inputUnifiedCompositionEntity) { - case COMPUTE: - createAbstractComputeProperties(unifiedCompositionDataList, - substitutionTemplateInputName, serviceTemplate, abstractPropertyValue); - break; - case PORT: - createAbstractPortProperties(unifiedCompositionDataList, substitutionTemplateInputName, - computeType, serviceTemplate, abstractPropertyValue); - break; - case SUB_INTERFACE: - createAbstractSubInterfaceProperties(unifiedCompositionDataList, - substitutionTemplateInputName, serviceTemplate, abstractPropertyValue); - break; - default: - break; - } - //Add the property only if it has at least one non-null value - if (abstractPropertyValue.stream().anyMatch(Objects::nonNull)) { - updateAbstractPropertyValue(substitutionTemplateInputName, inputParameterDefinition, - abstractPropertyValue, abstractSubstituteProperties); - } - } - return Optional.ofNullable(abstractSubstituteProperties); - } - - private void createAbstractComputeProperties(List - unifiedCompositionDataList, - String substitutionTemplateInputName, - ServiceTemplate serviceTemplate, - List abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - compositionData.getComputeTemplateConsolidationData(); - Object propertyValue = getComputePropertyValue(substitutionTemplateInputName, - serviceTemplate, computeTemplateConsolidationData); - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - - private void createAbstractPortProperties(List - unifiedCompositionDataList, - String substitutionTemplateInputName, - String computeType, - ServiceTemplate serviceTemplate, - List abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(compositionData); - //Get the input type for this input whether it is of type - // port__ or port__ - PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, - compositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - //Get the port property value - String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); - Object propertyValue = getPortPropertyValue(substitutionTemplateInputName, - computeType, portInputType, serviceTemplate, - portNodeTemplateId, portTemplateConsolidationData); - //If the value object is Optional.empty it implies that the property name was not - // found in the input name - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - } - - private void createAbstractSubInterfaceProperties(List - unifiedCompositionDataList, - String substitutionTemplateInputName, - ServiceTemplate serviceTemplate, - List abstractPropertyValue) { - for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(compositionData); - //Get the input type for this input whether it is of type - // subInterface__ or - // subInterface__ - PropertyInputType subInterfaceInputType = - getSubInterfaceInputType(substitutionTemplateInputName, compositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - //Get the subInterface property value - String subInterfaceNodeTemplateId = subInterfaceTemplateConsolidationData - .getNodeTemplateId(); - NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - subInterfaceNodeTemplateId); - String subInterfaceType = getSubInterfaceTypeSuffix(subInterfaceNodeTemplate - .getType()); - Object propertyValue = getSubInterfacePropertyValue(substitutionTemplateInputName, - subInterfaceType, subInterfaceInputType, serviceTemplate, - subInterfaceNodeTemplateId); - //If the value object is Optional.empty it implies that the property name was not - // found in the input name - if (!(propertyValue instanceof Optional)) { - abstractPropertyValue.add(propertyValue); - } - } - } - } - - private void updateAbstractPropertyValue(String substitutionTemplateInputName, - ParameterDefinition parameterDefinition, - List abstractPropertyValue, - Map abstractSubstituteProperties) { - if (abstractPropertyValue.size() > 1) { - abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); - } else { - Object propertyValue = abstractPropertyValue.get(0); - String entrySchemaType = parameterDefinition.getEntry_schema().getType(); - if (PropertyType.getSimplePropertyTypes().contains(entrySchemaType.toLowerCase()) - || entrySchemaType.equals(PropertyTypeExt.JSON.getDisplayName())) { - abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); - } else { - abstractSubstituteProperties.put(substitutionTemplateInputName, propertyValue); - } - } - } - - private void updateIdenticalPropertyValue(String identicalValuePropertyName, - String substitutionTemplateInputName, - UnifiedCompositionEntity entity, - UnifiedCompositionData unifiedCompositionData, - ServiceTemplate serviceTemplate, - Map abstractSubstituteProperties, - TranslationContext context) { - Optional identicalPropertyValueByType = - getIdenticalPropertyValueByType(identicalValuePropertyName, substitutionTemplateInputName, - entity, unifiedCompositionData, serviceTemplate, context); - - if (identicalPropertyValueByType.isPresent()) { - abstractSubstituteProperties - .put(substitutionTemplateInputName, identicalPropertyValueByType.get()); - - } - - - } - - private Optional getIdenticalPropertyValueByType(String identicalValuePropertyName, - String substitutionTemplateInputName, - UnifiedCompositionEntity entity, - UnifiedCompositionData - unifiedCompositionData, - ServiceTemplate serviceTemplate, - TranslationContext context) { - - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - - Optional identicalPropertyValue = Optional.empty(); - switch (entity) { - case COMPUTE: - identicalPropertyValue = - getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - computeTemplateConsolidationData, context); - break; - case OTHER: - identicalPropertyValue = - getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - computeTemplateConsolidationData, context); - break; - case PORT: - PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, - unifiedCompositionData); - Optional portTemplateConsolidationData = - unifiedCompositionData.getPortTemplateConsolidationDataList() - .stream() - .filter(s -> substitutionTemplateInputName. - contains(getPropertyInputPrefix(s.getNodeTemplateId(), - s.getPortType(), - portInputType, UnifiedCompositionEntity.PORT))) - .findFirst(); - - if(portTemplateConsolidationData.isPresent()) { - return getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, - portTemplateConsolidationData.get(), context); - } - break; - default: - break; - } - return identicalPropertyValue; - } - - - private PropertyInputType getPortInputType(String inputName, - UnifiedCompositionData unifiedCompositionData) { - String portInputPrefix = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_"; - ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData - .getComputeTemplateConsolidationData(); - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - //Scan the available port node template ids to check if the input is of the form - // "port__" - if (portTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) - .map(portNodeTemplateId -> portInputPrefix + portNodeTemplateId).anyMatch(inputName::startsWith)) { - return PropertyInputType.NODE_TEMPLATE_ID; - } - //Check whether the input is of the form "port__" - Set portTypes = computeTemplateConsolidationData.getPorts().keySet(); - if (portTypes.stream().map(portType -> portInputPrefix + portType + "_").anyMatch(inputName::startsWith)) { - return PropertyInputType.TYPE; - } - return PropertyInputType.OTHER; - } - - private PropertyInputType getSubInterfaceInputType(String inputName, - UnifiedCompositionData unifiedCompositionData) { - String subInterfaceInputPrefix = UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() - + "_"; - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - //Scan the available port node template ids to check if the input is of the form - // "subinterface__" - if (subInterfaceTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) - .map(subInterfaceNodeTemplateId -> subInterfaceInputPrefix - + subInterfaceNodeTemplateId) - .anyMatch(inputName::startsWith)) { - return PropertyInputType.NODE_TEMPLATE_ID; - } - //Check whether the input is of the form "subinterface__" - Set subInterfaceTypes = new HashSet<>(); - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - ListMultimap subInterfaceTypeToEntity = ArrayListMultimap.create(); - portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); - subInterfaceTypes.addAll(subInterfaceTypeToEntity.keySet()); - } - - if (subInterfaceTypes.stream().map(UnifiedCompositionUtil::getSubInterfaceTypeSuffix) - .map(subInterfaceTypeSuffix -> subInterfaceInputPrefix + subInterfaceTypeSuffix + "_") - .anyMatch(inputName::startsWith)) { - return PropertyInputType.TYPE; - } - return PropertyInputType.OTHER; - } - - private void cleanServiceTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - removeNodeTemplateFromServiceTemplate(serviceTemplate, entity, context); - updateHeatStackGroup(serviceTemplate, entity, context); - updateSubstitutionMapping(serviceTemplate, context); - } + private void createIndexInputParameter(ServiceTemplate substitutionServiceTemplate) { + ParameterDefinition indexParameterDefinition = DataModelUtil + .createParameterDefinition(PropertyType.INTEGER.getDisplayName(), "Index value of this substitution service template runtime instance", + false, createIndexValueConstraint(), null, 0); + DataModelUtil + .addInputParameterToTopologyTemplate(substitutionServiceTemplate, ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexParameterDefinition); + } - private void removeNodeTemplateFromServiceTemplate(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - String nodeTemplateIdToRemove = entity.getNodeTemplateId(); - Map nodeTemplates = - serviceTemplate.getTopology_template().getNode_templates(); - NodeTemplate nodeTemplateToRemove = - nodeTemplates.get(nodeTemplateIdToRemove); - nodeTemplates.remove(nodeTemplateIdToRemove); - - context.addCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - nodeTemplateIdToRemove, - entity.getClass() == ComputeTemplateConsolidationData.class - ? COMPUTE - : UnifiedCompositionEntity.PORT, - nodeTemplateToRemove); - - } - - private void removeCleanedNodeType(String cleanedNodeTemplateId, - ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeTemplate cleanedNodeTemplate = - context - .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - cleanedNodeTemplateId); - String typeToRemove = cleanedNodeTemplate.getType(); + private List createIndexValueConstraint() { + List constraints; + constraints = new ArrayList<>(); + Constraint constraint = new Constraint(); + constraint.setGreater_or_equal(0); + constraints.add(constraint); + return constraints; + } - if (Objects.nonNull(typeToRemove) - && serviceTemplate.getNode_types().containsKey(typeToRemove)) { - serviceTemplate.getNode_types().remove(typeToRemove); + private Optional getUnifiedCompositionInstance(UnifiedCompositionMode mode) { + String unifiedCompositionImplClassName = unifiedCompositionImplMap.get(mode.name()).getImplementationClass(); + if (StringUtils.isEmpty(unifiedCompositionImplClassName)) { + return Optional.empty(); + } + return Optional.of(CommonMethods.newInstance(unifiedCompositionImplClassName, UnifiedComposition.class)); + } + + private Optional> createAbstractSubstitutionProperties(ServiceTemplate serviceTemplate, + Map substitutionTemplateInputs, + List unifiedCompositionDataList, + TranslationContext context) { + Map abstractSubstituteProperties = new LinkedHashMap<>(); + //Since all the computes have the same type fetching the type from the first entry + NodeTemplate firstComputeNodeTemplate = DataModelUtil + .getNodeTemplate(serviceTemplate, unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData().getNodeTemplateId()); + String computeType = getComputeTypeSuffix(firstComputeNodeTemplate.getType()); + for (Map.Entry input : substitutionTemplateInputs.entrySet()) { + String substitutionTemplateInputName = input.getKey(); + ParameterDefinition inputParameterDefinition = input.getValue(); + String inputType = inputParameterDefinition.getType(); + UnifiedCompositionEntity inputUnifiedCompositionEntity = getInputCompositionEntity(substitutionTemplateInputName); + if (isIdenticalValueProperty(substitutionTemplateInputName, inputUnifiedCompositionEntity) || !inputType + .equalsIgnoreCase(PropertyType.LIST.getDisplayName())) { + //Handle identical value properties + Optional identicalValuePropertyName = getIdenticalValuePropertyName(substitutionTemplateInputName, + inputUnifiedCompositionEntity); + identicalValuePropertyName.ifPresent( + propertyName -> updateIdenticalPropertyValue(propertyName, substitutionTemplateInputName, inputUnifiedCompositionEntity, + unifiedCompositionDataList.get(0), serviceTemplate, abstractSubstituteProperties, context)); + continue; + } + //Check if the input is of type compute, port or sub interface + List abstractPropertyValue = new ArrayList<>(); + switch (inputUnifiedCompositionEntity) { + case COMPUTE: + createAbstractComputeProperties(unifiedCompositionDataList, substitutionTemplateInputName, serviceTemplate, + abstractPropertyValue); + break; + case PORT: + createAbstractPortProperties(unifiedCompositionDataList, substitutionTemplateInputName, computeType, serviceTemplate, + abstractPropertyValue); + break; + case SUB_INTERFACE: + createAbstractSubInterfaceProperties(unifiedCompositionDataList, substitutionTemplateInputName, serviceTemplate, + abstractPropertyValue); + break; + default: + break; + } + //Add the property only if it has at least one non-null value + if (abstractPropertyValue.stream().anyMatch(Objects::nonNull)) { + updateAbstractPropertyValue(substitutionTemplateInputName, inputParameterDefinition, abstractPropertyValue, + abstractSubstituteProperties); + } + } + return Optional.ofNullable(abstractSubstituteProperties); } - } - private void updateHeatStackGroup(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - Map groups = serviceTemplate.getTopology_template() - .getGroups() == null ? new HashMap<>() - : serviceTemplate.getTopology_template().getGroups(); - String nodeRelatedAbstractNodeId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entity.getNodeTemplateId()); - - for (Map.Entry groupEntry : groups.entrySet()) { - GroupDefinition groupDefinition = groupEntry.getValue(); - if (isHeatStackGroup(groupDefinition.getType())) { - updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nodeRelatedAbstractNodeId, - groupEntry); - } - } - } - - private void updateGroupMembersWithNewUnifiedNodeTemplateId( - EntityConsolidationData entity, - String newNodetemplateId, - Map.Entry groupEntry) { - List members = groupEntry.getValue().getMembers(); - if (members.contains(entity.getNodeTemplateId())) { - members.remove(entity.getNodeTemplateId()); - if (!members.contains(newNodetemplateId)) { - members.add(newNodetemplateId); - } - } - groupEntry.getValue().setMembers(members); - } - - private void updateSubstitutionMapping(ServiceTemplate serviceTemplate, - TranslationContext context) { - SubstitutionMapping substitutionMappings = - DataModelUtil.getSubstitutionMappings(serviceTemplate); - if (Objects.nonNull(substitutionMappings)) { + private void createAbstractComputeProperties(List unifiedCompositionDataList, String substitutionTemplateInputName, + ServiceTemplate serviceTemplate, List abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = compositionData.getComputeTemplateConsolidationData(); + Object propertyValue = getComputePropertyValue(substitutionTemplateInputName, serviceTemplate, computeTemplateConsolidationData); + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } - if (Objects.nonNull(substitutionMappings.getRequirements())) { - updateSubstitutionMappingRequirements(substitutionMappings.getRequirements(), - serviceTemplate, context); - } + private void createAbstractPortProperties(List unifiedCompositionDataList, String substitutionTemplateInputName, + String computeType, ServiceTemplate serviceTemplate, List abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(compositionData); + //Get the input type for this input whether it is of type + + // port__ or port__ + PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, compositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + //Get the port property value + String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + Object propertyValue = getPortPropertyValue(substitutionTemplateInputName, computeType, portInputType, serviceTemplate, + portNodeTemplateId, portTemplateConsolidationData); + //If the value object is Optional.empty it implies that the property name was not + + // found in the input name + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } + } - if (Objects.nonNull(substitutionMappings.getCapabilities())) { - updateSubstitutionMappingCapabilities(substitutionMappings.getCapabilities(), - serviceTemplate, context); - } + private void createAbstractSubInterfaceProperties(List unifiedCompositionDataList, String substitutionTemplateInputName, + ServiceTemplate serviceTemplate, List abstractPropertyValue) { + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + compositionData); + //Get the input type for this input whether it is of type + + // subInterface__ or + + // subInterface__ + PropertyInputType subInterfaceInputType = getSubInterfaceInputType(substitutionTemplateInputName, compositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + //Get the subInterface property value + String subInterfaceNodeTemplateId = subInterfaceTemplateConsolidationData.getNodeTemplateId(); + NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceNodeTemplateId); + String subInterfaceType = getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); + Object propertyValue = getSubInterfacePropertyValue(substitutionTemplateInputName, subInterfaceType, subInterfaceInputType, + serviceTemplate, subInterfaceNodeTemplateId); + //If the value object is Optional.empty it implies that the property name was not + + // found in the input name + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } } - } - private void updateSubstitutionMappingRequirements(Map> - substitutionMappingRequirements, - ServiceTemplate serviceTemplate, - TranslationContext context) { - for (Map.Entry> entry : substitutionMappingRequirements.entrySet()) { - List requirement = entry.getValue(); - String oldNodeTemplateId = requirement.get(0); - String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, - requirement.get(0)); - String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId( - serviceTemplate, oldNodeTemplateId); - if (Objects.nonNull(newAbstractNodeTemplateId) - && Objects.nonNull(newSubstitutionNodeTemplateId)) { - requirement.set(0, newAbstractNodeTemplateId); - String newRequirementValue = requirement.get(1) + "_" + newSubstitutionNodeTemplateId; - requirement.set(1, newRequirementValue); - } - } - } - - private void updateSubstitutionMappingCapabilities(Map> - substitutionMappingCapabilities, - ServiceTemplate serviceTemplate, - TranslationContext context) { - for (Map.Entry> entry : substitutionMappingCapabilities.entrySet()) { - List capability = entry.getValue(); - String oldNodeTemplateId = capability.get(0); - String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, - capability.get(0)); - String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId( - serviceTemplate, oldNodeTemplateId); - if (Objects.nonNull(newAbstractNodeTemplateId) - && Objects.nonNull(newSubstitutionNodeTemplateId)) { - capability.set(0, newAbstractNodeTemplateId); - String newRequirementValue = capability.get(1) + "_" + newSubstitutionNodeTemplateId; - capability.set(1, newRequirementValue); - } - } - } - - private void updateHeatStackGroupNestedComposition(ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - Map groups = serviceTemplate.getTopology_template() - .getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); - String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - Optional nestedNodeTemplateId = - context.getUnifiedNestedNodeTemplateId(serviceTemplateFileName, entity.getNodeTemplateId()); - if (nestedNodeTemplateId.isPresent()) { - for (Map.Entry groupEntry : groups.entrySet()) { - GroupDefinition groupDefinition = groupEntry.getValue(); - if (isHeatStackGroup(groupDefinition.getType())) { - updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nestedNodeTemplateId.get(), - groupEntry); - } - } - } - } - - private void handleNestedNodeTemplateInMainServiceTemplate(String nestedNodeTemplateId, - ServiceTemplate mainServiceTemplate, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(mainServiceTemplate, - nestedNodeTemplateId); - if (Objects.isNull(nestedNodeTemplate)) { - return; - } - - updateNestedNodeTemplateProperties(nestedServiceTemplate, nestedNodeTemplate, context); - - Optional unifiedNestedNodeTypeId = context - .getUnifiedNestedNodeTypeId( - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), - nestedNodeTemplate.getType()); - unifiedNestedNodeTypeId - .ifPresent(unifiedNestedNodeTypeIdVal -> updateNestedNodeTemplate( - unifiedNestedNodeTypeIdVal, nestedNodeTemplateId, nestedNodeTemplate, - mainServiceTemplate, context)); - } - - private void updateNestedNodeTemplateProperties(ServiceTemplate nestedServiceTemplate, - NodeTemplate nestedNodeTemplate, - TranslationContext context) { + private void updateAbstractPropertyValue(String substitutionTemplateInputName, ParameterDefinition parameterDefinition, + List abstractPropertyValue, Map abstractSubstituteProperties) { + if (abstractPropertyValue.size() > 1) { + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } else { + Object propertyValue = abstractPropertyValue.get(0); + String entrySchemaType = parameterDefinition.getEntry_schema().getType(); + if (PropertyType.getSimplePropertyTypes().contains(entrySchemaType.toLowerCase()) || entrySchemaType + .equals(PropertyTypeExt.JSON.getDisplayName())) { + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } else { + abstractSubstituteProperties.put(substitutionTemplateInputName, propertyValue); + } + } + } - Map newPropertyInputParamIds = - context.getAllNewPropertyInputParamIdsPerNodeTenplateId(ToscaUtil - .getServiceTemplateFileName(nestedServiceTemplate)); + private void updateIdenticalPropertyValue(String identicalValuePropertyName, String substitutionTemplateInputName, + UnifiedCompositionEntity entity, UnifiedCompositionData unifiedCompositionData, + ServiceTemplate serviceTemplate, Map abstractSubstituteProperties, + TranslationContext context) { + Optional identicalPropertyValueByType = getIdenticalPropertyValueByType(identicalValuePropertyName, substitutionTemplateInputName, + entity, unifiedCompositionData, serviceTemplate, context); + if (identicalPropertyValueByType.isPresent()) { + abstractSubstituteProperties.put(substitutionTemplateInputName, identicalPropertyValueByType.get()); + } + } - for (Map.Entry entry : newPropertyInputParamIds.entrySet()) { - if (Objects.nonNull(entry.getValue())) { - Object value = getClonedObject(entry.getValue()); - nestedNodeTemplate.getProperties().put(entry.getKey(), value); - } + private Optional getIdenticalPropertyValueByType(String identicalValuePropertyName, String substitutionTemplateInputName, + UnifiedCompositionEntity entity, UnifiedCompositionData unifiedCompositionData, + ServiceTemplate serviceTemplate, TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + Optional identicalPropertyValue = Optional.empty(); + switch (entity) { + case COMPUTE: + identicalPropertyValue = getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, computeTemplateConsolidationData, + context); + break; + case OTHER: + identicalPropertyValue = getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, computeTemplateConsolidationData, + context); + break; + case PORT: + PropertyInputType portInputType = getPortInputType(substitutionTemplateInputName, unifiedCompositionData); + Optional portTemplateConsolidationData = unifiedCompositionData.getPortTemplateConsolidationDataList() + .stream().filter(s -> substitutionTemplateInputName + .contains(getPropertyInputPrefix(s.getNodeTemplateId(), s.getPortType(), portInputType, UnifiedCompositionEntity.PORT))) + .findFirst(); + if (portTemplateConsolidationData.isPresent()) { + return getIdenticalPropertyValue(identicalValuePropertyName, serviceTemplate, portTemplateConsolidationData.get(), context); + } + break; + default: + break; + } + return identicalPropertyValue; } - String subNodeType = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type(); - nestedNodeTemplate.setType(subNodeType); + private PropertyInputType getPortInputType(String inputName, UnifiedCompositionData unifiedCompositionData) { + String portInputPrefix = UnifiedCompositionEntity.PORT.getDisplayName().toLowerCase() + "_"; + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + //Scan the available port node template ids to check if the input is of the form + + // "port__" + if (portTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) + .map(portNodeTemplateId -> portInputPrefix + portNodeTemplateId).anyMatch(inputName::startsWith)) { + return PropertyInputType.NODE_TEMPLATE_ID; + } + //Check whether the input is of the form "port__" + Set portTypes = computeTemplateConsolidationData.getPorts().keySet(); + if (portTypes.stream().map(portType -> portInputPrefix + portType + "_").anyMatch(inputName::startsWith)) { + return PropertyInputType.TYPE; + } + return PropertyInputType.OTHER; + } - } + private PropertyInputType getSubInterfaceInputType(String inputName, UnifiedCompositionData unifiedCompositionData) { + String subInterfaceInputPrefix = UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName().toLowerCase() + "_"; + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + //Scan the available port node template ids to check if the input is of the form - private void handleSubstitutionMappingInNestedServiceTemplate( - String newNestedNodeType, - ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - if (Objects.isNull(newNestedNodeType)) { - return; + // "subinterface__" + if (subInterfaceTemplateConsolidationDataList.stream().map(EntityConsolidationData::getNodeTemplateId) + .map(subInterfaceNodeTemplateId -> subInterfaceInputPrefix + subInterfaceNodeTemplateId).anyMatch(inputName::startsWith)) { + return PropertyInputType.NODE_TEMPLATE_ID; + } + //Check whether the input is of the form "subinterface__" + Set subInterfaceTypes = new HashSet<>(); + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + ListMultimap subInterfaceTypeToEntity = ArrayListMultimap.create(); + portTemplateConsolidationData.copyMappedInto(subInterfaceTypeToEntity); + subInterfaceTypes.addAll(subInterfaceTypeToEntity.keySet()); + } + if (subInterfaceTypes.stream().map(UnifiedCompositionUtil::getSubInterfaceTypeSuffix) + .map(subInterfaceTypeSuffix -> subInterfaceInputPrefix + subInterfaceTypeSuffix + "_").anyMatch(inputName::startsWith)) { + return PropertyInputType.TYPE; + } + return PropertyInputType.OTHER; } - Set relatedNestedNodeTypeIds = - context.getAllRelatedNestedNodeTypeIds(); + private void cleanServiceTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + removeNodeTemplateFromServiceTemplate(serviceTemplate, entity, context); + updateHeatStackGroup(serviceTemplate, entity, context); + updateSubstitutionMapping(serviceTemplate, context); + } - SubstitutionMapping substitutionMappings = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); - if (!relatedNestedNodeTypeIds.contains(substitutionMappings.getNode_type())) { - substitutionMappings.setNode_type(newNestedNodeType); + private void removeNodeTemplateFromServiceTemplate(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + String nodeTemplateIdToRemove = entity.getNodeTemplateId(); + Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); + NodeTemplate nodeTemplateToRemove = nodeTemplates.get(nodeTemplateIdToRemove); + nodeTemplates.remove(nodeTemplateIdToRemove); + context.addCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), nodeTemplateIdToRemove, + entity.getClass() == ComputeTemplateConsolidationData.class ? COMPUTE : UnifiedCompositionEntity.PORT, nodeTemplateToRemove); } - } - private void updateNestedNodeTemplate(String newNestedNodeTypeId, - String nestedNodeTemplateId, - NodeTemplate nestedNodeTemplate, - ServiceTemplate mainServiceTemplate, - TranslationContext context) { - String mainSTName = ToscaUtil.getServiceTemplateFileName(mainServiceTemplate); - String globalSTName = - ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - int index = - context.getHandledNestedComputeNodeTemplateIndex(globalSTName, newNestedNodeTypeId); - String newNodeTemplateId = - Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) - + "_" + index; - - nestedNodeTemplate.setType(newNestedNodeTypeId); - mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); - mainServiceTemplate.getTopology_template().getNode_templates() - .put(newNodeTemplateId, nestedNodeTemplate); - - context.addUnifiedNestedNodeTemplateId(mainSTName, nestedNodeTemplateId, newNodeTemplateId); - } - - private void handleNestedNodeTypesInGlobalSubstituteServiceTemplate( - String origNestedNodeTypeId, - String newNestedNodeTypeId, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { - Set relatedNestedNodeTypeIds = - context.getAllRelatedNestedNodeTypeIds(); - - Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); - if (!relatedNestedNodeTypeIds.contains(origNestedNodeTypeId)) { - NodeType nested = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, - origNestedNodeTypeId); - setNewValuesForNestedNodeType(origNestedNodeTypeId, newNestedNodeTypeId, nested, nodeTypes); - } else { - NodeType nested = - (NodeType) DataModelUtil.getClonedObject( - DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId)); - nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - nodeTypes.put(newNestedNodeTypeId, nested); - } - context.addUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - origNestedNodeTypeId, newNestedNodeTypeId); - } - - private void setNewValuesForNestedNodeType(String origNestedNodeType, - String newNestedNodeTypeId, - NodeType nested, - Map nodeTypes) { - if (Objects.nonNull(nested)) { - nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); - nodeTypes.remove(origNestedNodeType); - nodeTypes.put(newNestedNodeTypeId, nested); - } - } - - private Optional getNewNestedNodeTypeId(ServiceTemplate nestedServiceTemplate, - TranslationContext context) { - FileComputeConsolidationData fileComputeConsolidationData = - context.getConsolidationData().getComputeConsolidationData() - .getFileComputeConsolidationData( - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - - if (Objects.nonNull(fileComputeConsolidationData)) { - String nestedNodeTypePrefix = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat."; - return Optional - .of(nestedNodeTypePrefix + getComputeTypeInNestedFile(fileComputeConsolidationData)); - } - return Optional.empty(); - } - - private String getComputeTypeInNestedFile( - FileComputeConsolidationData fileComputeConsolidationData) { - List typeComputeConsolidationDatas = - new ArrayList<>(fileComputeConsolidationData.getAllTypeComputeConsolidationData()); - if (typeComputeConsolidationDatas.isEmpty()) { - return null; - } else { - String computeNodeType = fileComputeConsolidationData.getAllComputeTypes().iterator().next(); - return getComputeTypeSuffix(computeNodeType); - } - } - - private void handleGetAttrInAbstractNodeTemplate(ServiceTemplate serviceTemplate, - TranslationContext context, - String serviceTemplateFileName, - NodeTemplate abstractNodeTemplate) { - Map properties = - abstractNodeTemplate == null || abstractNodeTemplate.getProperties() == null - ? new HashMap<>() - : abstractNodeTemplate.getProperties(); - for (Object propertyValue : properties.values()) { - List> getAttrList = extractGetAttrFunction(propertyValue); - for (List getAttrFuncValue : getAttrList) { - String origNodeTemplateId = (String) getAttrFuncValue.get(0); - Optional nestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId(ToscaUtil - .getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + private void removeCleanedNodeType(String cleanedNodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate cleanedNodeTemplate = context + .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), cleanedNodeTemplateId); + String typeToRemove = cleanedNodeTemplate.getType(); + if (Objects.nonNull(typeToRemove) && serviceTemplate.getNode_types().containsKey(typeToRemove)) { + serviceTemplate.getNode_types().remove(typeToRemove); + } + } + + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + Map groups = + serviceTemplate.getTopology_template().getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); + String nodeRelatedAbstractNodeId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entity.getNodeTemplateId()); + for (Map.Entry groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nodeRelatedAbstractNodeId, groupEntry); + } + } + } + + private void updateGroupMembersWithNewUnifiedNodeTemplateId(EntityConsolidationData entity, String newNodetemplateId, + Map.Entry groupEntry) { + List members = groupEntry.getValue().getMembers(); + if (members.contains(entity.getNodeTemplateId())) { + members.remove(entity.getNodeTemplateId()); + if (!members.contains(newNodetemplateId)) { + members.add(newNodetemplateId); + } + } + groupEntry.getValue().setMembers(members); + } + + private void updateSubstitutionMapping(ServiceTemplate serviceTemplate, TranslationContext context) { + SubstitutionMapping substitutionMappings = DataModelUtil.getSubstitutionMappings(serviceTemplate); + if (Objects.nonNull(substitutionMappings)) { + if (Objects.nonNull(substitutionMappings.getRequirements())) { + updateSubstitutionMappingRequirements(substitutionMappings.getRequirements(), serviceTemplate, context); + } + if (Objects.nonNull(substitutionMappings.getCapabilities())) { + updateSubstitutionMappingCapabilities(substitutionMappings.getCapabilities(), serviceTemplate, context); + } + } + } + + private void updateSubstitutionMappingRequirements(Map> substitutionMappingRequirements, ServiceTemplate serviceTemplate, + TranslationContext context) { + for (Map.Entry> entry : substitutionMappingRequirements.entrySet()) { + List requirement = entry.getValue(); + String oldNodeTemplateId = requirement.get(0); + String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, requirement.get(0)); + String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, oldNodeTemplateId); + if (Objects.nonNull(newAbstractNodeTemplateId) && Objects.nonNull(newSubstitutionNodeTemplateId)) { + requirement.set(0, newAbstractNodeTemplateId); + String newRequirementValue = requirement.get(1) + "_" + newSubstitutionNodeTemplateId; + requirement.set(1, newRequirementValue); + } + } + } + + private void updateSubstitutionMappingCapabilities(Map> substitutionMappingCapabilities, ServiceTemplate serviceTemplate, + TranslationContext context) { + for (Map.Entry> entry : substitutionMappingCapabilities.entrySet()) { + List capability = entry.getValue(); + String oldNodeTemplateId = capability.get(0); + String newAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, capability.get(0)); + String newSubstitutionNodeTemplateId = context.getUnifiedSubstitutionNodeTemplateId(serviceTemplate, oldNodeTemplateId); + if (Objects.nonNull(newAbstractNodeTemplateId) && Objects.nonNull(newSubstitutionNodeTemplateId)) { + capability.set(0, newAbstractNodeTemplateId); + String newRequirementValue = capability.get(1) + "_" + newSubstitutionNodeTemplateId; + capability.set(1, newRequirementValue); + } + } + } + + private void updateHeatStackGroupNestedComposition(ServiceTemplate serviceTemplate, EntityConsolidationData entity, TranslationContext context) { + Map groups = + serviceTemplate.getTopology_template().getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional nestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId(serviceTemplateFileName, entity.getNodeTemplateId()); if (nestedNodeTemplateId.isPresent()) { - getAttrFuncValue.set(0, nestedNodeTemplateId.get()); + for (Map.Entry groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nestedNodeTemplateId.get(), groupEntry); + } + } + } + } + + private void handleNestedNodeTemplateInMainServiceTemplate(String nestedNodeTemplateId, ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, TranslationContext context) { + NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(mainServiceTemplate, nestedNodeTemplateId); + if (Objects.isNull(nestedNodeTemplate)) { + return; + } + updateNestedNodeTemplateProperties(nestedServiceTemplate, nestedNodeTemplate, context); + Optional unifiedNestedNodeTypeId = context + .getUnifiedNestedNodeTypeId(ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME), + nestedNodeTemplate.getType()); + unifiedNestedNodeTypeId.ifPresent( + unifiedNestedNodeTypeIdVal -> updateNestedNodeTemplate(unifiedNestedNodeTypeIdVal, nestedNodeTemplateId, nestedNodeTemplate, + mainServiceTemplate, context)); + } + + private void updateNestedNodeTemplateProperties(ServiceTemplate nestedServiceTemplate, NodeTemplate nestedNodeTemplate, + TranslationContext context) { + Map newPropertyInputParamIds = context + .getAllNewPropertyInputParamIdsPerNodeTenplateId(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + for (Map.Entry entry : newPropertyInputParamIds.entrySet()) { + if (Objects.nonNull(entry.getValue())) { + Object value = getClonedObject(entry.getValue()); + nestedNodeTemplate.getProperties().put(entry.getKey(), value); + } + } + String subNodeType = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type(); + nestedNodeTemplate.setType(subNodeType); + } + + private void handleSubstitutionMappingInNestedServiceTemplate(String newNestedNodeType, ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + if (Objects.isNull(newNestedNodeType)) { + return; + } + Set relatedNestedNodeTypeIds = context.getAllRelatedNestedNodeTypeIds(); + SubstitutionMapping substitutionMappings = nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + if (!relatedNestedNodeTypeIds.contains(substitutionMappings.getNode_type())) { + substitutionMappings.setNode_type(newNestedNodeType); + } + } + + private void updateNestedNodeTemplate(String newNestedNodeTypeId, String nestedNodeTemplateId, NodeTemplate nestedNodeTemplate, + ServiceTemplate mainServiceTemplate, TranslationContext context) { + String mainSTName = ToscaUtil.getServiceTemplateFileName(mainServiceTemplate); + String globalSTName = ToscaUtil.getServiceTemplateFileName(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + int index = context.getHandledNestedComputeNodeTemplateIndex(globalSTName, newNestedNodeTypeId); + String newNodeTemplateId = Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) + "_" + index; + nestedNodeTemplate.setType(newNestedNodeTypeId); + mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); + mainServiceTemplate.getTopology_template().getNode_templates().put(newNodeTemplateId, nestedNodeTemplate); + context.addUnifiedNestedNodeTemplateId(mainSTName, nestedNodeTemplateId, newNodeTemplateId); + } + + private void handleNestedNodeTypesInGlobalSubstituteServiceTemplate(String origNestedNodeTypeId, String newNestedNodeTypeId, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + Set relatedNestedNodeTypeIds = context.getAllRelatedNestedNodeTypeIds(); + Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + if (!relatedNestedNodeTypeIds.contains(origNestedNodeTypeId)) { + NodeType nested = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId); + setNewValuesForNestedNodeType(origNestedNodeTypeId, newNestedNodeTypeId, nested, nodeTypes); } else { - replaceGetAttrNodeIdAndAttrName(serviceTemplate, context, serviceTemplateFileName, - getAttrFuncValue); + NodeType nested = (NodeType) DataModelUtil + .getClonedObject(DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, origNestedNodeTypeId)); + nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + nodeTypes.put(newNestedNodeTypeId, nested); } - } + context.addUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, origNestedNodeTypeId, newNestedNodeTypeId); } - } - private void replaceGetAttrNodeIdAndAttrName(ServiceTemplate serviceTemplate, - TranslationContext context, - String serviceTemplateFileName, - List getAttrFuncValue) { - String origNodeTemplateId = (String) getAttrFuncValue.get(0); - String attributeName = (String) getAttrFuncValue.get(1); + private void setNewValuesForNestedNodeType(String origNestedNodeType, String newNestedNodeTypeId, NodeType nested, + Map nodeTypes) { + if (Objects.nonNull(nested)) { + nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + nodeTypes.remove(origNestedNodeType); + nodeTypes.put(newNestedNodeTypeId, nested); + } + } - String unifiedAbstractNodeTemplateId = - context.getUnifiedAbstractNodeTemplateId(serviceTemplate, origNodeTemplateId); + private Optional getNewNestedNodeTypeId(ServiceTemplate nestedServiceTemplate, TranslationContext context) { + FileComputeConsolidationData fileComputeConsolidationData = context.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + if (Objects.nonNull(fileComputeConsolidationData)) { + String nestedNodeTypePrefix = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat."; + return Optional.of(nestedNodeTypePrefix + getComputeTypeInNestedFile(fileComputeConsolidationData)); + } + return Optional.empty(); + } - if (Objects.isNull(unifiedAbstractNodeTemplateId)) { - return; + private String getComputeTypeInNestedFile(FileComputeConsolidationData fileComputeConsolidationData) { + List typeComputeConsolidationDatas = new ArrayList<>( + fileComputeConsolidationData.getAllTypeComputeConsolidationData()); + if (typeComputeConsolidationDatas.isEmpty()) { + return null; + } else { + String computeNodeType = fileComputeConsolidationData.getAllComputeTypes().iterator().next(); + return getComputeTypeSuffix(computeNodeType); + } } - String newNodeTemplateId = - getNewNodeTemplateId(origNodeTemplateId, serviceTemplateFileName, serviceTemplate, context); + private void handleGetAttrInAbstractNodeTemplate(ServiceTemplate serviceTemplate, TranslationContext context, String serviceTemplateFileName, + NodeTemplate abstractNodeTemplate) { + Map properties = + abstractNodeTemplate == null || abstractNodeTemplate.getProperties() == null ? new HashMap<>() : abstractNodeTemplate.getProperties(); + for (Object propertyValue : properties.values()) { + List> getAttrList = extractGetAttrFunction(propertyValue); + for (List getAttrFuncValue : getAttrList) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + Optional nestedNodeTemplateId = context + .getUnifiedNestedNodeTemplateId(ToscaUtil.getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + if (nestedNodeTemplateId.isPresent()) { + getAttrFuncValue.set(0, nestedNodeTemplateId.get()); + } else { + replaceGetAttrNodeIdAndAttrName(serviceTemplate, context, serviceTemplateFileName, getAttrFuncValue); + } + } + } + } - String newSubstitutionOutputParameterId = - getNewSubstitutionOutputParameterId(newNodeTemplateId, attributeName); + private void replaceGetAttrNodeIdAndAttrName(ServiceTemplate serviceTemplate, TranslationContext context, String serviceTemplateFileName, + List getAttrFuncValue) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + String attributeName = (String) getAttrFuncValue.get(1); + String unifiedAbstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId(serviceTemplate, origNodeTemplateId); + if (Objects.isNull(unifiedAbstractNodeTemplateId)) { + return; + } + String newNodeTemplateId = getNewNodeTemplateId(origNodeTemplateId, serviceTemplateFileName, serviceTemplate, context); + String newSubstitutionOutputParameterId = getNewSubstitutionOutputParameterId(newNodeTemplateId, attributeName); + getAttrFuncValue.set(0, unifiedAbstractNodeTemplateId); + getAttrFuncValue.set(1, newSubstitutionOutputParameterId); + } - getAttrFuncValue.set(0, unifiedAbstractNodeTemplateId); - getAttrFuncValue.set(1, newSubstitutionOutputParameterId); - } + private NodeTemplate getComputeNodeTemplate(String origNodeTemplateId, ServiceTemplate serviceTemplate, TranslationContext context) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, origNodeTemplateId); + if (computeNodeTemplate == null) { + computeNodeTemplate = context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + } + return computeNodeTemplate; + } - private NodeTemplate getComputeNodeTemplate(String origNodeTemplateId, - ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeTemplate computeNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, origNodeTemplateId); - if (computeNodeTemplate == null) { - computeNodeTemplate = - context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), - origNodeTemplateId); - } - return computeNodeTemplate; - } - - private String handleIdOfPort(String origNodeTemplateId, String serviceTemplateFileName, - ConsolidationData consolidationData) { - Optional> - computeTypeAndComputeTemplateByPortId = - getComputeTypeAndComputeTemplateByPortId(origNodeTemplateId, serviceTemplateFileName, - consolidationData); - if (computeTypeAndComputeTemplateByPortId.isPresent()) { - Pair computeIdToComputeData = - computeTypeAndComputeTemplateByPortId.get(); - return getNewPortNodeTemplateId(origNodeTemplateId, computeIdToComputeData.getKey(), - computeIdToComputeData.getValue()); - } - - return null; - } - - private Optional> - getComputeTypeAndComputeTemplateByPortId(String portId, String serviceTemplateFileName, - ConsolidationData consolidationData) { - FileComputeConsolidationData fileComputeConsolidationData = - consolidationData.getComputeConsolidationData() - .getFileComputeConsolidationData(serviceTemplateFileName); - Set computeTypes = - fileComputeConsolidationData.getAllComputeTypes(); - - for (String computeType : computeTypes) { - Collection computeTemplateConsolidationDatas = - fileComputeConsolidationData.getTypeComputeConsolidationData(computeType) - .getAllComputeTemplateConsolidationData(); - - for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDatas) { - if (ConsolidationDataUtil.isComputeReferenceToPortId(compute, portId)) { - return Optional.of(new ImmutablePair<>(computeType, compute)); - } - } - } - - return Optional.empty(); - } - - private boolean isIdIsOfExpectedType(String id, - UnifiedCompositionEntity expectedUnifiedCompositionEntity, - String serviceTemplateFileName, - TranslationContext context) { - UnifiedSubstitutionData unifiedSubstitutionData = - context.getUnifiedSubstitutionData().get(serviceTemplateFileName); - if (Objects.isNull(unifiedSubstitutionData)) { - return false; - } - - UnifiedCompositionEntity actualUnifiedCompositionEntity = - unifiedSubstitutionData.getCleanedNodeTemplateCompositionEntity(id); - - return actualUnifiedCompositionEntity == null ? false - : actualUnifiedCompositionEntity.equals(expectedUnifiedCompositionEntity); - } - - private boolean isHeatStackGroup(String groupType) { - return groupType.equals(ToscaGroupType.HEAT_STACK); - } - - private Object getPortPropertyValue(String inputName, - String computeType, - PropertyInputType portInputType, - ServiceTemplate serviceTemplate, - String portNodeTemplateId, - PortTemplateConsolidationData portTemplateConsolidationData) { - //Get the input prefix to extract the property name from the input name - String portType = portTemplateConsolidationData.getPortType(); - String portInputPrefix = getPropertyInputPrefix( - portNodeTemplateId, portType, portInputType, UnifiedCompositionEntity.PORT); - //Get the property name from the input - Optional propertyName = getPropertyNameFromInput(inputName, - UnifiedCompositionEntity.PORT, computeType, portInputPrefix); - //Get the property value from the node template - if (propertyName.isPresent()) { - NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - portNodeTemplateId); - if (Objects.nonNull(portNodeTemplate)) { - return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); - } - } - return Optional.empty(); - } - - private Object getComputePropertyValue( - String inputName, - ServiceTemplate serviceTemplate, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - computeTemplateConsolidationData.getNodeTemplateId()); - String nodeType = getComputeTypeSuffix(nodeTemplate.getType()); - Optional propertyName = - getPropertyNameFromInput(inputName, COMPUTE, nodeType, null); - if (propertyName.isPresent()) { - return getPropertyValueFromNodeTemplate(propertyName.get(), nodeTemplate); - } - return Optional.empty(); - } - - private Object getSubInterfacePropertyValue(String inputName, - String subInterfaceTypeSuffix, - PropertyInputType propertyInputType, - ServiceTemplate serviceTemplate, - String subInterfaceNodeTemplateId) { - //Get the input prefix to extract the property name from the input name - String propertyInputPrefix = getPropertyInputPrefix(subInterfaceNodeTemplateId, - subInterfaceTypeSuffix, propertyInputType, UnifiedCompositionEntity.SUB_INTERFACE); - //Get the property name from the input - Optional propertyName = getPropertyNameFromInput(inputName, - UnifiedCompositionEntity.SUB_INTERFACE, null, propertyInputPrefix); - //Get the property value from the node template - if (propertyName.isPresent()) { - NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, - subInterfaceNodeTemplateId); - if (Objects.nonNull(subInterfaceNodeTemplate)) { - return getPropertyValueFromNodeTemplate(propertyName.get(), subInterfaceNodeTemplate); - } - } - return Optional.empty(); - } - - private Optional getIdenticalPropertyValue(String identicalValuePropertyName, - ServiceTemplate serviceTemplate, - EntityConsolidationData entity, - TranslationContext context) { - NodeTemplate nodeTemplate = - getNodeTemplate(entity.getNodeTemplateId(), serviceTemplate, context); - - Object propertyValueFromNodeTemplate = - getPropertyValueFromNodeTemplate(identicalValuePropertyName, nodeTemplate); - - return Objects.isNull(propertyValueFromNodeTemplate) ? Optional.empty() - : Optional.of(propertyValueFromNodeTemplate); - } - - private UnifiedCompositionEntity getInputCompositionEntity(String inputName) { - UnifiedCompositionEntity inputCompositionEntity = UnifiedCompositionEntity.OTHER; - if (inputName.indexOf('_') != -1) { - String inputType = inputName.substring(0, inputName.indexOf('_')); - if (inputType.equalsIgnoreCase(COMPUTE.getDisplayName())) { - inputCompositionEntity = COMPUTE; - } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.PORT.getDisplayName())) { - inputCompositionEntity = UnifiedCompositionEntity.PORT; - } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.SUB_INTERFACE - .getDisplayName())) { - inputCompositionEntity = UnifiedCompositionEntity.SUB_INTERFACE; - } - } - return inputCompositionEntity; - } - - private Optional getPropertyNameFromInput( - String inputName, - UnifiedCompositionEntity compositionEntity, - String entityType, String propertyInputPrefix) { - String propertyName = null; - switch (compositionEntity) { - case COMPUTE: - propertyName = inputName.substring(inputName.lastIndexOf(entityType) - + entityType.length() + 1); - break; - case PORT: - case SUB_INTERFACE: - if (inputName.startsWith(propertyInputPrefix)) { - propertyName = inputName.split(propertyInputPrefix)[1]; - } - break; - default: - break; - } - return Optional.ofNullable(propertyName); - } - - private String getPropertyInputPrefix(String nodeTemplateId, - String propertyEntityType, - PropertyInputType propertyInputType, - UnifiedCompositionEntity unifiedCompositionEntity) { - String propertyInputPrefix = unifiedCompositionEntity.getDisplayName().toLowerCase() + "_"; - if (propertyInputType == PropertyInputType.NODE_TEMPLATE_ID) { - propertyInputPrefix += nodeTemplateId + "_"; - } else if (propertyInputType == PropertyInputType.TYPE) { - propertyInputPrefix += propertyEntityType + "_"; - } - return propertyInputPrefix; - } - - private boolean isIdenticalValueProperty(String inputName, - UnifiedCompositionEntity unifiedCompositionEntity) { - - List identicalValuePropertyList = - consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); - - StringBuilder builder = getPropertyValueStringBuilder(unifiedCompositionEntity); - if (Objects.isNull(builder)) { - return false; - } - - boolean isMatchingProperty = Pattern.matches(builder.toString(), inputName); - return isMatchingProperty - && isPropertyFromIdenticalValuesList(inputName, unifiedCompositionEntity, - identicalValuePropertyList); - } - - private boolean isPropertyFromIdenticalValuesList(String inputName, - UnifiedCompositionEntity unifiedCompositionEntity, - List identicalValuePropertyList) { - switch (unifiedCompositionEntity) { - case COMPUTE: - case OTHER: - Optional identicalValueProperty = getIdenticalValuePropertyName(inputName, unifiedCompositionEntity); - return identicalValueProperty.filter(identicalValuePropertyList::contains).isPresent(); - - case PORT: - return getPortPropertyNameFromInput(inputName, identicalValuePropertyList).isPresent(); - - default: - return false; + private String handleIdOfPort(String origNodeTemplateId, String serviceTemplateFileName, ConsolidationData consolidationData) { + Optional> computeTypeAndComputeTemplateByPortId = getComputeTypeAndComputeTemplateByPortId( + origNodeTemplateId, serviceTemplateFileName, consolidationData); + if (computeTypeAndComputeTemplateByPortId.isPresent()) { + Pair computeIdToComputeData = computeTypeAndComputeTemplateByPortId.get(); + return getNewPortNodeTemplateId(origNodeTemplateId, computeIdToComputeData.getKey(), computeIdToComputeData.getValue()); + } + return null; } - } - private Optional getPortPropertyNameFromInput(String inputName, - List identicalValuePropertyList) { - for (String identicalProperty : identicalValuePropertyList) { - if (inputName.endsWith(identicalProperty)) { - return Optional.of(identicalProperty); - } + private Optional> getComputeTypeAndComputeTemplateByPortId(String portId, + String serviceTemplateFileName, + ConsolidationData consolidationData) { + FileComputeConsolidationData fileComputeConsolidationData = consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(serviceTemplateFileName); + Set computeTypes = fileComputeConsolidationData.getAllComputeTypes(); + for (String computeType : computeTypes) { + Collection computeTemplateConsolidationDatas = fileComputeConsolidationData + .getTypeComputeConsolidationData(computeType).getAllComputeTemplateConsolidationData(); + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDatas) { + if (ConsolidationDataUtil.isComputeReferenceToPortId(compute, portId)) { + return Optional.of(new ImmutablePair<>(computeType, compute)); + } + } + } + return Optional.empty(); } - return Optional.empty(); - } - private StringBuilder getPropertyValueStringBuilder( - UnifiedCompositionEntity unifiedCompositionEntity) { + private boolean isIdIsOfExpectedType(String id, UnifiedCompositionEntity expectedUnifiedCompositionEntity, String serviceTemplateFileName, + TranslationContext context) { + UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData().get(serviceTemplateFileName); + if (Objects.isNull(unifiedSubstitutionData)) { + return false; + } + UnifiedCompositionEntity actualUnifiedCompositionEntity = unifiedSubstitutionData.getCleanedNodeTemplateCompositionEntity(id); + return actualUnifiedCompositionEntity == null ? false : actualUnifiedCompositionEntity.equals(expectedUnifiedCompositionEntity); + } - switch (unifiedCompositionEntity) { - case COMPUTE: - return getComputePropertyValueStringBuilder(); + private boolean isHeatStackGroup(String groupType) { + return groupType.equals(ToscaGroupType.HEAT_STACK); + } - case OTHER: - return getComputePropertyValueStringBuilder(); + private Object getPortPropertyValue(String inputName, String computeType, PropertyInputType portInputType, ServiceTemplate serviceTemplate, + String portNodeTemplateId, PortTemplateConsolidationData portTemplateConsolidationData) { + //Get the input prefix to extract the property name from the input name + String portType = portTemplateConsolidationData.getPortType(); + String portInputPrefix = getPropertyInputPrefix(portNodeTemplateId, portType, portInputType, UnifiedCompositionEntity.PORT); + //Get the property name from the input + Optional propertyName = getPropertyNameFromInput(inputName, UnifiedCompositionEntity.PORT, computeType, portInputPrefix); + //Get the property value from the node template + if (propertyName.isPresent()) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, portNodeTemplateId); + if (Objects.nonNull(portNodeTemplate)) { + return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); + } + } + return Optional.empty(); + } - case PORT: - return getPortPropertyValueStringBuilder(); + private Object getComputePropertyValue(String inputName, ServiceTemplate serviceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + String nodeType = getComputeTypeSuffix(nodeTemplate.getType()); + Optional propertyName = getPropertyNameFromInput(inputName, COMPUTE, nodeType, null); + if (propertyName.isPresent()) { + return getPropertyValueFromNodeTemplate(propertyName.get(), nodeTemplate); + } + return Optional.empty(); + } - case SUB_INTERFACE: - return getSubInterfacePropertyValueStringBuilder(); + private Object getSubInterfacePropertyValue(String inputName, String subInterfaceTypeSuffix, PropertyInputType propertyInputType, + ServiceTemplate serviceTemplate, String subInterfaceNodeTemplateId) { + //Get the input prefix to extract the property name from the input name + String propertyInputPrefix = getPropertyInputPrefix(subInterfaceNodeTemplateId, subInterfaceTypeSuffix, propertyInputType, + UnifiedCompositionEntity.SUB_INTERFACE); + //Get the property name from the input + Optional propertyName = getPropertyNameFromInput(inputName, UnifiedCompositionEntity.SUB_INTERFACE, null, propertyInputPrefix); + //Get the property value from the node template + if (propertyName.isPresent()) { + NodeTemplate subInterfaceNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceNodeTemplateId); + if (Objects.nonNull(subInterfaceNodeTemplate)) { + return getPropertyValueFromNodeTemplate(propertyName.get(), subInterfaceNodeTemplate); + } + } + return Optional.empty(); + } - default: - return null; + private Optional getIdenticalPropertyValue(String identicalValuePropertyName, ServiceTemplate serviceTemplate, + EntityConsolidationData entity, TranslationContext context) { + NodeTemplate nodeTemplate = getNodeTemplate(entity.getNodeTemplateId(), serviceTemplate, context); + Object propertyValueFromNodeTemplate = getPropertyValueFromNodeTemplate(identicalValuePropertyName, nodeTemplate); + return Objects.isNull(propertyValueFromNodeTemplate) ? Optional.empty() : Optional.of(propertyValueFromNodeTemplate); } - } - - private StringBuilder getPortPropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(PORT_IDENTICAL_VALUE_PROPERTY_PREFIX); - builder.append(".+"); - return builder; - } - - private StringBuilder getComputePropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX); - builder.append("[a-z]+"); - builder.append(COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX); - return builder; - } - - private StringBuilder getSubInterfacePropertyValueStringBuilder() { - StringBuilder builder; - builder = new StringBuilder(SUB_INTERFACE_PROPERTY_VALUE_PREFIX); - builder.append(".+"); - return builder; - } - - private Optional getIdenticalValuePropertyName(String input, - UnifiedCompositionEntity - unifiedCompositionEntity) { - switch (unifiedCompositionEntity) { - case COMPUTE: - return Optional.of(input.split("_")[1]); - - case OTHER: - return Optional.of(input.split("_")[1]); - - case PORT: - return getPortPropertyNameFromInput(input, consolidationService - .getPropertiesWithIdenticalVal(unifiedCompositionEntity)); - - default: + + private UnifiedCompositionEntity getInputCompositionEntity(String inputName) { + UnifiedCompositionEntity inputCompositionEntity = UnifiedCompositionEntity.OTHER; + if (inputName.indexOf('_') != -1) { + String inputType = inputName.substring(0, inputName.indexOf('_')); + if (inputType.equalsIgnoreCase(COMPUTE.getDisplayName())) { + inputCompositionEntity = COMPUTE; + } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.PORT.getDisplayName())) { + inputCompositionEntity = UnifiedCompositionEntity.PORT; + } else if (inputType.equalsIgnoreCase(UnifiedCompositionEntity.SUB_INTERFACE.getDisplayName())) { + inputCompositionEntity = UnifiedCompositionEntity.SUB_INTERFACE; + } + } + return inputCompositionEntity; + } + + private Optional getPropertyNameFromInput(String inputName, UnifiedCompositionEntity compositionEntity, String entityType, + String propertyInputPrefix) { + String propertyName = null; + switch (compositionEntity) { + case COMPUTE: + propertyName = inputName.substring(inputName.lastIndexOf(entityType) + entityType.length() + 1); + break; + case PORT: + case SUB_INTERFACE: + if (inputName.startsWith(propertyInputPrefix)) { + propertyName = inputName.split(propertyInputPrefix)[1]; + } + break; + default: + break; + } + return Optional.ofNullable(propertyName); + } + + private String getPropertyInputPrefix(String nodeTemplateId, String propertyEntityType, PropertyInputType propertyInputType, + UnifiedCompositionEntity unifiedCompositionEntity) { + String propertyInputPrefix = unifiedCompositionEntity.getDisplayName().toLowerCase() + "_"; + if (propertyInputType == PropertyInputType.NODE_TEMPLATE_ID) { + propertyInputPrefix += nodeTemplateId + "_"; + } else if (propertyInputType == PropertyInputType.TYPE) { + propertyInputPrefix += propertyEntityType + "_"; + } + return propertyInputPrefix; + } + + private boolean isIdenticalValueProperty(String inputName, UnifiedCompositionEntity unifiedCompositionEntity) { + List identicalValuePropertyList = consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity); + StringBuilder builder = getPropertyValueStringBuilder(unifiedCompositionEntity); + if (Objects.isNull(builder)) { + return false; + } + boolean isMatchingProperty = Pattern.matches(builder.toString(), inputName); + return isMatchingProperty && isPropertyFromIdenticalValuesList(inputName, unifiedCompositionEntity, identicalValuePropertyList); + } + + private boolean isPropertyFromIdenticalValuesList(String inputName, UnifiedCompositionEntity unifiedCompositionEntity, + List identicalValuePropertyList) { + switch (unifiedCompositionEntity) { + case COMPUTE: + case OTHER: + Optional identicalValueProperty = getIdenticalValuePropertyName(inputName, unifiedCompositionEntity); + return identicalValueProperty.filter(identicalValuePropertyList::contains).isPresent(); + case PORT: + return getPortPropertyNameFromInput(inputName, identicalValuePropertyList).isPresent(); + default: + return false; + } + } + + private Optional getPortPropertyNameFromInput(String inputName, List identicalValuePropertyList) { + for (String identicalProperty : identicalValuePropertyList) { + if (inputName.endsWith(identicalProperty)) { + return Optional.of(identicalProperty); + } + } return Optional.empty(); } - } - - private Object getPropertyValueFromNodeTemplate(String propertyName, NodeTemplate nodeTemplate) { - Map nodeTemplateProperties = nodeTemplate.getProperties(); - if (nodeTemplateProperties != null) { - Object propertyValue; - if (propertyName.startsWith(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { - propertyValue = getServiceTemplateFilterPropertyValue(propertyName, nodeTemplateProperties); - } else { - propertyValue = nodeTemplateProperties.get(propertyName); - propertyValue = getClonedObject(propertyValue); - } - return propertyValue; - } - return null; - } - - private Object getServiceTemplateFilterPropertyValue(String propertyName, - Map nodeTemplateProperties) { - Object propertyValue = null; - Object serviceTemplateFilterProperties = - nodeTemplateProperties.get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - String serviceTemplateFilterPropertyName = - propertyName.replace(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME + "_", ""); - - if (Objects.nonNull(serviceTemplateFilterProperties) - && serviceTemplateFilterProperties instanceof Map) { - propertyValue = ((Map) serviceTemplateFilterProperties).get(serviceTemplateFilterPropertyName); - } - return propertyValue; - } - - private Map getAllConsolidationNodeTemplateIdAndType( - List unifiedCompositionDataList) { - - Map consolidationNodeTemplateIdAndType = new HashMap<>(); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - ComputeTemplateConsolidationData computeTemplateConsolidationData = - unifiedCompositionData.getComputeTemplateConsolidationData(); - if (Objects.nonNull(computeTemplateConsolidationData)) { - consolidationNodeTemplateIdAndType.put(computeTemplateConsolidationData.getNodeTemplateId(), COMPUTE); - } - List subInterfaceTemplateConsolidationDataList = - getSubInterfaceTemplateConsolidationDataList(unifiedCompositionData); - for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : - subInterfaceTemplateConsolidationDataList) { - consolidationNodeTemplateIdAndType.put(subInterfaceTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.SUB_INTERFACE); - } - List portTemplateConsolidationDataList = - getPortTemplateConsolidationDataList(unifiedCompositionData); - for (PortTemplateConsolidationData portTemplateConsolidationData : - portTemplateConsolidationDataList) { - consolidationNodeTemplateIdAndType.put(portTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.PORT); - } - NestedTemplateConsolidationData nestedTemplateConsolidationData = - unifiedCompositionData.getNestedTemplateConsolidationData(); - if (Objects.nonNull(nestedTemplateConsolidationData)) { - consolidationNodeTemplateIdAndType - .put(nestedTemplateConsolidationData.getNodeTemplateId(), - UnifiedCompositionEntity.NESTED); - } - } - return consolidationNodeTemplateIdAndType; - } - - private List getPortTemplateConsolidationDataList( - UnifiedCompositionData unifiedCompositionData) { - return unifiedCompositionData.getPortTemplateConsolidationDataList() == null ? new - ArrayList<>() : unifiedCompositionData.getPortTemplateConsolidationDataList(); - } - - private enum PropertyInputType { - NODE_TEMPLATE_ID, - TYPE, - OTHER - } + + private StringBuilder getPropertyValueStringBuilder(UnifiedCompositionEntity unifiedCompositionEntity) { + switch (unifiedCompositionEntity) { + case COMPUTE: + return getComputePropertyValueStringBuilder(); + case OTHER: + return getComputePropertyValueStringBuilder(); + case PORT: + return getPortPropertyValueStringBuilder(); + case SUB_INTERFACE: + return getSubInterfacePropertyValueStringBuilder(); + default: + return null; + } + } + + private StringBuilder getPortPropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(PORT_IDENTICAL_VALUE_PROPERTY_PREFIX); + builder.append(".+"); + return builder; + } + + private StringBuilder getComputePropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX); + builder.append("[a-z]+"); + builder.append(COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX); + return builder; + } + + private StringBuilder getSubInterfacePropertyValueStringBuilder() { + StringBuilder builder; + builder = new StringBuilder(SUB_INTERFACE_PROPERTY_VALUE_PREFIX); + builder.append(".+"); + return builder; + } + + private Optional getIdenticalValuePropertyName(String input, UnifiedCompositionEntity unifiedCompositionEntity) { + switch (unifiedCompositionEntity) { + case COMPUTE: + return Optional.of(input.split("_")[1]); + case OTHER: + return Optional.of(input.split("_")[1]); + case PORT: + return getPortPropertyNameFromInput(input, consolidationService.getPropertiesWithIdenticalVal(unifiedCompositionEntity)); + default: + return Optional.empty(); + } + } + + private Object getPropertyValueFromNodeTemplate(String propertyName, NodeTemplate nodeTemplate) { + Map nodeTemplateProperties = nodeTemplate.getProperties(); + if (nodeTemplateProperties != null) { + Object propertyValue; + if (propertyName.startsWith(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME)) { + propertyValue = getServiceTemplateFilterPropertyValue(propertyName, nodeTemplateProperties); + } else { + propertyValue = nodeTemplateProperties.get(propertyName); + propertyValue = getClonedObject(propertyValue); + } + return propertyValue; + } + return null; + } + + private Object getServiceTemplateFilterPropertyValue(String propertyName, Map nodeTemplateProperties) { + Object propertyValue = null; + Object serviceTemplateFilterProperties = nodeTemplateProperties.get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + String serviceTemplateFilterPropertyName = propertyName.replace(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME + "_", ""); + if (Objects.nonNull(serviceTemplateFilterProperties) && serviceTemplateFilterProperties instanceof Map) { + propertyValue = ((Map) serviceTemplateFilterProperties).get(serviceTemplateFilterPropertyName); + } + return propertyValue; + } + + private Map getAllConsolidationNodeTemplateIdAndType(List unifiedCompositionDataList) { + Map consolidationNodeTemplateIdAndType = new HashMap<>(); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData.getComputeTemplateConsolidationData(); + if (Objects.nonNull(computeTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType.put(computeTemplateConsolidationData.getNodeTemplateId(), COMPUTE); + } + List subInterfaceTemplateConsolidationDataList = getSubInterfaceTemplateConsolidationDataList( + unifiedCompositionData); + for (SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData : subInterfaceTemplateConsolidationDataList) { + consolidationNodeTemplateIdAndType + .put(subInterfaceTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.SUB_INTERFACE); + } + List portTemplateConsolidationDataList = getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + consolidationNodeTemplateIdAndType.put(portTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.PORT); + } + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.nonNull(nestedTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType.put(nestedTemplateConsolidationData.getNodeTemplateId(), UnifiedCompositionEntity.NESTED); + } + } + return consolidationNodeTemplateIdAndType; + } + + private List getPortTemplateConsolidationDataList(UnifiedCompositionData unifiedCompositionData) { + return unifiedCompositionData.getPortTemplateConsolidationDataList() == null ? new ArrayList<>() + : unifiedCompositionData.getPortTemplateConsolidationDataList(); + } + + private enum PropertyInputType {NODE_TEMPLATE_ID, TYPE, OTHER} } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java index 82fb4b0c8e..00a3ff3ea4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -27,7 +25,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -44,178 +41,157 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolida */ public class UnifiedCompositionUtil { - private UnifiedCompositionUtil() { - //Hiding the implicit public constructor - } - - /** - * Gets all ports per port type, which are connected to the computes from the input - * computeTemplateConsolidationDataCollection. - * - * @param computeTemplateConsolidationDataCollection collection of compute template - * consolidation data - * @return set of port ids, per port type - */ - static Map> collectAllPortsFromEachTypesFromComputes( - Collection computeTemplateConsolidationDataCollection) { - Map> portTypeToIds = new HashMap<>(); - - for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDataCollection) { - Map> ports = compute.getPorts(); - if (!MapUtils.isEmpty(ports)) { - addPortsToMap(portTypeToIds, ports); - } + private UnifiedCompositionUtil() { + //Hiding the implicit public constructor + } + + /** + * Gets all ports per port type, which are connected to the computes from the input computeTemplateConsolidationDataCollection. + * + * @param computeTemplateConsolidationDataCollection collection of compute template consolidation data + * @return set of port ids, per port type + */ + static Map> collectAllPortsFromEachTypesFromComputes( + Collection computeTemplateConsolidationDataCollection) { + Map> portTypeToIds = new HashMap<>(); + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDataCollection) { + Map> ports = compute.getPorts(); + if (!MapUtils.isEmpty(ports)) { + addPortsToMap(portTypeToIds, ports); + } + } + return portTypeToIds; + } + + static ListMultimap collectAllSubInterfacesOfEachTypesFromPorts( + Collection portTemplateConsolidationDataCollection) { + ListMultimap subInterfaceDataByType = ArrayListMultimap.create(); + for (PortTemplateConsolidationData port : portTemplateConsolidationDataCollection) { + port.copyMappedInto(subInterfaceDataByType); + } + return subInterfaceDataByType; + } + + private static void addPortsToMap(Map> portTypeToIds, Map> ports) { + for (Map.Entry> portTypeToIdEntry : ports.entrySet()) { + portTypeToIds.putIfAbsent(portTypeToIdEntry.getKey(), new ArrayList<>()); + portTypeToIds.get(portTypeToIdEntry.getKey()).addAll(portTypeToIdEntry.getValue()); + } + } + + static String getComputeTypeSuffix(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + if (Objects.nonNull(computeNodeTemplate)) { + return getComputeTypeSuffix(computeNodeTemplate.getType()); + } + return null; } - return portTypeToIds; - } + public static String getNewComputeNodeTemplateId(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { + return getComputeTypeSuffix(serviceTemplate, computeNodeTemplateId); + } - static ListMultimap - collectAllSubInterfacesOfEachTypesFromPorts(Collection - portTemplateConsolidationDataCollection) { - ListMultimap subInterfaceDataByType = ArrayListMultimap.create(); - for (PortTemplateConsolidationData port : portTemplateConsolidationDataCollection) { - port.copyMappedInto(subInterfaceDataByType); + static String getComputeTypeSuffix(String computeType) { + return DataModelUtil.getNamespaceSuffix(computeType); } - return subInterfaceDataByType; - } - - private static void addPortsToMap(Map> portTypeToIds, - Map> ports) { - for (Map.Entry> portTypeToIdEntry : ports.entrySet()) { - portTypeToIds.putIfAbsent(portTypeToIdEntry.getKey(), new ArrayList<>()); - portTypeToIds.get(portTypeToIdEntry.getKey()).addAll(portTypeToIdEntry.getValue()); + + public static ComputeTemplateConsolidationData getConnectedComputeConsolidationData(List unifiedCompositionDataList, + String portNodeTemplateId) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + if (Objects.isNull(unifiedCompositionData.getComputeTemplateConsolidationData().getPorts())) { + continue; + } + Collection> portsCollection = unifiedCompositionData.getComputeTemplateConsolidationData().getPorts().values(); + for (List portIdList : portsCollection) { + if (portIdList.contains(portNodeTemplateId)) { + return unifiedCompositionData.getComputeTemplateConsolidationData(); + } + } + } + return null; } - } - static String getComputeTypeSuffix(ServiceTemplate serviceTemplate, - String computeNodeTemplateId) { - NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); - if (Objects.nonNull(computeNodeTemplate)) { - return getComputeTypeSuffix(computeNodeTemplate.getType()); + public static PortTemplateConsolidationData getPortTemplateConsolidationDataForPort(List unifiedCompositionDataList, + String portNodeTemplateId) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + if (CollectionUtils.isEmpty(unifiedCompositionData.getPortTemplateConsolidationDataList())) { + continue; + } + List portTemplateConsolidationDataList = unifiedCompositionData.getPortTemplateConsolidationDataList(); + for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { + if (portTemplateConsolidationData.getNodeTemplateId().equals(portNodeTemplateId)) { + return portTemplateConsolidationData; + } + } + } + return null; } - return null; - } - - public static String getNewComputeNodeTemplateId(ServiceTemplate serviceTemplate, String computeNodeTemplateId) { - return getComputeTypeSuffix(serviceTemplate, computeNodeTemplateId); - } - - static String getComputeTypeSuffix(String computeType) { - return DataModelUtil.getNamespaceSuffix(computeType); - } - - public static ComputeTemplateConsolidationData getConnectedComputeConsolidationData( - List unifiedCompositionDataList, - String portNodeTemplateId) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - if (Objects.isNull(unifiedCompositionData.getComputeTemplateConsolidationData().getPorts())) { - continue; - } - Collection> portsCollection = - unifiedCompositionData.getComputeTemplateConsolidationData().getPorts().values(); - for (List portIdList : portsCollection) { - if (portIdList.contains(portNodeTemplateId)) { - return unifiedCompositionData.getComputeTemplateConsolidationData(); + + //The ID should be _ or _ + public static String getNewPortNodeTemplateId(String portNodeTemplateId, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + StringBuilder newPortNodeTemplateId = new StringBuilder(); + String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId, DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); + newPortNodeTemplateId.append(DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); + if (computeTemplateConsolidationData.getPorts().get(portType) != null + && computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + //single port + newPortNodeTemplateId.append("_").append(portNodeTemplateId); + } else { + //consolidation port + newPortNodeTemplateId.append("_").append(portType); } - } + return newPortNodeTemplateId.toString(); } - return null; - } - - public static PortTemplateConsolidationData getPortTemplateConsolidationDataForPort(List - unifiedCompositionDataList, - String portNodeTemplateId) { - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - if (CollectionUtils.isEmpty(unifiedCompositionData.getPortTemplateConsolidationDataList())) { - continue; - } - List portTemplateConsolidationDataList = - unifiedCompositionData.getPortTemplateConsolidationDataList(); - for (PortTemplateConsolidationData portTemplateConsolidationData : portTemplateConsolidationDataList) { - if (portTemplateConsolidationData.getNodeTemplateId().equals(portNodeTemplateId)) { - return portTemplateConsolidationData; + + public static String getNewSubInterfaceNodeTemplateId(ServiceTemplate serviceTemplate, String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData, + TranslationContext context) { + //The ID should be __ + + // or __ + StringBuilder newSubInterfaceNodeTemplateId = new StringBuilder(); + newSubInterfaceNodeTemplateId.append( + getNewPortNodeTemplateId(subInterfaceTemplateConsolidationData.getParentPortNodeTemplateId(), connectedComputeNodeType, + computeTemplateConsolidationData)); + Optional portTemplateConsolidationData = subInterfaceTemplateConsolidationData + .getParentPortTemplateConsolidationData(serviceTemplate, context); + NodeTemplate subInterfaceNodeTemplate = DataModelUtil + .getNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData.getNodeTemplateId()); + if (portTemplateConsolidationData.isPresent()) { + String subInterfaceSuffix = getSubInterfaceSuffix(portTemplateConsolidationData.get(), subInterfaceNodeTemplate, + subInterfaceTemplateConsolidationData); + newSubInterfaceNodeTemplateId.append("_").append(subInterfaceSuffix); + return newSubInterfaceNodeTemplateId.toString(); } - } + return subInterfaceTemplateConsolidationData.getNodeTemplateId(); } - return null; - } - - //The ID should be _ or _ - public static String getNewPortNodeTemplateId( - String portNodeTemplateId, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData) { - - StringBuilder newPortNodeTemplateId = new StringBuilder(); - String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId, - DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); - newPortNodeTemplateId.append(DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); - if (computeTemplateConsolidationData.getPorts().get(portType) != null - && computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { - //single port - newPortNodeTemplateId.append("_").append(portNodeTemplateId); - } else { - //consolidation port - newPortNodeTemplateId.append("_").append(portType); + + static String getSubInterfaceTypeSuffix(String nodeType) { + return DataModelUtil.getNamespaceSuffix(nodeType); } - return newPortNodeTemplateId.toString(); - } - - public static String getNewSubInterfaceNodeTemplateId(ServiceTemplate serviceTemplate, - String connectedComputeNodeType, - ComputeTemplateConsolidationData computeTemplateConsolidationData, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData, - TranslationContext context) { - //The ID should be __ - // or __ - StringBuilder newSubInterfaceNodeTemplateId = new StringBuilder(); - newSubInterfaceNodeTemplateId.append(getNewPortNodeTemplateId(subInterfaceTemplateConsolidationData - .getParentPortNodeTemplateId(), connectedComputeNodeType, computeTemplateConsolidationData)); - Optional portTemplateConsolidationData = - subInterfaceTemplateConsolidationData.getParentPortTemplateConsolidationData(serviceTemplate, context); - NodeTemplate subInterfaceNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, subInterfaceTemplateConsolidationData.getNodeTemplateId()); - if (portTemplateConsolidationData.isPresent()) { - String subInterfaceSuffix = getSubInterfaceSuffix(portTemplateConsolidationData.get(), - subInterfaceNodeTemplate, subInterfaceTemplateConsolidationData); - newSubInterfaceNodeTemplateId.append("_").append(subInterfaceSuffix); - return newSubInterfaceNodeTemplateId.toString(); + + public static List getSubInterfaceTemplateConsolidationDataList( + UnifiedCompositionData unifiedCompositionData) { + return unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList() == null ? Collections.emptyList() + : unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList(); } - return subInterfaceTemplateConsolidationData.getNodeTemplateId(); - } - - static String getSubInterfaceTypeSuffix(String nodeType) { - return DataModelUtil.getNamespaceSuffix(nodeType); - } - - public static List getSubInterfaceTemplateConsolidationDataList( - UnifiedCompositionData unifiedCompositionData) { - return unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList() == null ? Collections.emptyList() : - unifiedCompositionData.getSubInterfaceTemplateConsolidationDataList(); - } - - private static String getSubInterfaceSuffix(PortTemplateConsolidationData portTemplateConsolidationData, - NodeTemplate subInterfaceNodeTemplate, - SubInterfaceTemplateConsolidationData - subInterfaceTemplateConsolidationData) { - if (portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(subInterfaceNodeTemplate.getType())) { - //If there are more than one subinterfaces with same type use node template id - return subInterfaceTemplateConsolidationData.getNodeTemplateId(); + + private static String getSubInterfaceSuffix(PortTemplateConsolidationData portTemplateConsolidationData, NodeTemplate subInterfaceNodeTemplate, + SubInterfaceTemplateConsolidationData subInterfaceTemplateConsolidationData) { + if (portTemplateConsolidationData.isSubInterfaceNodeTemplateIdParameter(subInterfaceNodeTemplate.getType())) { + //If there are more than one subinterfaces with same type use node template id + return subInterfaceTemplateConsolidationData.getNodeTemplateId(); + } + //Add sub interface type since we have only one subinterface per type + return getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); } - //Add sub interface type since we have only one subinterface per type - return getSubInterfaceTypeSuffix(subInterfaceNodeTemplate.getType()); - } - public static Map> collectAllPortsOfEachTypeFromComputes( - List unifiedCompositionDataList) { + public static Map> collectAllPortsOfEachTypeFromComputes(List unifiedCompositionDataList) { Map> portIdsPerPortType = new HashMap<>(); - unifiedCompositionDataList - .forEach(unifiedCompositionData -> - unifiedCompositionData.getComputeTemplateConsolidationData() - .collectAllPortsOfEachTypeFromCompute(portIdsPerPortType)); - + unifiedCompositionDataList.forEach(unifiedCompositionData -> unifiedCompositionData.getComputeTemplateConsolidationData() + .collectAllPortsOfEachTypeFromCompute(portIdsPerPortType)); return portIdsPerPortType; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java index 9fa086eb17..3bc540d9ae 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/DuplicateResourceIdsInDifferentFilesErrorBuilder.java @@ -24,12 +24,10 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public final class DuplicateResourceIdsInDifferentFilesErrorBuilder extends BaseErrorBuilder { - private static final String DUPLICATE_RESOURCE_ID_MSG = "Resource with id %s occurs more than once in " + - "different addOn files"; + private static final String DUPLICATE_RESOURCE_ID_MSG = "Resource with id %s occurs more than once in " + "different addOn files"; - public DuplicateResourceIdsInDifferentFilesErrorBuilder(String resourceId) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES) - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(DUPLICATE_RESOURCE_ID_MSG, resourceId)); - } + public DuplicateResourceIdsInDifferentFilesErrorBuilder(String resourceId) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES).withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(DUPLICATE_RESOURCE_ID_MSG, resourceId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java index fddf2a82d8..81f5860801 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class IncorrectResourceReferenceErrorBuilder extends BaseErrorBuilder { - private static final String INCORRECT_RESOURCE_REFERENCE_MSG = - "resource id '%s' with type '%s' has reference to resource '%s' with" - + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; + private static final String INCORRECT_RESOURCE_REFERENCE_MSG = "resource id '%s' with type '%s' has reference to resource '%s' with" + + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; - /** - * Instantiates a new Incorrect resource reference error builder. - * - * @param sourceResourceId the source resource id - * @param sourceResourceType the source resource type - * @param targetResourceId the target resource id - * @param targetResourceType the target resource type - * @param property the property - * @param validType the valid type - */ - public IncorrectResourceReferenceErrorBuilder(String sourceResourceId, String sourceResourceType, - String targetResourceId, String targetResourceType, - String property, String validType) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.INCORRECT_RESOURCE_REFERENCE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(INCORRECT_RESOURCE_REFERENCE_MSG, sourceResourceId, sourceResourceType, - targetResourceId, targetResourceType, property, validType)); - } + /** + * Instantiates a new Incorrect resource reference error builder. + * + * @param sourceResourceId the source resource id + * @param sourceResourceType the source resource type + * @param targetResourceId the target resource id + * @param targetResourceType the target resource type + * @param property the property + * @param validType the valid type + */ + public IncorrectResourceReferenceErrorBuilder(String sourceResourceId, String sourceResourceType, String targetResourceId, + String targetResourceType, String property, String validType) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.INCORRECT_RESOURCE_REFERENCE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String + .format(INCORRECT_RESOURCE_REFERENCE_MSG, sourceResourceId, sourceResourceType, targetResourceId, targetResourceType, property, + validType)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java index a16c341545..ee533fa6cb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/InvalidPropertyValueErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class InvalidPropertyValueErrorBuilder extends BaseErrorBuilder { - private static final String INVALID_FILED_VALUE_MSG = - "'%s' property has invalid value. Actual value is '%s' while '%s' value expected."; - - /** - * Instantiates a new Invalid property value error builder. - * - * @param propertyName the property name - * @param actualValue the actual value - * @param expectedValue the expected value - */ - public InvalidPropertyValueErrorBuilder(String propertyName, String actualValue, - String expectedValue) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.INVALID_PROPERTY_VALUE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(INVALID_FILED_VALUE_MSG, propertyName, actualValue, expectedValue)); - } + private static final String INVALID_FILED_VALUE_MSG = "'%s' property has invalid value. Actual value is '%s' while '%s' value expected."; + /** + * Instantiates a new Invalid property value error builder. + * + * @param propertyName the property name + * @param actualValue the actual value + * @param expectedValue the expected value + */ + public InvalidPropertyValueErrorBuilder(String propertyName, String actualValue, String expectedValue) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.INVALID_PROPERTY_VALUE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(INVALID_FILED_VALUE_MSG, propertyName, actualValue, expectedValue)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java index 6e06fef930..2232575cca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/MissingMandatoryPropertyErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class MissingMandatoryPropertyErrorBuilder extends BaseErrorBuilder { - private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = - "Mandatory property '%s' is missing"; + private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = "Mandatory property '%s' is missing"; - /** - * Instantiates a new Missing mandatory property error builder. - * - * @param propertyName the property name - */ - public MissingMandatoryPropertyErrorBuilder(String propertyName) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.MISSING_MANDATORY_PROPERTY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(MANDATORY_PROPERTY_IS_MISSING_MSG, propertyName)); - } + /** + * Instantiates a new Missing mandatory property error builder. + * + * @param propertyName the property name + */ + public MissingMandatoryPropertyErrorBuilder(String propertyName) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.MISSING_MANDATORY_PROPERTY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(MANDATORY_PROPERTY_IS_MISSING_MSG, propertyName)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java index ae903946e4..de944ce856 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class NotInSyncNumberOfInterfacesErrorBuilder extends BaseErrorBuilder { - private static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG = - "More than one ServiceInstance pointing to the same " - + "ServiceTemplate '%s', with different number of interfaces."; + private static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG = + "More than one ServiceInstance pointing to the same " + "ServiceTemplate '%s', with different number of interfaces."; - /** - * Instantiates a new Not in sync number of interfaces error builder. - * - * @param serviceTemplateResourceId the service template resource id - */ - public NotInSyncNumberOfInterfacesErrorBuilder(String serviceTemplateResourceId) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.NOT_IN_SYNC_NUMBER_OF_INTERFACES); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG, serviceTemplateResourceId)); - } + /** + * Instantiates a new Not in sync number of interfaces error builder. + * + * @param serviceTemplateResourceId the service template resource id + */ + public NotInSyncNumberOfInterfacesErrorBuilder(String serviceTemplateResourceId) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.NOT_IN_SYNC_NUMBER_OF_INTERFACES); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG, serviceTemplateResourceId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java index dc41e5d207..73b511b227 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; - public class ReferenceToUnsupportedResourceErrorBuilder extends BaseErrorBuilder { - private static final String REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG = - "Resource id '%s' with type '%s' has reference " - + "to unsupported resource '%s' with type '%s' in property '%s'"; + private static final String REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG = + "Resource id '%s' with type '%s' has reference " + "to unsupported resource '%s' with type '%s' in property '%s'"; - /** - * Instantiates a new Reference to unsupported resource error builder. - * - * @param sourceResourceId the source resource id - * @param sourceResourceType the source resource type - * @param targetResourceId the target resource id - * @param targetResourceType the target resource type - * @param property the property - */ - public ReferenceToUnsupportedResourceErrorBuilder(String sourceResourceId, - String sourceResourceType, - String targetResourceId, - String targetResourceType, String property) { - getErrorCodeBuilder().withId(TranslatorErrorCodes.REFERENCE_TO_UNSUPPORTED_RESOURCE); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG, sourceResourceId, sourceResourceType, - targetResourceId, targetResourceType, property)); - } + /** + * Instantiates a new Reference to unsupported resource error builder. + * + * @param sourceResourceId the source resource id + * @param sourceResourceType the source resource type + * @param targetResourceId the target resource id + * @param targetResourceType the target resource type + * @param property the property + */ + public ReferenceToUnsupportedResourceErrorBuilder(String sourceResourceId, String sourceResourceType, String targetResourceId, + String targetResourceType, String property) { + getErrorCodeBuilder().withId(TranslatorErrorCodes.REFERENCE_TO_UNSUPPORTED_RESOURCE); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String + .format(REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG, sourceResourceId, sourceResourceType, targetResourceId, targetResourceType, property)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java index 7fac501e76..506a0d92f4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ResourceNotFoundInHeatFileErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,28 +24,23 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class ResourceNotFoundInHeatFileErrorBuilder { - private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_ID = - "RESOURCE_NOT_FOUND_IN_FILE_ERR_ID"; - private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG = - "resource with id = %s was not found in heat file = %s."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Resource not found in heat file error builder. - * - * @param resourceId the resource id - * @param heatfileName the heatfile name - */ - public ResourceNotFoundInHeatFileErrorBuilder(String resourceId, String heatfileName) { - builder.withId(RESOURCE_NOT_FOUND_IN_FILE_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder - .withMessage(String.format(RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG, resourceId, heatfileName)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_ID = "RESOURCE_NOT_FOUND_IN_FILE_ERR_ID"; + private static final String RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG = "resource with id = %s was not found in heat file = %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Resource not found in heat file error builder. + * + * @param resourceId the resource id + * @param heatfileName the heatfile name + */ + public ResourceNotFoundInHeatFileErrorBuilder(String resourceId, String heatfileName) { + builder.withId(RESOURCE_NOT_FOUND_IN_FILE_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(RESOURCE_NOT_FOUND_IN_FILE_ERR_MSG, resourceId, heatfileName)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java index 5afb1ae3c2..0a03847da2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.errors; - public class TranslatorErrorCodes { - public static final String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; - public static final String HEAT_TO_TOSCA_MAPPING_COLLISION = "HEAT_TO_TOSCA_MAPPING_COLLISION"; - public static final String INCORRECT_RESOURCE_REFERENCE = "INCORRECT_RESOURCE_REFERENCE"; - public static final String REFERENCE_TO_UNSUPPORTED_RESOURCE = - "REFERENCE_TO_UNSUPPORTED_RESOURCE"; - public static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES = "NOT_IN_SYNC_NUMBER_OF_INTERFACES"; - public static final String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; - public static final String DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES = "DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES"; + + public static final String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; + public static final String HEAT_TO_TOSCA_MAPPING_COLLISION = "HEAT_TO_TOSCA_MAPPING_COLLISION"; + public static final String INCORRECT_RESOURCE_REFERENCE = "INCORRECT_RESOURCE_REFERENCE"; + public static final String REFERENCE_TO_UNSUPPORTED_RESOURCE = "REFERENCE_TO_UNSUPPORTED_RESOURCE"; + public static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES = "NOT_IN_SYNC_NUMBER_OF_INTERFACES"; + public static final String INVALID_PROPERTY_VALUE = "INVALID_PROPERTY_VALUE"; + public static final String DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES = "DUPLICATE_RESOURCE_ID_IN_DIFFERENT_FILES"; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java index 5a3dc7e042..0031d209e0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java @@ -13,66 +13,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.globaltypes; -import org.onap.sdc.tosca.datatypes.model.Import; -import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - +import org.onap.sdc.tosca.datatypes.model.Import; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; public class GlobalTypesGenerator { - private GlobalTypesGenerator() { - } + private GlobalTypesGenerator() { + } - /** - * Gets global types service template. - * - * @return the global types service template - */ - public static Map getGlobalTypesServiceTemplate(OnboardingTypesEnum - onboardingType) { - return GlobalTypesServiceTemplates.getGlobalTypesServiceTemplates(onboardingType); - } + /** + * Gets global types service template. + * + * @return the global types service template + */ + public static Map getGlobalTypesServiceTemplate(OnboardingTypesEnum onboardingType) { + return GlobalTypesServiceTemplates.getGlobalTypesServiceTemplates(onboardingType); + } - /** - * Gets global types import list. - * - * @return the global types import list - */ - public static List> getGlobalTypesImportList() { - List> globalImports = new ArrayList<>(); - Map globalImportMap = new HashMap<>(); - Map globalTypesServiceTemplate = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); - globalImportMap.put("openecomp_heat_index", - HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get - ("openecomp-heat/_index.yml"))); - globalImports.add(globalImportMap); - return globalImports; - } + /** + * Gets global types import list. + * + * @return the global types import list + */ + public static List> getGlobalTypesImportList() { + List> globalImports = new ArrayList<>(); + Map globalImportMap = new HashMap<>(); + Map globalTypesServiceTemplate = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP); + globalImportMap + .put("openecomp_heat_index", HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get("openecomp-heat/_index.yml"))); + globalImports.add(globalImportMap); + return globalImports; + } - /** - * Gets global types import list for Manual Vsp onboarding. - * - * @return the global types import list - */ - public static List> getManualVspGlobalTypesImportList() { - List> globalImports = new ArrayList<>(); - Map globalImportMap = new HashMap<>(); - Map globalTypesServiceTemplate = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL); - globalImportMap.put("openecomp_index", - HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get - ("openecomp/_index.yml"))); - globalImports.add(globalImportMap); - return globalImports; - } + /** + * Gets global types import list for Manual Vsp onboarding. + * + * @return the global types import list + */ + public static List> getManualVspGlobalTypesImportList() { + List> globalImports = new ArrayList<>(); + Map globalImportMap = new HashMap<>(); + Map globalTypesServiceTemplate = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.MANUAL); + globalImportMap.put("openecomp_index", HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get("openecomp/_index.yml"))); + globalImports.add(globalImportMap); + return globalImports; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java index dc63f970cd..2c6516eca9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.globaltypes; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -26,18 +28,11 @@ import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.utils.ResourceWalker; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - public class GlobalTypesServiceTemplates { private static final String ONAP_FILEPATH_REGEX = ".*" + Constants.GLOBAL_TYPES + "(/onap/|\\\\onap\\\\).*"; private static final Map> onboardingGlobalTypesServiceTemplates; - private GlobalTypesServiceTemplates() { - } - static { Map globalTypes; try { @@ -45,35 +40,31 @@ public class GlobalTypesServiceTemplates { } catch (CoreException coreException) { throw coreException; } catch (Exception exception) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES) - .withId(Constants.GLOBAL_TYPES_READ_ERROR) - .withCategory(ErrorCategory.APPLICATION).build(), exception); + throw new CoreException( + (new ErrorCode.ErrorCodeBuilder()).withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES).withId(Constants.GLOBAL_TYPES_READ_ERROR) + .withCategory(ErrorCategory.APPLICATION).build(), exception); } onboardingGlobalTypesServiceTemplates = init(globalTypes); } + private GlobalTypesServiceTemplates() { + } + public static Map getGlobalTypesServiceTemplates(OnboardingTypesEnum onboardingType) { if (onboardingType == null) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES) - .withId(Constants.INVALID_ONBOARDING_TYPE) - .withCategory(ErrorCategory.APPLICATION).build()); + throw new CoreException( + (new ErrorCode.ErrorCodeBuilder()).withMessage(Constants.FAILED_TO_GENERATE_GLOBAL_TYPES).withId(Constants.INVALID_ONBOARDING_TYPE) + .withCategory(ErrorCategory.APPLICATION).build()); } return onboardingGlobalTypesServiceTemplates.get(onboardingType); } private static Map> init(Map globalTypes) { - Map> onboardingGlobalTypesServiceTemplates = - new EnumMap<>(OnboardingTypesEnum.class); - Map zipOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.ZIP); - Map csarOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.CSAR); - Map manualOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.MANUAL); - Map defaultOnboardingGlobalTypes = - getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.NONE); + Map> onboardingGlobalTypesServiceTemplates = new EnumMap<>(OnboardingTypesEnum.class); + Map zipOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.ZIP); + Map csarOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.CSAR); + Map manualOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.MANUAL); + Map defaultOnboardingGlobalTypes = getOnboardingGlobalTypes(globalTypes, OnboardingTypesEnum.NONE); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.ZIP, zipOnboardingGlobalTypes); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.CSAR, csarOnboardingGlobalTypes); onboardingGlobalTypesServiceTemplates.put(OnboardingTypesEnum.MANUAL, manualOnboardingGlobalTypes); @@ -81,8 +72,7 @@ public class GlobalTypesServiceTemplates { return onboardingGlobalTypesServiceTemplates; } - private static Map getOnboardingGlobalTypes(Map globalTypes, - OnboardingTypesEnum onboardingType) { + private static Map getOnboardingGlobalTypes(Map globalTypes, OnboardingTypesEnum onboardingType) { Map globalTypesServiceTemplates = new HashMap<>(); ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); for (Map.Entry globalTypeContent : globalTypes.entrySet()) { @@ -91,13 +81,12 @@ public class GlobalTypesServiceTemplates { continue; } ToscaUtil.addServiceTemplateToMapWithKeyFileName(globalTypesServiceTemplates, - toscaExtensionYamlUtil.yamlToObject(globalTypeContent.getValue(), ServiceTemplate.class)); + toscaExtensionYamlUtil.yamlToObject(globalTypeContent.getValue(), ServiceTemplate.class)); } return globalTypesServiceTemplates; } - private static boolean isTypeValidCandidateForCsarPacking(String globalTypeResourceKey, - OnboardingTypesEnum onboardingType) { + private static boolean isTypeValidCandidateForCsarPacking(String globalTypeResourceKey, OnboardingTypesEnum onboardingType) { if (globalTypeResourceKey.contains(Constants.OPENECOMP_INVENTORY)) { // this global types folders should not be processed to the CSAR return false; @@ -105,5 +94,4 @@ public class GlobalTypesServiceTemplates { //Global types specific to csar onboarding should not be packed for other onboarding types return !globalTypeResourceKey.matches(ONAP_FILEPATH_REGEX) || onboardingType == OnboardingTypesEnum.CSAR; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java index cabb92c254..c36d8c66fa 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.helper; import java.util.ArrayList; @@ -26,7 +25,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -37,108 +35,89 @@ import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; public class ContrailTranslationHelper { - /** - * Gets compute node type id. - * - * @param contrailServiceTemplateResource contrail service teamplte resource - * @param contrailServiceTemplateResourceId contrailservice template resource id - * @param contrailServiceTemplateTranslatedId contrail service tempalte resource translated id - * @return the compute node type id - */ - public String getComputeNodeTypeId(Resource contrailServiceTemplateResource, - String contrailServiceTemplateResourceId, - String contrailServiceTemplateTranslatedId, - TranslationContext context) { - NameExtractor nodeTypeNameExtractor = - context.getNameExtractorImpl(ConfigConstants.CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY); - return nodeTypeNameExtractor - .extractNodeTypeName(contrailServiceTemplateResource, contrailServiceTemplateResourceId, - contrailServiceTemplateTranslatedId); - } - - /** - * Get property Regx matcher list. - * - * @return Regex exprission per contrail service template resource property, while contail compute - * type name is consider when setting the name value - */ - public List getPropertyRegexMatchersForComputeNodeType() { - List propertyRegexMatchers = new ArrayList<>(); - propertyRegexMatchers - .add(new PropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), - "_image_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), - "_flavor_name")); - return propertyRegexMatchers; - } - public String getSubstitutionContrailServiceTemplateMetadata(String heatFileName, - String serviceInstanceTranslatedId) { - return FileUtils.getFileWithoutExtention(heatFileName) + "_" + serviceInstanceTranslatedId; - } - - /** - * Translate fn split function optional. - * - * @param propertyValue the property value - * @param listSize the list size - * @param includeBooleanValue the include boolean value - * @return the optional - */ - public Optional>> translateFnSplitFunction(Object propertyValue, - int listSize, - boolean - includeBooleanValue) { - List> tokenPropertyValueList = new ArrayList<>(); - - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map propMap = (Map) propertyValue; - Map.Entry entry = propMap.entrySet().iterator().next(); - Object entity = entry.getValue(); - String key = entry.getKey(); - String tokenChar; + /** + * Gets compute node type id. + * + * @param contrailServiceTemplateResource contrail service teamplte resource + * @param contrailServiceTemplateResourceId contrailservice template resource id + * @param contrailServiceTemplateTranslatedId contrail service tempalte resource translated id + * @return the compute node type id + */ + public String getComputeNodeTypeId(Resource contrailServiceTemplateResource, String contrailServiceTemplateResourceId, + String contrailServiceTemplateTranslatedId, TranslationContext context) { + NameExtractor nodeTypeNameExtractor = context.getNameExtractorImpl(ConfigConstants.CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY); + return nodeTypeNameExtractor + .extractNodeTypeName(contrailServiceTemplateResource, contrailServiceTemplateResourceId, contrailServiceTemplateTranslatedId); + } - if (key.equals("Fn::Split") && entity instanceof List) { - tokenChar = (String) ((List) entity).get(0); - Object refParameter = ((List) entity).get(1); + /** + * Get property Regx matcher list. + * + * @return Regex exprission per contrail service template resource property, while contail compute type name is consider when setting the name + * value + */ + public List getPropertyRegexMatchersForComputeNodeType() { + List propertyRegexMatchers = new ArrayList<>(); + propertyRegexMatchers.add(new PropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), "_image_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), "_flavor_name")); + return propertyRegexMatchers; + } - for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { - Map tokenPropertyValue = new HashMap<>(); - tokenPropertyValue.put("token", new ArrayList<>()); + public String getSubstitutionContrailServiceTemplateMetadata(String heatFileName, String serviceInstanceTranslatedId) { + return FileUtils.getFileWithoutExtention(heatFileName) + "_" + serviceInstanceTranslatedId; + } - if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { - Map stringWithToken = new HashMap<>(); - ((Map) stringWithToken) - .put(ToscaFunctions.GET_INPUT.getFunctionName(), ((Map) refParameter).get("Ref")); - tokenPropertyValue.get("token").add(stringWithToken); - } else if (refParameter instanceof String) { - if (includeBooleanValue) { - StringBuilder booleanBuilder = new StringBuilder(); - String[] booleanValueList = ((String) refParameter).split(tokenChar); - for (int i = 0; i < booleanValueList.length; i++) { - if (i == 0) { - booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); - } else { - booleanBuilder.append(tokenChar); - booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + /** + * Translate fn split function optional. + * + * @param propertyValue the property value + * @param listSize the list size + * @param includeBooleanValue the include boolean value + * @return the optional + */ + public Optional>> translateFnSplitFunction(Object propertyValue, int listSize, boolean includeBooleanValue) { + List> tokenPropertyValueList = new ArrayList<>(); + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map propMap = (Map) propertyValue; + Map.Entry entry = propMap.entrySet().iterator().next(); + Object entity = entry.getValue(); + String key = entry.getKey(); + String tokenChar; + if (key.equals("Fn::Split") && entity instanceof List) { + tokenChar = (String) ((List) entity).get(0); + Object refParameter = ((List) entity).get(1); + for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { + Map tokenPropertyValue = new HashMap<>(); + tokenPropertyValue.put("token", new ArrayList<>()); + if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { + Map stringWithToken = new HashMap<>(); + ((Map) stringWithToken).put(ToscaFunctions.GET_INPUT.getFunctionName(), ((Map) refParameter).get("Ref")); + tokenPropertyValue.get("token").add(stringWithToken); + } else if (refParameter instanceof String) { + if (includeBooleanValue) { + StringBuilder booleanBuilder = new StringBuilder(); + String[] booleanValueList = ((String) refParameter).split(tokenChar); + for (int i = 0; i < booleanValueList.length; i++) { + if (i == 0) { + booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + } else { + booleanBuilder.append(tokenChar); + booleanBuilder.append(HeatBoolean.eval(booleanValueList[i])); + } + } + tokenPropertyValue.get("token").add(booleanBuilder.toString()); + } else { + tokenPropertyValue.get("token").add(refParameter); + } + } + tokenPropertyValue.get("token").add(tokenChar); + tokenPropertyValue.get("token").add(substringIndex); + tokenPropertyValueList.add(tokenPropertyValue); } - } - tokenPropertyValue.get("token").add(booleanBuilder.toString()); - } else { - tokenPropertyValue.get("token").add(refParameter); + return Optional.of(tokenPropertyValueList); } - } - tokenPropertyValue.get("token").add(tokenChar); - tokenPropertyValue.get("token").add(substringIndex); - tokenPropertyValueList.add(tokenPropertyValue); } - - return Optional.of(tokenPropertyValueList); - - } + return Optional.empty(); } - - return Optional.empty(); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java index 9a0865d6ed..205ef243c8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java @@ -13,8 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - - package org.openecomp.sdc.translator.services.heattotosca.helper; import java.util.ArrayList; @@ -25,7 +23,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -48,151 +45,109 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; public class ContrailV2VirtualMachineInterfaceHelper { - static Logger logger = - (Logger) LoggerFactory.getLogger(ContrailV2VirtualMachineInterfaceHelper.class); - /** - * Connect Virtual Machine Interface node template to network node template in TOSCA. - * - * @param resourceTranslationImpl resource translation implemetation - * @param translateTo translated ro object - * @param vmiNodeTemplate Virtual Machine Interface node template - */ - public void connectVmiToNetwork(ResourceTranslationBase resourceTranslationImpl, - TranslateTo translateTo, NodeTemplate vmiNodeTemplate) { - Object virtualNetworkRefs = - translateTo.getResource().getProperties() - .get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).size() == 0) { - return; - } - List acceptableResourceTypes = Arrays - .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - if (((List) virtualNetworkRefs).size() > 1) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include '" - + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME - + "' property with more than one network values, only " - + "the first network will be connected, " - + "all rest will be ignored in TOSCA translation."); - } - Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); - - Optional networkResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); - if (networkResourceId.isPresent()) { // get_resource - Resource networkResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getHeatFileName()); - if (acceptableResourceTypes.contains(networkResource.getType())) { - Optional resourceTranslatedId = - resourceTranslationImpl.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getContext()); - - if (resourceTranslatedId.isPresent()) { - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - vmiNodeTemplate, resourceTranslatedId.get()); - if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE - .equals(vmiNodeTemplate.getType())) { - ConsolidationDataUtil - .updateNodesConnectedOut(translateTo, resourceTranslatedId.get(), - ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); - } + static Logger logger = (Logger) LoggerFactory.getLogger(ContrailV2VirtualMachineInterfaceHelper.class); + + /** + * Connect Virtual Machine Interface node template to network node template in TOSCA. + * + * @param resourceTranslationImpl resource translation implemetation + * @param translateTo translated ro object + * @param vmiNodeTemplate Virtual Machine Interface node template + */ + public void connectVmiToNetwork(ResourceTranslationBase resourceTranslationImpl, TranslateTo translateTo, NodeTemplate vmiNodeTemplate) { + Object virtualNetworkRefs = translateTo.getResource().getProperties().get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) || ((List) virtualNetworkRefs).size() == 0) { + return; } - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include '" + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME - + "' property which is connect to " - + "unsupported/incorrect resource with type '" - + networkResource.getType() - + "', therefore, this connection will be ignored in TOSCA translation."); - } - } else { - Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - virtualNetworkRef); - if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() - && attachedResourceId.get().getEntityId() instanceof String) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(attachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - vmiNodeTemplate, translatedSharedResourceId.getTranslatedId()); - - if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE - .equals(vmiNodeTemplate.getType())) { - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, translatedSharedResourceId - .getTranslatedId(), ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, - requirementAssignment); - } + List acceptableResourceTypes = Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + if (((List) virtualNetworkRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + translateTo.getResource().getType() + "' include '" + + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + "' property with more than one network values, only " + + "the first network will be connected, " + "all rest will be ignored in TOSCA translation."); + } + Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); + Optional networkResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); + if (networkResourceId.isPresent()) { // get_resource + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getHeatFileName()); + if (acceptableResourceTypes.contains(networkResource.getType())) { + Optional resourceTranslatedId = resourceTranslationImpl + .getResourceTranslatedId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getContext()); + if (resourceTranslatedId.isPresent()) { + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(vmiNodeTemplate, resourceTranslatedId.get()); + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, resourceTranslatedId.get(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + translateTo.getResource().getType() + "' include '" + + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + "' property which is connect to " + + "unsupported/incorrect resource with type '" + networkResource.getType() + + "', therefore, this connection will be ignored in TOSCA translation."); + } + } else { + Optional attachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkRef); + if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() && attachedResourceId.get().getEntityId() instanceof String) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(vmiNodeTemplate, translatedSharedResourceId.getTranslatedId()); + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + } } - } } - } - /** - * Check if the input heat resource is Vlan sub interface resource. - * - * @param resource heat resource to be checked - * @return true - if input resource is valn sub interface resource flase - otherwise. - */ - public boolean isVlanSubInterfaceResource(Resource resource) { - - if (resource.getType().equals(HeatResourcesTypes - .CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) - && getVlanTagPropertyValue(resource).isPresent()) { - return true; + /** + * Check if the input heat resource is Vlan sub interface resource. + * + * @param resource heat resource to be checked + * @return true - if input resource is valn sub interface resource flase - otherwise. + */ + public boolean isVlanSubInterfaceResource(Resource resource) { + if (resource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) + && getVlanTagPropertyValue(resource).isPresent()) { + return true; + } + return false; } - return false; - } - - public boolean isVlanSubInterfaceConnectedToPortIndirectly(TranslateTo translateTo) { - Resource resource = translateTo.getResource(); - TranslationContext context = translateTo.getContext(); - Set nestedHeatsFiles = context.getNestedHeatsFiles(); - Map properties = resource.getProperties(); - - if (MapUtils.isNotEmpty(properties) - && properties.containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME)) { - Map portReference = getPortReference(properties); - - return CollectionUtils.isNotEmpty(nestedHeatsFiles) - && nestedHeatsFiles.contains(translateTo.getHeatFileName()) - && portReference.containsKey(ResourceReferenceFunctions.GET_PARAM.getFunction()); + public boolean isVlanSubInterfaceConnectedToPortIndirectly(TranslateTo translateTo) { + Resource resource = translateTo.getResource(); + TranslationContext context = translateTo.getContext(); + Set nestedHeatsFiles = context.getNestedHeatsFiles(); + Map properties = resource.getProperties(); + if (MapUtils.isNotEmpty(properties) && properties.containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME)) { + Map portReference = getPortReference(properties); + return CollectionUtils.isNotEmpty(nestedHeatsFiles) && nestedHeatsFiles.contains(translateTo.getHeatFileName()) && portReference + .containsKey(ResourceReferenceFunctions.GET_PARAM.getFunction()); + } + return false; } - return false; - } - - private Map getPortReference(Map properties) { - Object portReferenceObj = properties.get(HeatConstants.VMI_REFS_PROPERTY_NAME); - List portReference = - portReferenceObj instanceof List ? (List) portReferenceObj : new ArrayList<>(); - return CollectionUtils.isEmpty(portReference) ? new HashMap<>() - : (Map) portReference.get(0); - } - - private Optional getVlanTagPropertyValue(Resource resource) { - Object vmiProperties = resource.getProperties() - .get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); - if (vmiProperties != null && vmiProperties instanceof Map) { - return Optional.ofNullable(((Map) vmiProperties) - .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + private Map getPortReference(Map properties) { + Object portReferenceObj = properties.get(HeatConstants.VMI_REFS_PROPERTY_NAME); + List portReference = portReferenceObj instanceof List ? (List) portReferenceObj : new ArrayList<>(); + return CollectionUtils.isEmpty(portReference) ? new HashMap<>() : (Map) portReference.get(0); } - return Optional.empty(); - } - + private Optional getVlanTagPropertyValue(Resource resource) { + Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); + if (vmiProperties != null && vmiProperties instanceof Map) { + return Optional.ofNullable(((Map) vmiProperties).get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + } + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java index ac6d317722..ec33420085 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java @@ -18,6 +18,7 @@ * ============LICENSE_END========================================================= */ package org.openecomp.sdc.translator.services.heattotosca.helper; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -73,7 +74,6 @@ public class ResourceTranslationNeutronPortHelper { properties.put(IP_REQUIREMENTS, ipRequirementsList); properties.put(MAC_REQUIREMENTS, createMacRequirement()); return properties; - } private Map createMacRequirement() { @@ -85,7 +85,7 @@ public class ResourceTranslationNeutronPortHelper { } private void setMacRequirements(Map properties) { - updateMacCountRequired(properties); + updateMacCountRequired(properties); } private void updateMacCountRequired(Map properties) { @@ -97,17 +97,16 @@ public class ResourceTranslationNeutronPortHelper { } private void setFloatingIpCount(Map properties) { - handleIpCountRequired(properties, ALLOWED_ADDRESS_PAIRS, FLOATING_IP_COUNT_REQUIRED ); + handleIpCountRequired(properties, ALLOWED_ADDRESS_PAIRS, FLOATING_IP_COUNT_REQUIRED); } private void setFixedIpCount(Map properties) { - handleIpCountRequired(properties, FIXED_IPS, IP_COUNT_REQUIRED ); + handleIpCountRequired(properties, FIXED_IPS, IP_COUNT_REQUIRED); } - private void addDefaultIpRequirement(Map properties) { List> ipRequirementsList = ((List>) properties.get(IP_REQUIREMENTS)); - if(ipRequirementsList.isEmpty()) { + if (ipRequirementsList.isEmpty()) { ipRequirementsList.add(createIPRequirement(DEFAULT_IP_VERSION)); } } @@ -124,52 +123,48 @@ public class ResourceTranslationNeutronPortHelper { return ipRequirements; } - private void handleIpCountRequired(Map properties, String ipType, String ipCountRequired ){ - + private void handleIpCountRequired(Map properties, String ipType, String ipCountRequired) { Object propertyValue = properties.get(ipType); - if(propertyValue == null){ + if (propertyValue == null) { return; } - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { handleMapProperty(ipType, ipCountRequired, properties, (Map.Entry) ((Map) propertyValue).entrySet().iterator().next()); + } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + handleListProperty(ipType, ipCountRequired, properties, (List) propertyValue); } - else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - handleListProperty(ipType, ipCountRequired, properties, (List) propertyValue); - } - } - private void handleListProperty(String ipType, String ipCountRequired, Map properties, List propertyValue) { + private void handleListProperty(String ipType, String ipCountRequired, Map properties, List propertyValue) { for (int i = 0; i < propertyValue.size(); i++) { - handleIpAddress(ipType, ipCountRequired, properties, propertyValue.get(i)); + handleIpAddress(ipType, ipCountRequired, properties, propertyValue.get(i)); } } private void handleMapProperty(String ipType, String ipCountRequired, Map properties, Map.Entry mapEntry) { - updateIpCountRequired(ipType, ipCountRequired, properties, mapEntry.getValue()); + updateIpCountRequired(ipType, ipCountRequired, properties, mapEntry.getValue()); } private void handleIpAddress(String ipType, String ipCountRequired, Map properties, Object ipMap) { - if(ipMap instanceof Map && !((Map) ipMap).isEmpty()) { + if (ipMap instanceof Map && !((Map) ipMap).isEmpty()) { Object ipAddressMap = ((Map) ipMap).get(IP_ADDRESS); if (ipAddressMap instanceof Map && !((Map) ipAddressMap).isEmpty()) { Object ipInput = ((Map) ipAddressMap).get(GET_INPUT); - updateIpCountRequired(ipType, ipCountRequired, properties, ipInput); + updateIpCountRequired(ipType, ipCountRequired, properties, ipInput); } } } private void updateIpCountRequired(String ipType, String ipCountRequired, Map properties, Object ipInput) { Object ipVersion = getVersion(ipInput, ipType); - updateIpCountRequiredForVersion(ipCountRequired, properties, ipVersion); + updateIpCountRequiredForVersion(ipCountRequired, properties, ipVersion); } - private void updateIpCountRequiredForVersion(String ipCountRequired, Map properties, Object ipVersion) { + private void updateIpCountRequiredForVersion(String ipCountRequired, Map properties, Object ipVersion) { if (ipVersion != null) { HashMap> ipRequirementsMap = getIPRequirements(properties); - Map ipRequirement = ipRequirementsMap.get(ipVersion); - if (ipRequirement == null){ + Map ipRequirement = ipRequirementsMap.get(ipVersion); + if (ipRequirement == null) { ipRequirement = addIPRequirement(properties, ipVersion); } updateIpCountRequired(ipCountRequired, ipRequirement); @@ -177,56 +172,51 @@ public class ResourceTranslationNeutronPortHelper { } private Map addIPRequirement(Map properties, Object ipVersion) { - List> ipRequirementsList = ((List>) properties.get(IP_REQUIREMENTS)); + List> ipRequirementsList = ((List>) properties.get(IP_REQUIREMENTS)); Map newIpRequirement = createIPRequirement(ipVersion); ipRequirementsList.add(newIpRequirement); return newIpRequirement; } private void updateIpCountRequired(String ipCountRequired, Map ipRequirement) { - Map isIPCountRequired = (Map)ipRequirement.get(ipCountRequired); + Map isIPCountRequired = (Map) ipRequirement.get(ipCountRequired); isIPCountRequired.put(IS_REQUIRED, Boolean.TRUE); } - private HashMap > getIPRequirements (Map properties) { + private HashMap> getIPRequirements(Map properties) { HashMap> ipRequirementsMap = new HashMap<>(); - List> ipRequirementsList = ((List>) properties.get(IP_REQUIREMENTS)); - ipRequirementsList.stream().forEach(e->ipRequirementsMap.put(e.get(IP_VERSION),e)); + List> ipRequirementsList = ((List>) properties.get(IP_REQUIREMENTS)); + ipRequirementsList.stream().forEach(e -> ipRequirementsMap.put(e.get(IP_VERSION), e)); return ipRequirementsMap; } private void setNetworkRoleTag(Map properties) { Object propertyValue = properties.get(NETWORK); if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map.Entry mapEntry = - (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); - if (mapEntry.getValue() instanceof String && getNetworkRole(mapEntry.getValue())!=null) { + Map.Entry mapEntry = (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); + if (mapEntry.getValue() instanceof String && getNetworkRole(mapEntry.getValue()) != null) { properties.put(NETWORK_ROLE_TAG, getNetworkRole(mapEntry.getValue())); } } } private Object getVersion(Object value, String type) { - Object version = null; - if(type.equals(FIXED_IPS)){ - version = getIpVersion(value); - } - else if(type.equals(ALLOWED_ADDRESS_PAIRS)){ - version = getFloatingIpVersion(value); + if (type.equals(FIXED_IPS)) { + version = getIpVersion(value); + } else if (type.equals(ALLOWED_ADDRESS_PAIRS)) { + version = getFloatingIpVersion(value); } return version; } private Object getFloatingIpVersion(Object value) { Object ipVersion = null; - // Allowed ONLY String parameter - if(value instanceof String) { + if (value instanceof String) { if (((String) value).endsWith(FLOATING_V6_IP)) { ipVersion = 6; - } - else if (((String) value).endsWith(FLOATING_IP)){ + } else if (((String) value).endsWith(FLOATING_IP)) { ipVersion = 4; } } @@ -234,18 +224,15 @@ public class ResourceTranslationNeutronPortHelper { } private Object getIpVersion(Object value) { - // Allowed List or String parameter Object ipVersion = null; - if (value instanceof List && !((List) value).isEmpty()){ + if (value instanceof List && !((List) value).isEmpty()) { value = ((List) value).get(0); } - - if(value instanceof String) { + if (value instanceof String) { if (((String) value).endsWith(V6_IPS) || ((String) value).matches(IPV6_REGEX)) { ipVersion = 6; - } - else { + } else { ipVersion = 4; } } @@ -254,15 +241,13 @@ public class ResourceTranslationNeutronPortHelper { private Object getNetworkRole(String value) { Object networkRole = null; - if(value.endsWith(NET_NAME)) { + if (value.endsWith(NET_NAME)) { networkRole = value.substring(0, value.length() - NET_NAME.length()); - } - else if(value.endsWith(NET_ID)) { + } else if (value.endsWith(NET_ID)) { networkRole = value.substring(0, value.length() - NET_ID.length()); - } - else if(value.endsWith(NET_FQDN)) { + } else if (value.endsWith(NET_FQDN)) { networkRole = value.substring(0, value.length() - NET_FQDN.length()); } return networkRole; } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java index 6328541927..0a3b1e8954 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.helper; import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; @@ -29,7 +28,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -45,126 +43,112 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; public class VolumeTranslationHelper { - private final Logger logger; - public VolumeTranslationHelper(Logger logger) { - this.logger = logger; - } - /** - * Gets file data containing volume. - * - * @param filesToSearch the files to search - * @param resourceId the resource id - * @param translateTo the translate to - * @param types the types - * @return the file data containing volume - */ - public Optional getFileDataContainingVolume(List filesToSearch, - String resourceId, - TranslateTo translateTo, - FileData.Type... types) { - if (CollectionUtils.isEmpty(filesToSearch)) { - return Optional.empty(); + private final Logger logger; + + public VolumeTranslationHelper(Logger logger) { + this.logger = logger; } - List fileDatas = Objects.isNull(types) ? filesToSearch : HeatToToscaUtil - .getFilteredListOfFileDataByTypes(filesToSearch, types); - Optional fileDataAndIDs = - getResourceFileDataAndIDsForVolumeConnection(resourceId, translateTo, fileDatas); - if (fileDataAndIDs.isPresent()) { - return fileDataAndIDs; + /** + * Gets file data containing volume. + * + * @param filesToSearch the files to search + * @param resourceId the resource id + * @param translateTo the translate to + * @param types the types + * @return the file data containing volume + */ + public Optional getFileDataContainingVolume(List filesToSearch, String resourceId, TranslateTo translateTo, + FileData.Type... types) { + if (CollectionUtils.isEmpty(filesToSearch)) { + return Optional.empty(); + } + List fileDatas = Objects.isNull(types) ? filesToSearch : HeatToToscaUtil.getFilteredListOfFileDataByTypes(filesToSearch, types); + Optional fileDataAndIDs = getResourceFileDataAndIDsForVolumeConnection(resourceId, translateTo, fileDatas); + if (fileDataAndIDs.isPresent()) { + return fileDataAndIDs; + } + return Optional.empty(); } - return Optional.empty(); - } - private Optional getResourceFileDataAndIDsForVolumeConnection( - String resourceId, TranslateTo translateTo, List fileDatas) { - for (FileData data : fileDatas) { - HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFiles().getFileContentAsStream(data.getFile()), - HeatOrchestrationTemplate.class); - Map outputs = heatOrchestrationTemplate.getOutputs(); - if (Objects.isNull(outputs)) { - continue; - } - Output output = outputs.get(resourceId); - if (Objects.nonNull(output)) { - Optional attachedOutputId = HeatToToscaUtil - .extractAttachedResourceId(data.getFile(), heatOrchestrationTemplate, - translateTo.getContext(), output.getValue()); - if (attachedOutputId.isPresent()) { - AttachedResourceId attachedResourceId = attachedOutputId.get(); - if (!isOutputIsGetResource(resourceId, data, attachedResourceId)) { - continue; - } - String translatedId = (String) attachedResourceId.getTranslatedId(); - if (isOutputOfTypeCinderVolume(translateTo, data, heatOrchestrationTemplate, - translatedId)) { - ResourceFileDataAndIDs fileDataAndIDs = - new ResourceFileDataAndIDs((String) attachedResourceId.getEntityId(), - translatedId, - data); - return Optional.of(fileDataAndIDs); - } else { - logger.warn( - "output: '" + resourceId + "' in file '" + data.getFile() + "' is not of type '" - + CINDER_VOLUME_RESOURCE_TYPE.getHeatResource() + "'"); - } + private Optional getResourceFileDataAndIDsForVolumeConnection(String resourceId, TranslateTo translateTo, + List fileDatas) { + for (FileData data : fileDatas) { + HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translateTo.getContext().getFiles().getFileContentAsStream(data.getFile()), HeatOrchestrationTemplate.class); + Map outputs = heatOrchestrationTemplate.getOutputs(); + if (Objects.isNull(outputs)) { + continue; + } + Output output = outputs.get(resourceId); + if (Objects.nonNull(output)) { + Optional attachedOutputId = HeatToToscaUtil + .extractAttachedResourceId(data.getFile(), heatOrchestrationTemplate, translateTo.getContext(), output.getValue()); + if (attachedOutputId.isPresent()) { + AttachedResourceId attachedResourceId = attachedOutputId.get(); + if (!isOutputIsGetResource(resourceId, data, attachedResourceId)) { + continue; + } + String translatedId = (String) attachedResourceId.getTranslatedId(); + if (isOutputOfTypeCinderVolume(translateTo, data, heatOrchestrationTemplate, translatedId)) { + ResourceFileDataAndIDs fileDataAndIDs = new ResourceFileDataAndIDs((String) attachedResourceId.getEntityId(), translatedId, + data); + return Optional.of(fileDataAndIDs); + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not of type '" + CINDER_VOLUME_RESOURCE_TYPE + .getHeatResource() + "'"); + } + } + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not found"); + } } - } else { - logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not found"); - } + return Optional.empty(); } - return Optional.empty(); - } - private boolean isOutputOfTypeCinderVolume(TranslateTo translateTo, FileData data, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedId) { - return getResourceByTranslatedResourceId(data.getFile(), heatOrchestrationTemplate, - translatedId, translateTo, CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()).isPresent(); - } + private boolean isOutputOfTypeCinderVolume(TranslateTo translateTo, FileData data, HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedId) { + return getResourceByTranslatedResourceId(data.getFile(), heatOrchestrationTemplate, translatedId, translateTo, + CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()).isPresent(); + } - private Optional>> getResourceByTranslatedResourceId( - String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslateTo translateTo, String heatResourceType) { - List> list = heatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter( - entry -> getPredicatesForTranslatedIdToResourceId(fileName, heatOrchestrationTemplate, - translatedResourceId, translateTo.getContext(), heatResourceType) - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); - if (CollectionUtils.isEmpty(list)) { - return Optional.empty(); - } else { - return Optional.of(list); + private Optional>> getResourceByTranslatedResourceId(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslateTo translateTo, + String heatResourceType) { + List> list = heatOrchestrationTemplate.getResources().entrySet().stream().filter( + entry -> getPredicatesForTranslatedIdToResourceId(fileName, heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), + heatResourceType).stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(list)) { + return Optional.empty(); + } else { + return Optional.of(list); + } } - } - private List>> getPredicatesForTranslatedIdToResourceId( - String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslationContext context, String heatResourceType) { - List>> list = new ArrayList<>(); - list.add(entry -> entry.getValue().getType().equals(heatResourceType)); - list.add(entry -> { - Optional resourceTranslatedId = ResourceTranslationBase - .getResourceTranslatedId(fileName, heatOrchestrationTemplate, entry.getKey(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(translatedResourceId); - }); - return list; - } + private List>> getPredicatesForTranslatedIdToResourceId(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslationContext context, + String heatResourceType) { + List>> list = new ArrayList<>(); + list.add(entry -> entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> { + Optional resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(fileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(translatedResourceId); + }); + return list; + } - private boolean isOutputIsGetResource(String resourceId, FileData data, - AttachedResourceId attachedResourceId) { - if (attachedResourceId.isGetResource()) { - return true; - } else { - logger.warn("output: '" + resourceId + "' in file '" + data.getFile() - + "' is not defined as get_resource and therefore not supported as shared resource."); - return false; + private boolean isOutputIsGetResource(String resourceId, FileData data, AttachedResourceId attachedResourceId) { + if (attachedResourceId.isGetResource()) { + return true; + } else { + logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + + "' is not defined as get_resource and therefore not supported as shared resource."); + return false; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java index aad57e0d5e..f65dc888f8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import static org.openecomp.sdc.translator.services.heattotosca.ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -44,16 +42,14 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslatio public class FunctionTranslationGetAttrImpl implements FunctionTranslation { private static List translateGetAttributeFunctionExpression(FunctionTranslator functionTranslator) { - List attributeParamList = (List) functionTranslator.getFunctionValue(); List toscaAttributeParamList = new ArrayList<>(); - Optional targetResourceTranslatedId = Optional.empty(); String targetResourceId = null; if (attributeParamList.get(0) instanceof String) { targetResourceId = (String) attributeParamList.get(0); targetResourceTranslatedId = handleResourceName(targetResourceId, functionTranslator.getHeatFileName(), - functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); + functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); } if (!targetResourceTranslatedId.isPresent()) { //unsupported resource @@ -65,98 +61,80 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { if (!toscaAttList.isPresent()) { //Unsupported attribute toscaAttributeParamList.clear(); - toscaAttributeParamList.add(functionTranslator.getUnsupportedAttributePrefix() - + attributeParamList.get(0) + "." + attributeParamList.get(1)); + toscaAttributeParamList + .add(functionTranslator.getUnsupportedAttributePrefix() + attributeParamList.get(0) + "." + attributeParamList.get(1)); return toscaAttributeParamList; } toscaAttributeParamList.addAll(toscaAttList.get()); - handleGetAttrConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId.get(), - toscaAttList.get()); - - String resourceType = HeatToToscaUtil.getResourceType((String) attributeParamList.get(0), functionTranslator - .getHeatOrchestrationTemplate(), functionTranslator.getHeatFileName()); - Optional> toscaIndexOrKey = handleAttributeIndexOrKey(functionTranslator, resourceType, - attributeParamList); + handleGetAttrConsolidationData(functionTranslator, targetResourceId, targetResourceTranslatedId.get(), toscaAttList.get()); + String resourceType = HeatToToscaUtil.getResourceType((String) attributeParamList.get(0), functionTranslator.getHeatOrchestrationTemplate(), + functionTranslator.getHeatFileName()); + Optional> toscaIndexOrKey = handleAttributeIndexOrKey(functionTranslator, resourceType, attributeParamList); toscaIndexOrKey.ifPresent(toscaAttributeParamList::addAll); return toscaAttributeParamList; } - private static void handleGetAttrConsolidationData(FunctionTranslator functionTranslator, - String targetResourceId, - String targetResourceTranslatedId, - List toscaAttList) { + private static void handleGetAttrConsolidationData(FunctionTranslator functionTranslator, String targetResourceId, + String targetResourceTranslatedId, List toscaAttList) { Optional resourceTranslatedId; String resourceId = functionTranslator.getResourceId(); String resourceTranslatedIdValue = null; if (resourceId != null) { resourceTranslatedId = handleResourceName(resourceId, functionTranslator.getHeatFileName(), - functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); + functionTranslator.getHeatOrchestrationTemplate(), functionTranslator.getContext()); if (resourceTranslatedId.isPresent()) { resourceTranslatedIdValue = resourceTranslatedId.get(); - handleGetAttrOutConsolidationData(functionTranslator, targetResourceTranslatedId, - resourceTranslatedIdValue, toscaAttList); + handleGetAttrOutConsolidationData(functionTranslator, targetResourceTranslatedId, resourceTranslatedIdValue, toscaAttList); } } - handleGetAttrInConsolidationData(functionTranslator, resourceTranslatedIdValue, - targetResourceId, targetResourceTranslatedId, toscaAttList); + handleGetAttrInConsolidationData(functionTranslator, resourceTranslatedIdValue, targetResourceId, targetResourceTranslatedId, toscaAttList); } - private static void handleGetAttrOutConsolidationData(FunctionTranslator functionTranslator, - String targetTranslatedResourceId, - String resourceTranslatedId, - List toscaAttList) { + private static void handleGetAttrOutConsolidationData(FunctionTranslator functionTranslator, String targetTranslatedResourceId, + String resourceTranslatedId, List toscaAttList) { if (functionTranslator.getServiceTemplate() == null) { return; } - String attName = (String) toscaAttList.get(0); - ConsolidationDataUtil.updateNodeGetAttributeOut(functionTranslator, targetTranslatedResourceId, - resourceTranslatedId, attName); - + ConsolidationDataUtil.updateNodeGetAttributeOut(functionTranslator, targetTranslatedResourceId, resourceTranslatedId, attName); } - private static void handleGetAttrInConsolidationData(FunctionTranslator functionTranslator, - String resourceTranslatedId, - String targetResourceId, - String targetResourceTranslatedId, - List toscaAttList) { + private static void handleGetAttrInConsolidationData(FunctionTranslator functionTranslator, String resourceTranslatedId, String targetResourceId, + String targetResourceTranslatedId, List toscaAttList) { if (functionTranslator.getServiceTemplate() == null) { return; } String attName = (String) toscaAttList.get(0); if (Objects.nonNull(resourceTranslatedId)) { - ConsolidationDataUtil.updateNodeGetAttributeIn(functionTranslator, resourceTranslatedId, - targetResourceId, targetResourceTranslatedId, attName); + ConsolidationDataUtil + .updateNodeGetAttributeIn(functionTranslator, resourceTranslatedId, targetResourceId, targetResourceTranslatedId, attName); } else { - ConsolidationDataUtil.updateOutputParamGetAttrIn(functionTranslator, targetResourceId, - targetResourceTranslatedId, functionTranslator.getPropertyName(), attName); + ConsolidationDataUtil + .updateOutputParamGetAttrIn(functionTranslator, targetResourceId, targetResourceTranslatedId, functionTranslator.getPropertyName(), + attName); } } - private static Optional> handleAttributeIndexOrKey(FunctionTranslator functionTranslator, - String resourceType, + private static Optional> handleAttributeIndexOrKey(FunctionTranslator functionTranslator, String resourceType, List attributeParamList) { - List attributeIndexOrKey = new ArrayList<>(); if (attributeParamList.size() < 3) { return Optional.empty(); } - for (int i = 2; i < attributeParamList.size(); i++) { if (isInteger(attributeParamList.get(i))) { attributeIndexOrKey.add(attributeParamList.get(i)); } else if (attributeParamList.get(i) instanceof Map) { attributeIndexOrKey.add(getToscaAttributeValue(functionTranslator, attributeParamList.get(i))); } else { - Object toscaAttributeName = resourceType == null ? null : functionTranslator.getContext() - .getElementMapping(resourceType, Constants.ATTR, getAttributeFullPath(attributeParamList, i)); + Object toscaAttributeName = resourceType == null ? null + : functionTranslator.getContext().getElementMapping(resourceType, Constants.ATTR, getAttributeFullPath(attributeParamList, i)); if (toscaAttributeName == null) { toscaAttributeName = attributeParamList.get(i); } attributeIndexOrKey.add(toscaAttributeName); } } - return Optional.of(attributeIndexOrKey); } @@ -183,18 +161,15 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return StringUtils.isNumeric(String.valueOf(inputNumber)); } - private static Optional handleResourceName(String resourceId, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private static Optional handleResourceName(String resourceId, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { - return ResourceTranslationBase - .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + return ResourceTranslationBase.getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); } - private static Optional> handleAttributeName(List attributeParamList, - FunctionTranslator functionTranslator) { + private static Optional> handleAttributeName(List attributeParamList, FunctionTranslator functionTranslator) { String resourceId = (String) attributeParamList.get(0); - Resource resource = HeatToToscaUtil.getResource(functionTranslator.getHeatOrchestrationTemplate(), - resourceId, functionTranslator.getHeatFileName()); + Resource resource = HeatToToscaUtil + .getResource(functionTranslator.getHeatOrchestrationTemplate(), resourceId, functionTranslator.getHeatFileName()); if (attributeParamList.size() == 1) { return getResourceTranslatedAttributesList(resource, functionTranslator.getContext()); } @@ -204,8 +179,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { if (HeatToToscaUtil.isNestedResource(resource)) { return getNestedResourceTranslatedAttribute((String) attributeParamList.get(1)); } else { - return getResourceTranslatedAttribute(resource, (String) attributeParamList.get(1), functionTranslator - .getContext()); + return getResourceTranslatedAttribute(resource, (String) attributeParamList.get(1), functionTranslator.getContext()); } } @@ -227,8 +201,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return Optional.of(translatedAttributesList); } - private static Optional> getResourceTranslatedAttributesList(Resource resource, - TranslationContext context) { + private static Optional> getResourceTranslatedAttributesList(Resource resource, TranslationContext context) { List translatedAttributes = new ArrayList<>(); if (HeatToToscaUtil.isNestedResource(resource)) { Optional nestedFile = HeatToToscaUtil.getNestedFile(resource); @@ -236,13 +209,11 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { return Optional.empty(); } HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFiles().getFileContentAsStream(nestedFile.get()), HeatOrchestrationTemplate.class); + .yamlToObject(context.getFiles().getFileContentAsStream(nestedFile.get()), HeatOrchestrationTemplate.class); translatedAttributes.addAll(nestedHeatOrchestrationTemplate.getOutputs().keySet()); return Optional.of(translatedAttributes); - } else { - Map resourceMappingAttributes = - context.getElementMapping(resource.getType(), Constants.ATTR); + Map resourceMappingAttributes = context.getElementMapping(resource.getType(), Constants.ATTR); if (resourceMappingAttributes == null) { return Optional.empty(); } @@ -252,9 +223,7 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { } } - private static Optional> getResourceTranslatedAttribute(Resource resource, - String attributeName, - TranslationContext context) { + private static Optional> getResourceTranslatedAttribute(Resource resource, String attributeName, TranslationContext context) { List translatedAttributesList = new ArrayList<>(); String translatedAttribute = context.getElementMapping(resource.getType(), Constants.ATTR, attributeName); if (translatedAttribute != null) { @@ -265,13 +234,10 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { } } - private static Object getToscaAttributeValue(FunctionTranslator functionTranslator, - Object attributeVal) { + private static Object getToscaAttributeValue(FunctionTranslator functionTranslator, Object attributeVal) { if (attributeVal instanceof Map && !((Map) attributeVal).isEmpty()) { - Map.Entry functionMapEntry = - (Map.Entry) ((Map) attributeVal).entrySet().iterator().next(); - Optional functionTranslationInstance = - FunctionTranslationFactory.getInstance(functionMapEntry.getKey()); + Map.Entry functionMapEntry = (Map.Entry) ((Map) attributeVal).entrySet().iterator().next(); + Optional functionTranslationInstance = FunctionTranslationFactory.getInstance(functionMapEntry.getKey()); if (functionTranslationInstance.isPresent()) { functionTranslator.setFunctionValue(functionMapEntry.getValue()); return functionTranslationInstance.get().translateFunction(functionTranslator); @@ -295,8 +261,8 @@ public class FunctionTranslationGetAttrImpl implements FunctionTranslation { public Object translateFunction(FunctionTranslator functionTranslator) { Object returnValue; List attributeFunctionExpression = translateGetAttributeFunctionExpression(functionTranslator); - if (functionTranslator.isResourceSupported(attributeFunctionExpression.get(0).toString()) - && functionTranslator.isAttributeSupported(attributeFunctionExpression.get(0).toString())) { + if (functionTranslator.isResourceSupported(attributeFunctionExpression.get(0).toString()) && functionTranslator + .isAttributeSupported(attributeFunctionExpression.get(0).toString())) { Map getAttrValue = new HashMap<>(); getAttrValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), attributeFunctionExpression); returnValue = getAttrValue; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java index b81f8fbe33..253410e493 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ArtifactDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.ToscaArtifactType; @@ -25,14 +28,9 @@ import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class FunctionTranslationGetFileImpl implements FunctionTranslation { - private static ArtifactDefinition createArtifactDefinition(Object function, - ToscaFileOutputService toscaFileOutputService) { + + private static ArtifactDefinition createArtifactDefinition(Object function, ToscaFileOutputService toscaFileOutputService) { ArtifactDefinition artifactDefinition = new ArtifactDefinition(); artifactDefinition.setType(ToscaArtifactType.NATIVE_DEPLOYMENT); artifactDefinition.setFile("../" + toscaFileOutputService.getArtifactsFolderName() + "/" + function); @@ -41,7 +39,6 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { @Override public Object translateFunction(FunctionTranslator functionTranslator) { - String file = ((String) functionTranslator.getFunctionValue()).replace("file:///", ""); final String artifactId = file.split("\\.")[0]; Map returnValue = new HashMap<>(); @@ -49,7 +46,6 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { artifactParameters.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); returnValue.put(ToscaFunctions.GET_ARTIFACT.getFunctionName(), artifactParameters); artifactParameters.add(artifactId); - ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); if (functionTranslator.getToscaTemplate() instanceof NodeTemplate) { NodeTemplate nodeTemplate = (NodeTemplate) functionTranslator.getToscaTemplate(); @@ -61,5 +57,4 @@ public class FunctionTranslationGetFileImpl implements FunctionTranslation { } return returnValue; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java index 793799e5f0..e7257dd9f4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import java.util.ArrayList; @@ -21,21 +20,21 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; - import org.openecomp.sdc.heat.datatypes.model.HeatPseudoParameters; import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; public class FunctionTranslationGetParamImpl implements FunctionTranslation { + private static Object translateGetParamFunctionExpression(FunctionTranslator functionTranslator) { Object functionValue = functionTranslator.getFunctionValue(); Object returnValue = null; if (functionValue instanceof String) { returnValue = functionValue; if (HeatPseudoParameters.getPseudoParameterNames().contains(functionValue)) { - functionTranslator.getContext().addUsedHeatPseudoParams(functionTranslator.getHeatFileName(), - (String) functionValue, (String) functionValue); + functionTranslator.getContext() + .addUsedHeatPseudoParams(functionTranslator.getHeatFileName(), (String) functionValue, (String) functionValue); } } else if (functionValue instanceof List) { returnValue = new ArrayList<>(); @@ -49,15 +48,13 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { } } } - return returnValue; } private static Object translatedInnerMap(FunctionTranslator functionTranslator, Map paramMap) { Map translatedInnerMapValue = new HashMap<>(); for (Map.Entry entry : paramMap.entrySet()) { - Optional functionTranslationInstance = - FunctionTranslationFactory.getInstance(entry.getKey()); + Optional functionTranslationInstance = FunctionTranslationFactory.getInstance(entry.getKey()); if (functionTranslationInstance.isPresent()) { functionTranslator.setFunctionValue(entry.getValue()); return functionTranslationInstance.get().translateFunction(functionTranslator); @@ -68,8 +65,7 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { return translatedInnerMapValue; } - private static Object translatedInnerValue(FunctionTranslator functionTranslator, - Object value) { + private static Object translatedInnerValue(FunctionTranslator functionTranslator, Object value) { if (value instanceof String) { return value; } else if (value instanceof Map) { @@ -81,15 +77,13 @@ public class FunctionTranslationGetParamImpl implements FunctionTranslation { } return returnedList; } - return value; } @Override public Object translateFunction(FunctionTranslator functionTranslator) { Map returnValue = new HashMap<>(); - returnValue.put(ToscaFunctions.GET_INPUT.getFunctionName(), - translateGetParamFunctionExpression(functionTranslator)); + returnValue.put(ToscaFunctions.GET_INPUT.getFunctionName(), translateGetParamFunctionExpression(functionTranslator)); return returnValue; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java index 383ee5075b..c4feb54f1e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java @@ -13,23 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; +import java.util.Optional; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; -import java.util.Optional; - public class FunctionTranslationGetResourceImpl implements FunctionTranslation { + @Override public Object translateFunction(FunctionTranslator functionTranslator) { Object returnValue; - Optional resourceTranslatedId = ResourceTranslationBase.getResourceTranslatedId(functionTranslator - .getHeatFileName(), functionTranslator.getHeatOrchestrationTemplate(), + Optional resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(functionTranslator.getHeatFileName(), functionTranslator.getHeatOrchestrationTemplate(), (String) functionTranslator.getFunctionValue(), functionTranslator.getContext()); - returnValue = resourceTranslatedId.orElseGet(() -> functionTranslator.getUnsupportedResourcePrefix() - + functionTranslator.getFunctionValue()); + returnValue = resourceTranslatedId.orElseGet(() -> functionTranslator.getUnsupportedResourcePrefix() + functionTranslator.getFunctionValue()); return returnValue; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java index 768f531938..38516df225 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -26,7 +25,6 @@ public class FunctionTranslator { private static final String UNSUPPORTED_RESOURCE_PREFIX = "UNSUPPORTED_RESOURCE_"; private static final String UNSUPPORTED_ATTRIBUTE_PREFIX = "UNSUPPORTED_ATTRIBUTE_"; - private ServiceTemplate serviceTemplate; private String resourceId; private String propertyName; @@ -40,8 +38,7 @@ public class FunctionTranslator { //default constructor } - public FunctionTranslator(TranslateTo functionTranslateTo, String propertyName, Object functionValue, - Template toscaTemplate) { + public FunctionTranslator(TranslateTo functionTranslateTo, String propertyName, Object functionValue, Template toscaTemplate) { this.serviceTemplate = functionTranslateTo.getServiceTemplate(); this.resourceId = functionTranslateTo.getResourceId(); this.propertyName = propertyName; @@ -52,11 +49,9 @@ public class FunctionTranslator { this.context = functionTranslateTo.getContext(); } - public static TranslateTo getFunctionTranslateTo(ServiceTemplate serviceTemplate, String resourceId, - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - return new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, null, resourceId, null, - context); + public static TranslateTo getFunctionTranslateTo(ServiceTemplate serviceTemplate, String resourceId, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + return new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, null, resourceId, null, context); } public ServiceTemplate getServiceTemplate() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java index cbb53ab831..5e68b41a38 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; +import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; + +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; @@ -23,23 +26,14 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; - public class NameExtractorContrailComputeImpl implements NameExtractor { @Override public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { ContrailTranslationHelper contrailTranslationHelper = new ContrailTranslationHelper(); - List propertyRegexMatchers = - contrailTranslationHelper.getPropertyRegexMatchersForComputeNodeType(); - Optional extractedNodeTypeName = NameExtractorUtil.extractNodeTypeNameByPropertiesPriority(resource - .getProperties(), propertyRegexMatchers); - - return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX - + (extractedNodeTypeName.orElseGet(() -> "compute_" + translatedId)); + List propertyRegexMatchers = contrailTranslationHelper.getPropertyRegexMatchersForComputeNodeType(); + Optional extractedNodeTypeName = NameExtractorUtil + .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX + (extractedNodeTypeName.orElseGet(() -> "compute_" + translatedId)); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java index 980e3ca9ba..14b95c0f94 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; +import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; + +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; @@ -23,24 +26,14 @@ import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationNovaServerImpl; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.tosca.services.ToscaConstants.HEAT_NODE_TYPE_SUFFIX; - public class NameExtractorNovaServerImpl implements NameExtractor { @Override public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { ResourceTranslationNovaServerImpl novaServerTranslator = new ResourceTranslationNovaServerImpl(); - List propertyRegexMatchers = - novaServerTranslator.getPropertyRegexMatchersForNovaNodeType(); - + List propertyRegexMatchers = novaServerTranslator.getPropertyRegexMatchersForNovaNodeType(); Optional extractedNodeTypeName = NameExtractorUtil - .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); - - return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX - + (extractedNodeTypeName.orElseGet(() -> translatedId.replace(".", "_"))); + .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + HEAT_NODE_TYPE_SUFFIX + (extractedNodeTypeName.orElseGet(() -> translatedId.replace(".", "_"))); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java index f3aaf710f8..76b147afff 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -23,7 +22,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -51,6 +49,7 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.errors.TranslatorErrorCodes; abstract class BaseResourceConnection { + protected static Logger logger = LoggerFactory.getLogger(BaseResourceConnection.class); protected TranslateTo translateTo; FileData nestedFileData; @@ -58,9 +57,8 @@ abstract class BaseResourceConnection { NodeType nodeType; ResourceTranslationBase resourceTranslationBase; - BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, - FileData nestedFileData, NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { this.translateTo = translateTo; this.nestedFileData = nestedFileData; this.substitutionNodeTemplate = substitutionNodeTemplate; @@ -72,45 +70,33 @@ abstract class BaseResourceConnection { abstract List> getPredicatesListForConnectionPoints(); - abstract Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + abstract Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName); abstract String getDesiredResourceType(); - abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry connectionPointEntry); + abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry connectionPointEntry); - abstract Map.Entry getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, - Map.Entry - connectionPointEntry); + abstract Map.Entry getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, Map.Entry connectionPointEntry); - abstract void addRequirementToConnectResources(Map.Entry connectionPointEntry, - List paramNames); + abstract void addRequirementToConnectResources(Map.Entry connectionPointEntry, List paramNames); abstract List> getAllConnectionPoints(); - abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes); + abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes); void connect() { - ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()); + ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()); List paramNames; HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFileContentAsStream(nestedFileData.getFile()), - HeatOrchestrationTemplate.class); + .yamlToObject(translateTo.getContext().getFileContentAsStream(nestedFileData.getFile()), HeatOrchestrationTemplate.class); List> exposedConnectionPoints = getAllConnectionPoints(); for (Map connectionPointsMap : exposedConnectionPoints) { for (Map.Entry connectionPointEntry : connectionPointsMap.entrySet()) { - paramNames = - getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, - nestedFileData.getFile(), connectionPointEntry); + paramNames = getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, nestedFileData.getFile(), + connectionPointEntry); if (CollectionUtils.isNotEmpty(paramNames)) { addRequirementToConnectResources(connectionPointEntry, paramNames); } @@ -118,51 +104,38 @@ abstract class BaseResourceConnection { } } - private List getConnectionParameterName(ServiceTemplate nestedServiceTemplate, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName, - Map.Entry connectionPointEntry) { + private List getConnectionParameterName(ServiceTemplate nestedServiceTemplate, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, Map.Entry connectionPointEntry) { List connectionParameterNameList = new ArrayList<>(); - String mappedTranslatedResourceId = getMappedNodeTranslatedResourceId(nestedServiceTemplate, - connectionPointEntry); - NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedTranslatedResourceId); + String mappedTranslatedResourceId = getMappedNodeTranslatedResourceId(nestedServiceTemplate, connectionPointEntry); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedTranslatedResourceId); if (isDesiredNodeTemplateType(mappedNodeTemplate)) { - return getResourcesConnectionParameterName(mappedTranslatedResourceId, - nestedHeatOrchestrationTemplate, nestedHeatFileName); + return getResourcesConnectionParameterName(mappedTranslatedResourceId, nestedHeatOrchestrationTemplate, nestedHeatFileName); } - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); if (!toscaAnalyzerService.isSubstitutableNodeTemplate(mappedNodeTemplate)) { return Collections.emptyList(); } Optional mappedSubstituteServiceTemplateName = toscaAnalyzerService - .getSubstituteServiceTemplateName(mappedTranslatedResourceId, mappedNodeTemplate); + .getSubstituteServiceTemplateName(mappedTranslatedResourceId, mappedNodeTemplate); if (!mappedSubstituteServiceTemplateName.isPresent()) { return Collections.emptyList(); } - String mappedNestedHeatFileName = translateTo.getContext().getNestedHeatFileName() - .get(mappedSubstituteServiceTemplateName.get()); + String mappedNestedHeatFileName = translateTo.getContext().getNestedHeatFileName().get(mappedSubstituteServiceTemplateName.get()); if (Objects.isNull(mappedNestedHeatFileName)) { return Collections.emptyList(); } HeatOrchestrationTemplate mappedNestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFileContentAsStream(mappedNestedHeatFileName), - HeatOrchestrationTemplate.class); - ServiceTemplate mappedNestedServiceTemplate = - translateTo.getContext().getTranslatedServiceTemplates().get(mappedNestedHeatFileName); - List nestedPropertyNames = getConnectionParameterName(mappedNestedServiceTemplate, - mappedNestedHeatOrchestrationTemplate, mappedNestedHeatFileName, - getMappedConnectionPointEntry(nestedServiceTemplate, connectionPointEntry)); - + .yamlToObject(translateTo.getContext().getFileContentAsStream(mappedNestedHeatFileName), HeatOrchestrationTemplate.class); + ServiceTemplate mappedNestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates().get(mappedNestedHeatFileName); + List nestedPropertyNames = getConnectionParameterName(mappedNestedServiceTemplate, mappedNestedHeatOrchestrationTemplate, + mappedNestedHeatFileName, getMappedConnectionPointEntry(nestedServiceTemplate, connectionPointEntry)); if (CollectionUtils.isEmpty(nestedPropertyNames)) { return connectionParameterNameList; } for (String propertyName : nestedPropertyNames) { Object propertyValue = mappedNodeTemplate.getProperties().get(propertyName); - if (propertyValue instanceof Map - && ((Map) propertyValue).containsKey(ToscaFunctions.GET_INPUT.getFunctionName())) { + if (propertyValue instanceof Map && ((Map) propertyValue).containsKey(ToscaFunctions.GET_INPUT.getFunctionName())) { Object paramName = ((Map) propertyValue).get(ToscaFunctions.GET_INPUT.getFunctionName()); if (paramName instanceof String) { connectionParameterNameList.add((String) paramName); @@ -172,46 +145,39 @@ abstract class BaseResourceConnection { return connectionParameterNameList; } - private List getResourcesConnectionParameterName(String translatedResourceId, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + private List getResourcesConnectionParameterName(String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List params = new ArrayList<>(); - Optional>> heatResources = - getResourceByTranslatedResourceId(translatedResourceId, nestedHeatOrchestrationTemplate); + Optional>> heatResources = getResourceByTranslatedResourceId(translatedResourceId, + nestedHeatOrchestrationTemplate); if (!heatResources.isPresent()) { return params; } for (Map.Entry resourceEntry : heatResources.get()) { Resource heatResource = resourceEntry.getValue(); if (!MapUtils.isEmpty(heatResource.getProperties())) { - Optional> connectorParamName = - getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, - nestedHeatOrchestrationTemplate, nestedHeatFileName); + Optional> connectorParamName = getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, + nestedHeatOrchestrationTemplate, nestedHeatFileName); connectorParamName.ifPresent(params::addAll); } } return params; } - protected Optional>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - Optional>> resourceByTranslatedResourceId = - resourceTranslationBase.getResourceByTranslatedResourceId(nestedFileData.getFile(), - nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, - getDesiredResourceType()); + protected Optional>> getResourceByTranslatedResourceId(String translatedResourceId, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + Optional>> resourceByTranslatedResourceId = resourceTranslationBase + .getResourceByTranslatedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, + getDesiredResourceType()); if (!resourceByTranslatedResourceId.isPresent()) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage( - "Failed to get original resource from heat for translate resource id '" - + translatedResourceId + "'") - .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION) - .withCategory(ErrorCategory.APPLICATION).build()); + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Failed to get original resource from heat for translate resource id '" + translatedResourceId + "'") + .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION).withCategory(ErrorCategory.APPLICATION).build()); } return resourceByTranslatedResourceId; } - RequirementAssignment createRequirementAssignment(Map.Entry requirementEntry, - String node, + RequirementAssignment createRequirementAssignment(Map.Entry requirementEntry, String node, NodeTemplate nodeTemplate) { RequirementAssignment requirementAssignment = null; if (Objects.nonNull(node)) { @@ -224,88 +190,66 @@ abstract class BaseResourceConnection { return requirementAssignment; } - - Optional getConnectionTranslatedNodeUsingGetParamFunc( - Map.Entry connectionPointEntry, String paramName, - List supportedNodeTypes) { - - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional getConnectionTranslatedNodeUsingGetParamFunc(Map.Entry connectionPointEntry, String paramName, + List supportedNodeTypes) { + Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); - if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, - shareResource)) { + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, shareResource)) { return Optional.of(shareResource.getTranslatedId()); } } return Optional.empty(); } - private boolean isSupportedSharedResource(String paramName, String connectionPointId, - List supportedNodeTypes, + private boolean isSupportedSharedResource(String paramName, String connectionPointId, List supportedNodeTypes, TranslatedHeatResource shareResource) { - return Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) - && validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointId, shareResource.getHeatResource(), supportedNodeTypes); + return Objects.nonNull(shareResource) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) + && validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointId, shareResource.getHeatResource(), + supportedNodeTypes); } - Optional getConnectionTranslatedHeatResourceUsingGetParamFunc( - Map.Entry connectionPointEntry, String paramName, - List supportedNodeTypes) { - - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional getConnectionTranslatedHeatResourceUsingGetParamFunc(Map.Entry connectionPointEntry, String paramName, + List supportedNodeTypes) { + Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); - if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, - shareResource)) { + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (isSupportedSharedResource(paramName, connectionPointEntry.getKey(), supportedNodeTypes, shareResource)) { return Optional.of(shareResource); } } return Optional.empty(); } - - Optional getConnectionTranslatedNodeUsingGetResourceFunc( - Map.Entry connectionPointEntry, String paramName, Object paramValue, - List supportedNodeTypes) { - Optional getResourceAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + Optional getConnectionTranslatedNodeUsingGetResourceFunc(Map.Entry connectionPointEntry, String paramName, Object paramValue, + List supportedNodeTypes) { + Optional getResourceAttachedResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); if (getResourceAttachedResourceId.isPresent()) { // get resource - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(getResourceAttachedResourceId.get()); - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointEntry.getKey(), resource, supportedNodeTypes)) { - return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), getResourceAttachedResourceId.get(), - translateTo.getContext()); + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointEntry.getKey(), resource, + supportedNodeTypes)) { + return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + getResourceAttachedResourceId.get(), translateTo.getContext()); } } - return Optional.empty(); } - Optional getConnectionResourceUsingGetResourceFunc( - Map.Entry connectionPointEntry, String paramName, Object paramValue, - List supportedNodeTypes) { - Optional getResourceAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + Optional getConnectionResourceUsingGetResourceFunc(Map.Entry connectionPointEntry, String paramName, Object paramValue, + List supportedNodeTypes) { + Optional getResourceAttachedResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); if (getResourceAttachedResourceId.isPresent()) { // get resource - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(getResourceAttachedResourceId.get()); - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - connectionPointEntry.getKey(), resource, supportedNodeTypes)) { + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, connectionPointEntry.getKey(), resource, + supportedNodeTypes)) { return getResourceAttachedResourceId; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java index f7aa72cdb4..83824a3535 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java @@ -13,10 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -35,49 +41,32 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION; - public class ContrailPortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { - ContrailPortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + + ContrailPortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); - return toscaAnalyzerService - .isTypeOf(nodeTemplate, ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, - translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()), toscaServiceModel); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, + translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()), toscaServiceModel); } @Override protected List> getPredicatesListForConnectionPoints() { ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Object interfaceListProperty = heatResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceListProperty == null) { @@ -85,25 +74,24 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing } List paramsList = new ArrayList<>(); if (interfaceListProperty instanceof List) { - return getConnectorPropertyParamNameFromList(nestedHeatOrchestrationTemplate, nestedHeatFileName, - (List) interfaceListProperty, paramsList); + return getConnectorPropertyParamNameFromList(nestedHeatOrchestrationTemplate, nestedHeatFileName, (List) interfaceListProperty, + paramsList); } else if (interfaceListProperty instanceof Map) { - return getConnectorPropertyParamNameFromMap(nestedHeatOrchestrationTemplate, nestedHeatFileName, - (Map) interfaceListProperty, paramsList); + return getConnectorPropertyParamNameFromMap(nestedHeatOrchestrationTemplate, nestedHeatFileName, (Map) interfaceListProperty, paramsList); } return Optional.empty(); } - private Optional> getConnectorPropertyParamNameFromList( - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName, - List interfaceListProperty, List paramsList) { + private Optional> getConnectorPropertyParamNameFromList(HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, List interfaceListProperty, + List paramsList) { for (Object interfaceEntry : interfaceListProperty) { if (interfaceEntry instanceof Map) { - Optional attachedVirtualNetwork = HeatToToscaUtil.extractAttachedResourceId( - nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + Optional attachedVirtualNetwork = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), ((Map) interfaceEntry).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); - if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() - && attachedVirtualNetwork.get().getEntityId() instanceof String) { + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() && attachedVirtualNetwork.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); } } @@ -111,17 +99,14 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing return Optional.of(paramsList); } - private Optional> getConnectorPropertyParamNameFromMap(HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName, - Map interfaceListProperty, + private Optional> getConnectorPropertyParamNameFromMap(HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, + String nestedHeatFileName, Map interfaceListProperty, List paramsList) { Optional attachedVirtualNetwork = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, - translateTo.getContext(), - interfaceListProperty.get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); - if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() - && attachedVirtualNetwork.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + interfaceListProperty.get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() && attachedVirtualNetwork.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); return Optional.of(paramsList); } @@ -134,40 +119,30 @@ public class ContrailPortToNetResourceConnection extends ResourceConnectionUsing } @Override - protected void addRequirementToConnectResources( - Map.Entry requirementDefinitionEntry, - List paramNames) { + protected void addRequirementToConnectResources(Map.Entry requirementDefinitionEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } - Integer index = Integer.valueOf( - requirementDefinitionEntry.getKey().substring("link_port_".length()).substring(0, 1)); - + Integer index = Integer.valueOf(requirementDefinitionEntry.getKey().substring("link_port_".length()).substring(0, 1)); String paramName = paramNames.get( - index); // port can connect to one network only and we are + index); // port can connect to one network only and we are + // expecting to get only one param(unlike security rules to port) Object paramValue = translateTo.getResource().getProperties().get(paramName); - List supportedNetworkTypes = - ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger + .warn(LOG_UNSUPPORTED_CONTRAIL_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java index 24ff55de60..a5ac194290 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES_NESTED; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -43,11 +41,9 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; -public class ContrailV2VlanToInterfaceResourceConnection - extends ResourceConnectionUsingRequirementHelper { +public class ContrailV2VlanToInterfaceResourceConnection extends ResourceConnectionUsingRequirementHelper { - ContrailV2VlanToInterfaceResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + ContrailV2VlanToInterfaceResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -60,38 +56,29 @@ public class ContrailV2VlanToInterfaceResourceConnection @Override protected List> getPredicatesListForConnectionPoints() { ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NETWORK_PORT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NETWORK_PORT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO)); return predicates; } @Override - protected Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List interfaces = new ArrayList<>(); Object interfaceRefs = heatResource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) - || ((List) interfaceRefs).isEmpty()) { + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) || ((List) interfaceRefs).isEmpty()) { return Optional.empty(); } if (((List) interfaceRefs).size() > 1) { - logger.warn(LOG_MULTIPLE_INTERFACE_VALUES_NESTED, - translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), - HeatConstants.VMI_REFS_PROPERTY_NAME); + logger.warn(LOG_MULTIPLE_INTERFACE_VALUES_NESTED, translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), HeatConstants.VMI_REFS_PROPERTY_NAME); } Object interfaceRef = ((List) interfaceRefs).get(0); Optional attachedInterfaceResource = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), interfaceRef); - if (attachedInterfaceResource.isPresent() && attachedInterfaceResource.get().isGetParam() - && attachedInterfaceResource.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), interfaceRef); + if (attachedInterfaceResource.isPresent() && attachedInterfaceResource.get().isGetParam() && attachedInterfaceResource.get() + .getEntityId() instanceof String) { interfaces.add((String) attachedInterfaceResource.get().getEntityId()); } return Optional.of(interfaces); @@ -103,44 +90,32 @@ public class ContrailV2VlanToInterfaceResourceConnection } @Override - protected void addRequirementToConnectResources( - Map.Entry requirementDefinitionEntry, - List paramNames) { + protected void addRequirementToConnectResources(Map.Entry requirementDefinitionEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - List supportedInterfaceTypes = - Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedInterfaceTypes); + List supportedInterfaceTypes = Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedInterfaceTypes); } } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { - if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes) - || (new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(connectedResource))) { - logger.warn(LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, - getLogMessageSuffixForConnectedResource(connectedResource), connectedResource.getType(), - connectionPointId, supportedTypes.toString()); + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { + if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes) || (new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(connectedResource))) { + logger.warn(LOG_UNSUPPORTED_VMI_VLAN_SUB_INTERFACE_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, + getLogMessageSuffixForConnectedResource(connectedResource), connectedResource.getType(), connectionPointId, + supportedTypes.toString()); return false; } return true; } private String getLogMessageSuffixForConnectedResource(Resource connectedResource) { - return new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(connectedResource) ? "Vlan Sub interface " : ""; + return new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(connectedResource) ? "Vlan Sub interface " : ""; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java index aece1b3d33..ed5b5928fe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java @@ -13,10 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -32,63 +40,44 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import java.util.*; -import java.util.function.Predicate; +public class ContrailV2VmInterfaceToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION; - -public class ContrailV2VmInterfaceToNetResourceConnection - extends ResourceConnectionUsingRequirementHelper { - - ContrailV2VmInterfaceToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + ContrailV2VmInterfaceToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return (nodeTemplate.getType() - .equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE) - || nodeTemplate.getType() - .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE)); + return (nodeTemplate.getType().equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE) || nodeTemplate.getType() + .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE)); } @Override protected List> getPredicatesListForConnectionPoints() { ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { List networks = new ArrayList<>(); Object virtualNetworkRefs = heatResource.getProperties().get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).isEmpty()) { + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) || ((List) virtualNetworkRefs).isEmpty()) { return Optional.empty(); } if (((List) virtualNetworkRefs).size() > 1) { - logger.warn(LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES, translateTo.getResourceId(), - translateTo.getResource().getType(), heatResourceId, - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + logger.warn(LOG_MULTIPLE_VIRTUAL_NETWORK_REFS_VALUES, translateTo.getResourceId(), translateTo.getResource().getType(), heatResourceId, + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); } Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); Optional network = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), virtualNetworkRef); - if (network.isPresent() && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), virtualNetworkRef); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { networks.add((String) network.get().getEntityId()); } return Optional.of(networks); @@ -100,33 +89,24 @@ public class ContrailV2VmInterfaceToNetResourceConnection } @Override - protected void addRequirementToConnectResources( - Map.Entry requirementDefinitionEntry, - List paramNames) { + protected void addRequirementToConnectResources(Map.Entry requirementDefinitionEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - List supportedNetworkTypes = - ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION, - nestedResourceId, nestedPropertyName, connectedResource.getType(), connectionPointId, - supportedTypes.toString()); + logger.warn(LOG_UNSUPPORTED_VMI_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java index cd8e3764e2..e2a39e2bca 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION; @@ -26,7 +25,6 @@ import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; @@ -53,8 +51,7 @@ import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslatio class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelper { - NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -62,36 +59,27 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp @Override boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = - HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NOVA_SERVER, - translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()), toscaServiceModel); + translateTo.getContext().getTranslatedServiceTemplates().get(translateTo.getResource().getType()), toscaServiceModel); } @Override List> getPredicatesListForConnectionPoints() { ArrayList> predicates = new ArrayList<>(); - predicates - .add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_ATTACHMENT) - && req.getNode().equals(ToscaNodeType.NATIVE_BLOCK_STORAGE) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_ATTACHES_TO)); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_ATTACHMENT) && req.getNode().equals(ToscaNodeType.NATIVE_BLOCK_STORAGE) + && req.getRelationship().equals(ToscaRelationshipType.NATIVE_ATTACHES_TO)); return predicates; } @Override Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - String nestedHeatFileName) { - - + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Optional volumeId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), heatResource.getProperties().get("volume_id")); - if (volumeId.isPresent() && volumeId.get().isGetParam() - && volumeId.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get("volume_id")); + if (volumeId.isPresent() && volumeId.get().isGetParam() && volumeId.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) volumeId.get().getEntityId())); } else { return Optional.empty(); @@ -104,58 +92,36 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp } @Override - void addRequirementToConnectResources( - Map.Entry requirementDefinitionEntry, - List paramNames) { - - + void addRequirementToConnectResources(Map.Entry requirementDefinitionEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } - - List supportedVolumeTypes = - Collections.singletonList(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - + List supportedVolumeTypes = Collections.singletonList(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); for (String paramName : paramNames) { Object paramValue = translateTo.getResource().getProperties().get(paramName); - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedVolumeTypes); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedVolumeTypes); } - } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { - - + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger + .warn(LOG_UNSUPPORTED_VOL_ATTACHMENT_VOLUME_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } - return true; } @Override - protected Optional>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - - - List>> predicates = - buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translatedResourceId); - List> list = - nestedHeatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter(entry -> predicates - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); + protected Optional>> getResourceByTranslatedResourceId(String translatedResourceId, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + List>> predicates = buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translatedResourceId); + List> list = nestedHeatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> predicates.stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); if (CollectionUtils.isEmpty(list)) { return Optional.empty(); } else { @@ -164,26 +130,20 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp } @Override - Optional getConnectionTranslatedNodeUsingGetParamFunc( - Map.Entry requirementDefinitionEntry, String paramName, - List supportedTargetNodeTypes) { - - + Optional getConnectionTranslatedNodeUsingGetParamFunc(Map.Entry requirementDefinitionEntry, + String paramName, List supportedTargetNodeTypes) { Optional targetTranslatedNodeId = super - .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, - supportedTargetNodeTypes); + .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, supportedTargetNodeTypes); if (targetTranslatedNodeId.isPresent()) { return targetTranslatedNodeId; } - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); if (!attachedResourceId.isPresent()) { return Optional.empty(); } AttachedResourceId resourceId = attachedResourceId.get(); if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + TranslatedHeatResource shareResource = translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); if (Objects.nonNull(shareResource)) { return Optional.empty(); } @@ -191,36 +151,28 @@ class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelp Optional fileData = HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); if (fileData.isPresent()) { Optional fileDataContainingResource = new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), - (String) resourceId.getEntityId(), translateTo, FileData.Type.HEAT_VOL); + .getFileDataContainingVolume(fileData.get().getData(), (String) resourceId.getEntityId(), translateTo, FileData.Type.HEAT_VOL); if (fileDataContainingResource.isPresent()) { return Optional.of(fileDataContainingResource.get().getTranslatedResourceId()); } } } - return Optional.empty(); } - private List>> buildPredicates( - String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String novaTranslatedResourceId) { + private List>> buildPredicates(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String novaTranslatedResourceId) { List>> list = new ArrayList<>(); list.add(entry -> entry.getValue().getType().equals(getDesiredResourceType())); list.add(entry -> { Object instanceUuidProp = entry.getValue().getProperties().get("instance_uuid"); TranslationContext context = translateTo.getContext(); Optional instanceUuid = HeatToToscaUtil - .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, - instanceUuidProp); + .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, instanceUuidProp); if (instanceUuid.isPresent()) { - Optional resourceTranslatedId = - ResourceTranslationBase.getResourceTranslatedId(fileName, heatOrchestrationTemplate, - (String) instanceUuid.get().getTranslatedId(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(novaTranslatedResourceId); - + Optional resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(fileName, heatOrchestrationTemplate, (String) instanceUuid.get().getTranslatedId(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(novaTranslatedResourceId); } else { throw new CoreException(new MissingMandatoryPropertyErrorBuilder("instance_uuid").build()); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java index 6782561b36..c3298a6ad5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; @@ -40,12 +39,9 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import com.google.common.collect.ImmutableList; - public class PortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { - PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, + PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @@ -58,33 +54,24 @@ public class PortToNetResourceConnection extends ResourceConnectionUsingRequirem @Override protected List> getPredicatesListForConnectionPoints() { ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) - && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) - && req.getRelationship().equals( - ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + predicates.add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) && (req.getNode() == null || req.getNode() + .equals(ToscaNodeType.NATIVE_ROOT)) && req.getRelationship().equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); return predicates; } @Override - protected Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { Optional network = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo - .getContext(), heatResource.getProperties().get(HeatConstants.NETWORK_PROPERTY_NAME)); - if (network.isPresent() && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get(HeatConstants.NETWORK_PROPERTY_NAME)); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) network.get().getEntityId())); } else { - network = HeatToToscaUtil - .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo - .getContext(), heatResource.getProperties().get(HeatConstants.NETWORK_ID_PROPERTY_NAME)); - if (network.isPresent() - && network.get().isGetParam() - && network.get().getEntityId() instanceof String) { + network = HeatToToscaUtil.extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, translateTo.getContext(), + heatResource.getProperties().get(HeatConstants.NETWORK_ID_PROPERTY_NAME)); + if (network.isPresent() && network.get().isGetParam() && network.get().getEntityId() instanceof String) { return Optional.of(Collections.singletonList((String) network.get().getEntityId())); } else { return Optional.empty(); @@ -98,37 +85,28 @@ public class PortToNetResourceConnection extends ResourceConnectionUsingRequirem } @Override - protected void addRequirementToConnectResources( - Map.Entry requirementDefinitionEntry, - List paramNames) { + protected void addRequirementToConnectResources(Map.Entry requirementDefinitionEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } String paramName = paramNames.get(0); // port can connect to one network only and we are + // expecting to have only one param(unlike security rules to port) Object paramValue = translateTo.getResource().getProperties().get(paramName); - List supportedNetworkTypes = ImmutableList.of( - HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, - supportedNetworkTypes); + List supportedNetworkTypes = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, supportedNetworkTypes); } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - final String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, final String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, - nestedPropertyName, connectedResource.getType(), connectionPointId, supportedTypes.toString()); + logger.warn(LOG_UNSUPPORTED_PORT_NETWORK_REQUIREMENT_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } return true; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java index 0d89b0c363..c2284f29b5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED; @@ -25,8 +24,12 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.services.DataModelUtil; @@ -39,43 +42,31 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact public abstract class ResourceConnectionUsingCapabilityHelper extends BaseResourceConnection { - ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } - abstract Map.Entry createRequirementDefinition( - String capabilityKey); + abstract Map.Entry createRequirementDefinition(String capabilityKey); @Override - String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry connectionPointEntry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .get(connectionPointEntry.getKey()); + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry connectionPointEntry) { + List substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); return substitutionMapping.get(0); } @Override - Map.Entry getMappedConnectionPointEntry( - ServiceTemplate nestedServiceTemplate, - Map.Entry connectionPointEntry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .get(connectionPointEntry.getKey()); + Map.Entry getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + List substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); String mappedNodeTranslatedId = substitutionMapping.get(0); String mappedCapabilityId = substitutionMapping.get(1); - NodeTemplate mappedNodeTemplate = - nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedNodeTranslatedId); - NodeType substituteNodeType = - translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() - .get(mappedNodeTemplate.getType()); - Optional capabilityDefinition = - DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedNodeTranslatedId); + NodeType substituteNodeType = translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional capabilityDefinition = DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); return new Map.Entry() { @Override public String getKey() { @@ -102,74 +93,53 @@ public abstract class ResourceConnectionUsingCapabilityHelper extends BaseResour if (capabilities == null) { return exposedRequirementsList; } - capabilities.entrySet() - .stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - }); + capabilities.entrySet().stream().filter(entry -> predicates.stream().anyMatch(p -> p.test(entry.getValue()))).forEach(entry -> { + Map exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + }); return exposedRequirementsList; } - void addRequirementToConnectResource(Map.Entry connectionPointEntry, - List supportedSourceNodeTypes, String paramName) { + void addRequirementToConnectResource(Map.Entry connectionPointEntry, List supportedSourceNodeTypes, + String paramName) { Object paramValue = translateTo.getResource().getProperties().get(paramName); if (paramValue == null) { - logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, - translateTo.getResourceId(), connectionPointEntry.getKey(), ToscaConstants.CAPABILITY); + logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), connectionPointEntry.getKey(), + ToscaConstants.CAPABILITY); return; } - - Map.Entry requirementDefinition = - createRequirementDefinition(connectionPointEntry.getKey()); - - Optional sourceResourceId = - getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, - supportedSourceNodeTypes); + Map.Entry requirementDefinition = createRequirementDefinition(connectionPointEntry.getKey()); + Optional sourceResourceId = getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, + supportedSourceNodeTypes); if (sourceResourceId.isPresent()) { Resource sourceResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), - translateTo.getHeatFileName()); - Optional translatedSourceNodeId = - ResourceTranslationFactory.getInstance(sourceResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), sourceResource, - sourceResourceId.get(), translateTo.getContext()); + .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), translateTo.getHeatFileName()); + Optional translatedSourceNodeId = ResourceTranslationFactory.getInstance(sourceResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + sourceResource, sourceResourceId.get(), translateTo.getContext()); if (translatedSourceNodeId.isPresent()) { - NodeTemplate sourceNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedSourceNodeId.get()); - RequirementAssignment requirementAssignment = createRequirementAssignment( - requirementDefinition, translateTo.getTranslatedId(), sourceNodeTemplate); - ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), - translateTo.getResource(), sourceResource, translatedSourceNodeId.get(), - requirementDefinition.getKey(), requirementAssignment); + NodeTemplate sourceNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedSourceNodeId.get()); + RequirementAssignment requirementAssignment = createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), + sourceNodeTemplate); + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), translateTo.getResource(), sourceResource, + translatedSourceNodeId.get(), requirementDefinition.getKey(), requirementAssignment); } else { - logger.warn(LOG_UNSUPPORTED_CAPABILITY_CONNECTION, sourceResource.getType(), - connectionPointEntry.getKey(), - connectionPointEntry.getValue().getType()); + logger.warn(LOG_UNSUPPORTED_CAPABILITY_CONNECTION, sourceResource.getType(), connectionPointEntry.getKey(), + connectionPointEntry.getValue().getType()); } } else { - Optional sharedSourceTranslatedHeatResource = - getConnectionTranslatedHeatResourceUsingGetParamFunc(connectionPointEntry, paramName, - supportedSourceNodeTypes); + Optional sharedSourceTranslatedHeatResource = getConnectionTranslatedHeatResourceUsingGetParamFunc( + connectionPointEntry, paramName, supportedSourceNodeTypes); if (sharedSourceTranslatedHeatResource.isPresent()) { NodeTemplate sharedSourceNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - sharedSourceTranslatedHeatResource.get().getTranslatedId()); - RequirementAssignment requirementAssignment = createRequirementAssignment( - requirementDefinition, translateTo.getTranslatedId(), sharedSourceNodeTemplate); - - ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), - translateTo.getResource(), sharedSourceTranslatedHeatResource.get().getHeatResource(), - sharedSourceTranslatedHeatResource.get().getTranslatedId(), - requirementDefinition.getKey(), - requirementAssignment); + .getNodeTemplate(translateTo.getServiceTemplate(), sharedSourceTranslatedHeatResource.get().getTranslatedId()); + RequirementAssignment requirementAssignment = createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), + sharedSourceNodeTemplate); + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), translateTo.getResource(), + sharedSourceTranslatedHeatResource.get().getHeatResource(), sharedSourceTranslatedHeatResource.get().getTranslatedId(), + requirementDefinition.getKey(), requirementAssignment); } } } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java index a10eb348db..30ae5dd57a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED; @@ -24,52 +23,40 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -//import org.openecomp.core.model.types.ServiceTemplate; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; abstract class ResourceConnectionUsingRequirementHelper extends BaseResourceConnection { - ResourceConnectionUsingRequirementHelper(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { + + ResourceConnectionUsingRequirementHelper(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override - String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, - Map.Entry connectionPointEntry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(connectionPointEntry.getKey()); + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, Map.Entry connectionPointEntry) { + List substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); return substitutionMapping.get(0); } @Override - Map.Entry getMappedConnectionPointEntry( - ServiceTemplate nestedServiceTemplate, - Map.Entry connectionPointEntry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(connectionPointEntry.getKey()); + Map.Entry getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + List substitutionMapping = nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); String mappedNodeTranslatedId = substitutionMapping.get(0); String mappedReqId = substitutionMapping.get(1); - NodeTemplate mappedNodeTemplate = - nestedServiceTemplate.getTopology_template().getNode_templates() - .get(mappedNodeTranslatedId); - NodeType substituteNodeType = - translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() - .get(mappedNodeTemplate.getType()); - Optional requirementDefinition = - DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); + NodeTemplate mappedNodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates().get(mappedNodeTranslatedId); + NodeType substituteNodeType = translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional requirementDefinition = DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); return new Map.Entry() { @Override public String getKey() { @@ -96,41 +83,30 @@ abstract class ResourceConnectionUsingRequirementHelper extends BaseResourceConn if (requirements == null) { return exposedRequirementsList; } - requirements.stream() - .map(Map::entrySet) - .forEach(x -> x.stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - })); + requirements.stream().map(Map::entrySet) + .forEach(x -> x.stream().filter(entry -> predicates.stream().anyMatch(p -> p.test(entry.getValue()))).forEach(entry -> { + Map exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + })); return exposedRequirementsList; } - void addRequirementToConnectResource( - Map.Entry requirementDefinitionEntry, String paramName, - Object paramValue, List supportedNetworkTypes) { + void addRequirementToConnectResource(Map.Entry requirementDefinitionEntry, String paramName, Object paramValue, + List supportedNetworkTypes) { if (paramValue == null) { - logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), - requirementDefinitionEntry.getKey(), ToscaConstants.REQUIREMENT); + logger.warn(LOG_NESTED_RESOURCE_PROPERTY_NOT_DEFINED, paramName, translateTo.getResourceId(), requirementDefinitionEntry.getKey(), + ToscaConstants.REQUIREMENT); return; } - Optional targetTranslatedNodeId = - getConnectionTranslatedNodeUsingGetResourceFunc(requirementDefinitionEntry, paramName, - paramValue, supportedNetworkTypes); + Optional targetTranslatedNodeId = getConnectionTranslatedNodeUsingGetResourceFunc(requirementDefinitionEntry, paramName, paramValue, + supportedNetworkTypes); if (targetTranslatedNodeId.isPresent()) { - createRequirementAssignment(requirementDefinitionEntry, targetTranslatedNodeId.get(), - substitutionNodeTemplate); + createRequirementAssignment(requirementDefinitionEntry, targetTranslatedNodeId.get(), substitutionNodeTemplate); } else { - targetTranslatedNodeId = - getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, - supportedNetworkTypes); - targetTranslatedNodeId - .ifPresent(targetTranslatedId -> createRequirementAssignment(requirementDefinitionEntry, - targetTranslatedId, substitutionNodeTemplate)); + targetTranslatedNodeId = getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, supportedNetworkTypes); + targetTranslatedNodeId.ifPresent( + targetTranslatedId -> createRequirementAssignment(requirementDefinitionEntry, targetTranslatedId, substitutionNodeTemplate)); } } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java index 9011c9e91c..1e04028480 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -25,9 +24,7 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; - import java.util.stream.Collectors; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -62,76 +59,49 @@ public abstract class ResourceTranslationBase { * @param context the context * @return the resource translated id */ - public static Optional getResourceTranslatedId(String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String resourceId, - TranslationContext context) { + public static Optional getResourceTranslatedId(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId, TranslationContext context) { if (!context.getTranslatedIds().containsKey(heatFileName)) { context.getTranslatedIds().put(heatFileName, new HashMap<>()); } - Map translatedIdsPerFile = context.getTranslatedIds().get(heatFileName); String translatedId = translatedIdsPerFile.get(resourceId); if (translatedId != null) { return Optional.of(translatedId); } - Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } - return getTranslatedResourceId(resourceId, heatFileName, resource, heatOrchestrationTemplate, - context - ); + return getTranslatedResourceId(resourceId, heatFileName, resource, heatOrchestrationTemplate, context); } - private static Optional getTranslatedResourceId(String resourceId, - String heatFileName, - Resource resource, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - TranslateTo translateTo = - generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, - context); - - String translatedId = - ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); - - if (ConsolidationDataUtil.isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(translatedId, - heatFileName, context)) { + private static Optional getTranslatedResourceId(String resourceId, String heatFileName, Resource resource, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + TranslateTo translateTo = generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, context); + String translatedId = ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); + if (ConsolidationDataUtil.isNodeTemplatePointsToServiceTemplateWithoutNodeTemplates(translatedId, heatFileName, context)) { return Optional.empty(); } - if (translatedId != null) { context.getTranslatedIds().get(heatFileName).put(resourceId, translatedId); } - return Optional.ofNullable(translatedId); } private static Optional getResourceTranslatedElementTemplate(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String resourceId, TranslationContext context) { + HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId, TranslationContext context) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } - TranslateTo translateTo = - generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, - context); - - return ResourceTranslationFactory.getInstance(resource) - .getTranslatedToscaTopologyElement(translateTo); + TranslateTo translateTo = generateTranslationTo(heatFileName, heatOrchestrationTemplate, resource, resourceId, context); + return ResourceTranslationFactory.getInstance(resource).getTranslatedToscaTopologyElement(translateTo); } - private static TranslateTo generateTranslationTo(String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - Resource resource, String resourceId, - TranslationContext context) { + private static TranslateTo generateTranslationTo(String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, + String resourceId, TranslationContext context) { TranslateTo to = new TranslateTo(); to.setHeatFileName(heatFileName); to.setServiceTemplate(null); @@ -157,16 +127,12 @@ public abstract class ResourceTranslationBase { * @return the translated id if this resource is supported, or empty value if not supported */ public Optional translateResource(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, + HeatOrchestrationTemplate heatOrchestrationTemplate, Resource resource, String resourceId, TranslationContext context) { - Optional translatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + Optional translatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); context.getTranslatedResources().putIfAbsent(heatFileName, new HashSet<>()); - if (isResourceWithSameIdAppearsInOtherFiles(heatFileName, resourceId, context)) { - throw new CoreException( - new DuplicateResourceIdsInDifferentFilesErrorBuilder(resourceId).build()); + throw new CoreException(new DuplicateResourceIdsInDifferentFilesErrorBuilder(resourceId).build()); } if (context.getTranslatedResources().get(heatFileName).contains(resourceId)) { return translatedId; @@ -174,13 +140,11 @@ public abstract class ResourceTranslationBase { if (!translatedId.isPresent()) { return Optional.empty(); } - logger.debug("Translate- file: {} resource Id: {} translated resource id: {}", - heatFileName, resourceId, translatedId.get()); - TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate, - heatOrchestrationTemplate, resource, resourceId, translatedId.get(), context); + logger.debug("Translate- file: {} resource Id: {} translated resource id: {}", heatFileName, resourceId, translatedId.get()); + TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, resourceId, translatedId.get(), + context); translate(translateTo); context.getTranslatedResources().get(heatFileName).add(resourceId); - if (DataModelUtil.isNodeTemplate(translatedId.get(), serviceTemplate)) { if (!context.getHeatStackGroupMembers().containsKey(heatFileName)) { context.getHeatStackGroupMembers().put(heatFileName, new HashSet<>()); @@ -191,14 +155,9 @@ public abstract class ResourceTranslationBase { return translatedId; } - private boolean isResourceWithSameIdAppearsInOtherFiles(String heatFileName, - String resourceId, - TranslationContext context) { - Set translatedResourceIdsFromOtherFiles = - context.getTranslatedResourceIdsFromOtherFiles(heatFileName); - - return CollectionUtils.isNotEmpty(translatedResourceIdsFromOtherFiles) - && translatedResourceIdsFromOtherFiles.contains(resourceId); + private boolean isResourceWithSameIdAppearsInOtherFiles(String heatFileName, String resourceId, TranslationContext context) { + Set translatedResourceIdsFromOtherFiles = context.getTranslatedResourceIdsFromOtherFiles(heatFileName); + return CollectionUtils.isNotEmpty(translatedResourceIdsFromOtherFiles) && translatedResourceIdsFromOtherFiles.contains(resourceId); } protected String generateTranslatedId(TranslateTo translateTo) { @@ -207,11 +166,9 @@ public abstract class ResourceTranslationBase { } else { return null; } - } - protected Optional getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional getTranslatedToscaTopologyElement(TranslateTo translateTo) { if (isEssentialRequirementsValid(translateTo)) { return Optional.of(ToscaTopologyTemplateElements.NODE_TEMPLATE); } else { @@ -224,12 +181,10 @@ public abstract class ResourceTranslationBase { } private void updateResourceDependency(TranslateTo translateTo) { - Resource resource = translateTo.getResource(); if (resource.getDepends_on() == null) { return; } - if (resource.getDepends_on() instanceof List) { List dependsOnList = (List) resource.getDepends_on(); for (String dependsOnResourceId : dependsOnList) { @@ -243,67 +198,47 @@ public abstract class ResourceTranslationBase { private void addDependency(String dependsOnResourceId, TranslateTo translateTo) { String heatFileName = translateTo.getHeatFileName(); - HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo - .getHeatOrchestrationTemplate(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); TranslationContext context = translateTo.getContext(); - - Optional resourceTranslatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, - context); - - Optional resourceTranslatedElementTemplate = - getResourceTranslatedElementTemplate(heatFileName, heatOrchestrationTemplate, - dependsOnResourceId, context); - - if (resourceTranslatedId.isPresent() - && (resourceTranslatedElementTemplate.isPresent() - && resourceTranslatedElementTemplate.get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) { + Optional resourceTranslatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, context); + Optional resourceTranslatedElementTemplate = getResourceTranslatedElementTemplate(heatFileName, + heatOrchestrationTemplate, dependsOnResourceId, context); + if (resourceTranslatedId.isPresent() && (resourceTranslatedElementTemplate.isPresent() + && resourceTranslatedElementTemplate.get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) { Resource sourceResource = translateTo.getResource(); - Resource targetResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, dependsOnResourceId, - translateTo.getHeatFileName()); + Resource targetResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, dependsOnResourceId, translateTo.getHeatFileName()); if (isValidDependency(sourceResource, targetResource, translateTo)) { - addDependsOnRequirement(dependsOnResourceId, translateTo, resourceTranslatedId.get(), sourceResource, - targetResource); + addDependsOnRequirement(dependsOnResourceId, translateTo, resourceTranslatedId.get(), sourceResource, targetResource); } } } - private void addDependsOnRequirement(String dependsOnResourceId, TranslateTo translateTo, - String resourceTranslatedId, Resource sourceResource, + private void addDependsOnRequirement(String dependsOnResourceId, TranslateTo translateTo, String resourceTranslatedId, Resource sourceResource, Resource targetResource) { RequirementAssignment requirementAssignment = new RequirementAssignment(); requirementAssignment.setNode(resourceTranslatedId); requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NODE); requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_DEPENDS_ON); - DataModelUtil.addRequirementAssignment(translateTo.getServiceTemplate().getTopology_template() - .getNode_templates().get(translateTo.getTranslatedId()), + DataModelUtil + .addRequirementAssignment(translateTo.getServiceTemplate().getTopology_template().getNode_templates().get(translateTo.getTranslatedId()), ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); ConsolidationDataUtil - .updateNodesConnectedData(translateTo, dependsOnResourceId, targetResource, - sourceResource, translateTo.getTranslatedId(), ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, - requirementAssignment); + .updateNodesConnectedData(translateTo, dependsOnResourceId, targetResource, sourceResource, translateTo.getTranslatedId(), + ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); } private boolean isValidDependency(Resource sourceResource, Resource targetResource, TranslateTo translateTo) { - return !(HeatToToscaUtil.isNestedResource(sourceResource) || HeatToToscaUtil.isNestedResource(targetResource)) - && HeatToToscaUtil.isValidDependsOnCandidate(sourceResource, targetResource, - ConsolidationEntityType.OTHER, translateTo.getContext()); + return !(HeatToToscaUtil.isNestedResource(sourceResource) || HeatToToscaUtil.isNestedResource(targetResource)) && HeatToToscaUtil + .isValidDependsOnCandidate(sourceResource, targetResource, ConsolidationEntityType.OTHER, translateTo.getContext()); } - Optional>> getResourceByTranslatedResourceId( - String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, - TranslateTo translateTo, - String heatResourceType) { - List> list = heatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter(entry -> getPredicatesForTranslatedIdToResourceId(heatFileName, - heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), - heatResourceType) - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); + Optional>> getResourceByTranslatedResourceId(String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslateTo translateTo, + String heatResourceType) { + List> list = heatOrchestrationTemplate.getResources().entrySet().stream().filter( + entry -> getPredicatesForTranslatedIdToResourceId(heatFileName, heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), + heatResourceType).stream().allMatch(p -> p.test(entry))).collect(Collectors.toList()); if (CollectionUtils.isEmpty(list)) { return Optional.empty(); } else { @@ -311,17 +246,16 @@ public abstract class ResourceTranslationBase { } } - private List>> getPredicatesForTranslatedIdToResourceId( - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslationContext context, String heatResourceType) { + private List>> getPredicatesForTranslatedIdToResourceId(String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslationContext context, + String heatResourceType) { List>> list = new ArrayList<>(); - list.add(entry -> - entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> entry.getValue().getType().equals(heatResourceType)); list.add(entry -> { - Optional resourceTranslatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(translatedResourceId); + Optional resourceTranslatedId = getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() && resourceTranslatedId.get().equals(translatedResourceId); }); return list; } @@ -329,5 +263,4 @@ public abstract class ResourceTranslationBase { boolean isUnsupportedResourceType(Resource resource, List supportedTypes) { return !Objects.nonNull(resource) || !supportedTypes.contains(resource.getType()); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java index ed772346cf..a0ec36c937 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java @@ -13,9 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_INSTANCE_UUID; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; + +import java.util.List; +import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate; @@ -42,13 +47,6 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatory import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_INSTANCE_UUID; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; - public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); @@ -59,19 +57,15 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans relationTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); String heatFileName = translateTo.getHeatFileName(); relationTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - relationTemplate.getProperties(), heatFileName, - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - relationTemplate, translateTo.getContext())); - + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), relationTemplate.getProperties(), heatFileName, translateTo.getHeatOrchestrationTemplate(), + translateTo.getResource().getType(), relationTemplate, translateTo.getContext())); String volumeIdPropertyName = HeatConstants.VOL_ID_PROPERTY_NAME; AttachedResourceId attachedVolumeId = getAttachedResourceId(translateTo, volumeIdPropertyName); String instanceUuid = HeatConstants.INSTANCE_UUID_PROPERTY_NAME; AttachedResourceId attachedNovaServerId = getAttachedResourceId(translateTo, instanceUuid); if (attachedNovaServerId.isGetResource()) { - handleNovaGetResource(translateTo, relationTemplate, attachedVolumeId, - (String) attachedNovaServerId.getEntityId()); + handleNovaGetResource(translateTo, relationTemplate, attachedVolumeId, (String) attachedNovaServerId.getEntityId()); } else { logger.warn(LOG_INVALID_INSTANCE_UUID, translateTo.getResourceId(), translateTo.getResource().getType()); } @@ -87,16 +81,15 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans } private AttachedResourceId getAttachedResourceId(TranslateTo translateTo, String propertyName) { - Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, - propertyName); + Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); if (!attachedResourceId.isPresent()) { throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); } return attachedResourceId.get(); } - private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, String novaResourceId) { + private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, AttachedResourceId volResourceId, + String novaResourceId) { RequirementAssignment requirement = new RequirementAssignment(); String toscaCapabilityAttachment = ToscaCapabilityType.NATIVE_ATTACHMENT; requirement.setCapability(toscaCapabilityAttachment); @@ -108,93 +101,72 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans translateNovaServerResource(translateTo, novaResourceId, requirement); } - private void translateNovaServerResource(TranslateTo translateTo, String novaResourceId, - RequirementAssignment requirement) { - Resource novaServerResource = - getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, translateTo.getHeatFileName()); - if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), - novaServerResource.getType())) { - logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), - novaServerResource.getType(), HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); + private void translateNovaServerResource(TranslateTo translateTo, String novaResourceId, RequirementAssignment requirement) { + Resource novaServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, translateTo.getHeatFileName()); + if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), novaServerResource.getType())) { + logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), novaServerResource.getType(), + HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); return; } Optional translatedNovaServerId = ResourceTranslationFactory.getInstance(novaServerResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), novaServerResource, novaResourceId, - translateTo.getContext()); - + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + novaServerResource, novaResourceId, translateTo.getContext()); if (translatedNovaServerId.isPresent() && StringUtils.isNotEmpty(requirement.getNode())) { - NodeTemplate novaServerNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); - DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, ToscaConstants - .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + NodeTemplate novaServerNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); + DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirement); //Add volume information to consolidation data - ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, - novaServerNodeTemplate.getType(), translatedNovaServerId.get(), ToscaConstants - .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaServerNodeTemplate.getType(), translatedNovaServerId.get(), + ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirement); } } - private void createVolumeNovaRelationshipForVolGetParam(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, - RequirementAssignment requirement) { + private void createVolumeNovaRelationshipForVolGetParam(TranslateTo translateTo, RelationshipTemplate relationTemplate, + AttachedResourceId volResourceId, RequirementAssignment requirement) { String volumeResourceIdParamName = (String) volResourceId.getEntityId(); - if (translateTo.getContext().getHeatSharedResourcesByParam().containsKey(volumeResourceIdParamName) - && !isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (translateTo.getContext().getHeatSharedResourcesByParam().containsKey(volumeResourceIdParamName) && !isHeatFileNested(translateTo, + translateTo.getHeatFileName())) { handleSharedVolume(translateTo, relationTemplate, requirement, volumeResourceIdParamName); } else { handleUnsharedVolume(translateTo, relationTemplate, requirement, volumeResourceIdParamName); } } - private void handleSharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, - RequirementAssignment requirement, String volumeResourceIdParamName) { - Resource volServerResource = translateTo.getContext().getHeatSharedResourcesByParam() - .get(volumeResourceIdParamName).getHeatResource(); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { - logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), - volServerResource.getType(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + private void handleSharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, + String volumeResourceIdParamName) { + Resource volServerResource = translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName).getHeatResource(); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), volServerResource.getType())) { + logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), volServerResource.getType(), + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); return; } - requirement.setNode(translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) - .getTranslatedId()); + requirement.setNode(translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName).getTranslatedId()); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } - private void createVolumeNovaRelationshipForVolGetResource(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - AttachedResourceId volResourceId, - RequirementAssignment requirement) { - Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), - (String) volResourceId.getTranslatedId(), translateTo.getHeatFileName()); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { + private void createVolumeNovaRelationshipForVolGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, + AttachedResourceId volResourceId, RequirementAssignment requirement) { + Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), (String) volResourceId.getTranslatedId(), + translateTo.getHeatFileName()); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), volServerResource.getType())) { logger.warn(LOG_UNSUPPORTED_VOLUME_ATTACHMENT_MSG, translateTo.getResourceId(), volServerResource.getType(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); return; } requirement.setNode((String) volResourceId.getTranslatedId()); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } - private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, - RequirementAssignment requirement, String volumeResourceId) { + private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, + String volumeResourceId) { List allFilesData = translateTo.getContext().getManifest().getContent().getData(); Optional fileData = HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); if (fileData.isPresent()) { - Optional fileDataContainingResource = - new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, - FileData.Type.HEAT_VOL); - fileDataContainingResource.ifPresent(resourceFileDataAndIDs -> addRelationshipToServiceTemplate( - translateTo, relationTemplate, requirement, resourceFileDataAndIDs)); + Optional fileDataContainingResource = new VolumeTranslationHelper(logger) + .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, FileData.Type.HEAT_VOL); + fileDataContainingResource.ifPresent( + resourceFileDataAndIDs -> addRelationshipToServiceTemplate(translateTo, relationTemplate, requirement, resourceFileDataAndIDs)); } } @@ -202,17 +174,13 @@ public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTrans return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName); } - private void addRelationshipToServiceTemplate(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - RequirementAssignment requirement, + private void addRelationshipToServiceTemplate(TranslateTo translateTo, RelationshipTemplate relationTemplate, RequirementAssignment requirement, ResourceFileDataAndIDs resourceFileDataAndIDs) { String translatedId = resourceFileDataAndIDs.getTranslatedResourceId(); - String toscaVolIdPropName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VOL_ID_PROPERTY_NAME); + String toscaVolIdPropName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VOL_ID_PROPERTY_NAME); relationTemplate.getProperties().put(toscaVolIdPropName, translatedId); requirement.setNode(translatedId); requirement.setRelationship(translateTo.getTranslatedId()); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - relationTemplate); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), relationTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java index a69c26c04f..a00d45e164 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.Map; @@ -26,7 +25,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase { private static final String VOLUME_SIZE_PROPERTY_NAME = "size"; @@ -36,23 +34,18 @@ public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase final NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); handleSizeProperty(nodeTemplate.getProperties()); - final String toscaReadOnlyPropName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.READ_ONLY_PROPERTY_NAME); + final String toscaReadOnlyPropName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.READ_ONLY_PROPERTY_NAME); final Object readOnlyPropVal = nodeTemplate.getProperties().get(toscaReadOnlyPropName); if (readOnlyPropVal != null && !(readOnlyPropVal instanceof Map)) { nodeTemplate.getProperties().put(toscaReadOnlyPropName, HeatBoolean.eval(readOnlyPropVal)); } - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - private void handleSizeProperty(final Map nodeTemplateProperties) { final Object size = nodeTemplateProperties.get(VOLUME_SIZE_PROPERTY_NAME); if (size == null) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java index 5708748ce9..ede04e1ff0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.heat.services.HeatConstants.NETWORK_PROPERTY_NAME; +import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_POLICY_RESOURCE; + +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -30,12 +36,6 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import java.util.Optional; - -import static org.openecomp.sdc.heat.services.HeatConstants.NETWORK_PROPERTY_NAME; -import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.*; - public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTranslationBase { protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationContrailAttachPolicyImpl.class); @@ -47,11 +47,10 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla if (translatedNetworkResourceId == null) { return; } - NodeTemplate policyNodeTemplate = getTranslatedPolicyNodeTemplate(translateTo, heatFileName); if (policyNodeTemplate != null) { DataModelUtil.addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createAttachmentRequirementAssignment(translatedNetworkResourceId)); + createAttachmentRequirementAssignment(translatedNetworkResourceId)); } } @@ -61,35 +60,27 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla } @Override - protected Optional getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } - private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, - String heatFileName) { + private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, String heatFileName) { AttachedResourceId attachedPolicyResourceId = extractAttachedResourceIdHandleMissing(translateTo, "policy"); NodeTemplate policyNodeTemplate = new NodeTemplate(); - Optional policyResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId); + Optional policyResourceId = HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId); if (policyResourceId.isPresent()) { policyNodeTemplate = getPolicyNodeTemplate(translateTo, heatFileName, policyResourceId.get()); } else { - logger.warn(LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_POLICY_PROPERTY_GET_ATTR, translateTo.getResourceId(), translateTo.getResource().getType()); } return policyNodeTemplate; } - private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, - String policyResourceId) { - Resource policyResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); - Optional translatedPolicyResourceId = - ResourceTranslationFactory.getInstance(policyResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); + private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, String policyResourceId) { + Resource policyResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); + Optional translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), policyResource, + policyResourceId, translateTo.getContext()); if (!translatedPolicyResourceId.isPresent()) { logger.warn(LOG_UNSUPPORTED_POLICY_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); return null; @@ -98,24 +89,18 @@ public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTransla } private String getTranslatedNetworkResourceId(TranslateTo translateTo) { - AttachedResourceId attachedNetworkResourceId = extractAttachedResourceIdHandleMissing(translateTo, - NETWORK_PROPERTY_NAME); - + AttachedResourceId attachedNetworkResourceId = extractAttachedResourceIdHandleMissing(translateTo, NETWORK_PROPERTY_NAME); String translatedNetworkResourceId = null; if (attachedNetworkResourceId.isGetResource()) { translatedNetworkResourceId = (String) attachedNetworkResourceId.getTranslatedId(); } else { - logger.warn(LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_POLICY_NETWORK_PROPERTY, translateTo.getResourceId(), translateTo.getResource().getType()); } return translatedNetworkResourceId; } - private AttachedResourceId extractAttachedResourceIdHandleMissing( - TranslateTo translateTo, String propertyName) { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); - + private AttachedResourceId extractAttachedResourceIdHandleMissing(TranslateTo translateTo, String propertyName) { + Optional attachedResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); if (!attachedResourceId.isPresent()) { throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java index b631573e24..6e58f6399e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -26,19 +25,16 @@ import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatT public class ResourceTranslationContrailNetworkPolicyImpl extends ResourceTranslationBase { - protected static Logger logger = - (Logger) LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); + protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); @Override protected void translate(TranslateTo translateTo) { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAIL_NETWORK_RULE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java index 305c034470..d4ee120fb8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.tosca.services.ToscaConstants.MANDATORY_PROPERTY_NAME; @@ -25,14 +24,25 @@ import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogCo import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION; +import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - -import org.onap.sdc.tosca.datatypes.model.*; +import org.onap.sdc.tosca.datatypes.model.AttributeDefinition; +import org.onap.sdc.tosca.datatypes.model.GroupDefinition; +import org.onap.sdc.tosca.datatypes.model.Import; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; +import org.onap.sdc.tosca.datatypes.model.PropertyDefinition; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.onap.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.onap.sdc.tosca.datatypes.model.TopologyTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -63,8 +73,6 @@ import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypes import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import com.google.common.collect.ImmutableList; - public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTranslationBase { private static final String INTERFACE_LIST = "interface_list"; @@ -73,13 +81,11 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran @Override public void translate(TranslateTo translateTo) { Resource serviceInstanceResource = translateTo.getResource(); - AttachedResourceId contrailServiceTemplateAttached = getServiceTemplateAttachedId(translateTo, - serviceInstanceResource); + AttachedResourceId contrailServiceTemplateAttached = getServiceTemplateAttachedId(translateTo, serviceInstanceResource); if (contrailServiceTemplateAttached.isGetResource()) { translateContrailServiceInstance(translateTo, serviceInstanceResource, contrailServiceTemplateAttached); } else { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_GET_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); } } @@ -87,62 +93,49 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran AttachedResourceId contrailServiceTemplateAttached) { String contrailServiceTemplateResourceId = (String) contrailServiceTemplateAttached.getEntityId(); Resource contrailServiceTemplateResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), - contrailServiceTemplateResourceId, translateTo.getHeatFileName()); - if (!contrailServiceTemplateResource.getType() - .equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE, translateTo.getResourceId(), - translateTo.getResource().getType(), contrailServiceTemplateResourceId, - contrailServiceTemplateResource.getType(), - HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource()); + .getResource(translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResourceId, translateTo.getHeatFileName()); + if (!contrailServiceTemplateResource.getType().equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_INVALID_TYPE, translateTo.getResourceId(), translateTo.getResource().getType(), + contrailServiceTemplateResourceId, contrailServiceTemplateResource.getType(), + HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource()); return; } - Optional contrailServiceTemplateTranslatedId = - ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResource, - contrailServiceTemplateResourceId, translateTo.getContext()); + Optional contrailServiceTemplateTranslatedId = ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + contrailServiceTemplateResource, contrailServiceTemplateResourceId, translateTo.getContext()); if (!contrailServiceTemplateTranslatedId.isPresent()) { - logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType(), contrailServiceTemplateResourceId, - contrailServiceTemplateResource.getType()); + logger.warn(LOG_SERVICE_TEMPLATE_PROPERTY_UNSUPPORTED_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType(), + contrailServiceTemplateResourceId, contrailServiceTemplateResource.getType()); return; } - ServiceTemplate globalSubstitutionServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); String contrailStId = ResourceTranslationContrailServiceTemplateImpl - .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); + .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); NodeType substitutedNodeType = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, contrailStId); int numberOfPorts = getServiceInstanceNumberOfPorts(serviceInstanceResource); - if (substitutedNodeType.getRequirements() != null - && substitutedNodeType.getRequirements().size() != numberOfPorts) { + if (substitutedNodeType.getRequirements() != null && substitutedNodeType.getRequirements().size() != numberOfPorts) { logger.warn(LOG_MULTIPLE_SERVICE_INSTANCE_DIFF_INTERFACES, contrailServiceTemplateResourceId); return; } addNetworkLinkRequirements(substitutedNodeType, numberOfPorts); - NodeTemplate substitutedNodeTemplate = createSubstitutedNodeTemplate(translateTo, - contrailServiceTemplateResource, contrailStId, numberOfPorts); + NodeTemplate substitutedNodeTemplate = createSubstitutedNodeTemplate(translateTo, contrailServiceTemplateResource, contrailStId, + numberOfPorts); String computeNodeTypeId = new ContrailTranslationHelper() - .getComputeNodeTypeId(contrailServiceTemplateResource, contrailServiceTemplateResourceId, - contrailServiceTemplateTranslatedId.get(), translateTo.getContext()); + .getComputeNodeTypeId(contrailServiceTemplateResource, contrailServiceTemplateResourceId, contrailServiceTemplateTranslatedId.get(), + translateTo.getContext()); boolean orderedInterfaces = getOrderedInterfaces(contrailServiceTemplateResource); - ServiceTemplate nestedServiceTemplate = createNestedServiceTemplate(translateTo, computeNodeTypeId, - contrailStId, substitutedNodeTemplate, orderedInterfaces); - addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), - nestedServiceTemplate, contrailServiceTemplateResource); + ServiceTemplate nestedServiceTemplate = createNestedServiceTemplate(translateTo, computeNodeTypeId, contrailStId, substitutedNodeTemplate, + orderedInterfaces); + addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), nestedServiceTemplate, contrailServiceTemplateResource); translateTo.getContext().getTranslatedServiceTemplates().put(new ContrailTranslationHelper() - .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), - translateTo.getTranslatedId()), nestedServiceTemplate); + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), translateTo.getTranslatedId()), nestedServiceTemplate); } - private void addAbstractSubstitutionProperty(TranslateTo translateTo, - Map substitutionProperties, - ServiceTemplate nestedServiceTemplate, - Resource contrailServiceTemplateResource) { + private void addAbstractSubstitutionProperty(TranslateTo translateTo, Map substitutionProperties, + ServiceTemplate nestedServiceTemplate, Resource contrailServiceTemplateResource) { Map innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); Object countValue = handleScaleOutProperty(translateTo, innerProps); handleServiceScalingProperty(translateTo, innerProps, contrailServiceTemplateResource); boolean mandatory = false; @@ -157,16 +150,13 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } private Object handleScaleOutProperty(TranslateTo translateTo, Map innerProps) { - Object scaleOutPropertyValue = - translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); + Object scaleOutPropertyValue = translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); Object countValue = null; if (scaleOutPropertyValue instanceof Map) { countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - Constants.MAX_INSTANCES_PROPERTY_NAME, - ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), Constants.MAX_INSTANCES_PROPERTY_NAME, + ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), null, translateTo.getContext()); if (countValue != null) { innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); } else { @@ -178,21 +168,17 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return countValue; } - private void handleServiceScalingProperty(TranslateTo translateTo, Map innerProps, - Resource contrailServiceTemplateResource) { - Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); + private void handleServiceScalingProperty(TranslateTo translateTo, Map innerProps, Resource contrailServiceTemplateResource) { + Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); Object serviceScalingValue; if (serviceScalingPropertyValue != null) { serviceScalingValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - HeatConstants.SERVICE_SCALING_PROPERTY_NAME, serviceScalingPropertyValue, null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, - translateTo.getContext()); + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), HeatConstants.SERVICE_SCALING_PROPERTY_NAME, + serviceScalingPropertyValue, null, translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, + translateTo.getContext()); if (serviceScalingValue != null) { innerProps.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, - (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean.eval(serviceScalingValue) : - serviceScalingValue); + (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean.eval(serviceScalingValue) : serviceScalingValue); } } } @@ -209,47 +195,37 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return true; } - private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, - String computeNodeTypeId, - String substitutedNodeTypeId, - NodeTemplate substitutedNodeTemplate, - boolean orderedInterfaces) { + private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, String computeNodeTypeId, String substitutedNodeTypeId, + NodeTemplate substitutedNodeTemplate, boolean orderedInterfaces) { ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); setNestedServiceTemplateGeneralDetails(translateTo, nestedSubstitutionServiceTemplate); String heatStackGroupKey = addHeatStackGroup(translateTo, nestedSubstitutionServiceTemplate); addSubstitutionMappingEntry(nestedSubstitutionServiceTemplate, substitutedNodeTypeId); handleInputParameters(nestedSubstitutionServiceTemplate, translateTo); - String computeNodeTemplateId = handleComputeNodeTemplate(translateTo, computeNodeTypeId, - nestedSubstitutionServiceTemplate, heatStackGroupKey); + String computeNodeTemplateId = handleComputeNodeTemplate(translateTo, computeNodeTypeId, nestedSubstitutionServiceTemplate, + heatStackGroupKey); handleOutputParameters(nestedSubstitutionServiceTemplate, computeNodeTemplateId, translateTo); handleServiceInstanceInterfaces(translateTo, - new ContrailServiceInstanceTo(nestedSubstitutionServiceTemplate, substitutedNodeTemplate, - heatStackGroupKey, orderedInterfaces, computeNodeTemplateId)); + new ContrailServiceInstanceTo(nestedSubstitutionServiceTemplate, substitutedNodeTemplate, heatStackGroupKey, orderedInterfaces, + computeNodeTemplateId)); return nestedSubstitutionServiceTemplate; } - private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, - String nodeTemplateId, TranslateTo translateTo) { + private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, String nodeTemplateId, TranslateTo translateTo) { if (nodeTemplateId == null) { return; } ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - - Optional contrailAbstractNodeType = - toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo - .getContext().getGlobalServiceTemplates().values()); - + Optional contrailAbstractNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); if (!contrailAbstractNodeType.isPresent()) { return; } - Map contrailAbstractAttributes = - contrailAbstractNodeType.get().getAttributes(); + Map contrailAbstractAttributes = contrailAbstractNodeType.get().getAttributes(); Map nestedSubstitutionServiceTemplateOutputs = new HashMap<>(); - if (contrailAbstractAttributes == null) { return; } - for (Map.Entry attributeDefinitionEntry : contrailAbstractAttributes.entrySet()) { AttributeDefinition abstractAttributeDef = attributeDefinitionEntry.getValue(); if (abstractAttributeDef != null) { @@ -258,22 +234,18 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran outputGetAttributeList.add(nodeTemplateId); outputGetAttributeList.add(attributeDefinitionEntry.getKey()); outputValue.put(ToscaFunctions.GET_ATTRIBUTE.getFunctionName(), outputGetAttributeList); - nestedSubstitutionServiceTemplateOutputs.put(attributeDefinitionEntry.getKey(), - DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); + nestedSubstitutionServiceTemplateOutputs + .put(attributeDefinitionEntry.getKey(), DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); } } - if (!nestedSubstitutionServiceTemplateOutputs.isEmpty()) { - nestedSubstitutionServiceTemplate.getTopology_template() - .setOutputs(nestedSubstitutionServiceTemplateOutputs); + nestedSubstitutionServiceTemplate.getTopology_template().setOutputs(nestedSubstitutionServiceTemplateOutputs); } } - private void handleServiceInstanceInterfaces(TranslateTo translateTo, - ContrailServiceInstanceTo contrailServiceInstanceTo) { + private void handleServiceInstanceInterfaces(TranslateTo translateTo, ContrailServiceInstanceTo contrailServiceInstanceTo) { Resource serviceInstanceResource = translateTo.getResource(); - Object interfaceListProperty = - serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + Object interfaceListProperty = serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceListProperty == null) { return; } @@ -287,99 +259,76 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } - private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, - Integer index, ContrailServiceInstanceTo contrailServiceInstanceTo) { + private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, Integer index, + ContrailServiceInstanceTo contrailServiceInstanceTo) { if (index == null) { index = 0; } NodeTemplate portNodeTemplate = createPortNodeTemplate(index, contrailServiceInstanceTo.isOrderedInterfaces(), - contrailServiceInstanceTo.getComputeNodeTemplateId()); + contrailServiceInstanceTo.getComputeNodeTemplateId()); String portNodeTemplateId = Constants.SERVICE_INSTANCE_PORT_PREFIX + index; String portReqMappingKey = Constants.SERVICE_INSTANCE_LINK_PREFIX + portNodeTemplateId; - - DataModelUtil.addNodeTemplate(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - portNodeTemplateId, portNodeTemplate); - updateSubstitutionMappingRequirement(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - portReqMappingKey, portNodeTemplateId); - updateHeatStackGroup(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), - contrailServiceInstanceTo.getHeatStackGroupKey(), portNodeTemplateId); - connectPortToNetwork(translateTo, interfacePropertyValue, contrailServiceInstanceTo - .getSubstitutedNodeTemplate(), portReqMappingKey); + DataModelUtil.addNodeTemplate(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), portNodeTemplateId, portNodeTemplate); + updateSubstitutionMappingRequirement(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), portReqMappingKey, portNodeTemplateId); + updateHeatStackGroup(contrailServiceInstanceTo.getNestedSubstitutionServiceTemplate(), contrailServiceInstanceTo.getHeatStackGroupKey(), + portNodeTemplateId); + connectPortToNetwork(translateTo, interfacePropertyValue, contrailServiceInstanceTo.getSubstitutedNodeTemplate(), portReqMappingKey); } - private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, - NodeTemplate substitutedNodeTemplate, + private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, NodeTemplate substitutedNodeTemplate, String portReqMappingKey) { - List validNetworksForConnections = ImmutableList.of( - HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + List validNetworksForConnections = ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); if (!(interfacePropertyValue instanceof Map)) { return; } Object virtualNetworkValue = ((Map) interfacePropertyValue).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME); if (virtualNetworkValue == null) { - logger.warn(LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_MISSING_VIRTUAL_NETWORK_INTERFACE_LIST, translateTo.getResourceId(), translateTo.getResource().getType()); return; } Optional networkAttachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), virtualNetworkValue); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkValue); if (!networkAttachedResourceId.isPresent()) { return; } - Optional networkResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); + Optional networkResourceId = HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); if (networkResourceId.isPresent()) { - Resource networkResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - networkResourceId.get(), translateTo.getHeatFileName()); + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getHeatFileName()); if (validNetworksForConnections.contains(networkResource.getType())) { - Optional networkTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getContext()); - networkTranslatedId.ifPresent(translatedId -> addLinkToNetworkRequirementAssignment( - substitutedNodeTemplate, translatedId, portReqMappingKey)); - + Optional networkTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), translateTo.getContext()); + networkTranslatedId + .ifPresent(translatedId -> addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, translatedId, portReqMappingKey)); } else { - logger.warn(LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_UNSUPPORTED_NETWORK_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType()); } - } else if (networkAttachedResourceId.get().isGetParam() - && networkAttachedResourceId.get().getEntityId() instanceof String) { + } else if (networkAttachedResourceId.get().isGetParam() && networkAttachedResourceId.get().getEntityId() instanceof String) { TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() - .get(networkAttachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, - translatedSharedResourceId.getTranslatedId(), portReqMappingKey); + .get(networkAttachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, translatedSharedResourceId.getTranslatedId(), portReqMappingKey); } } else { - logger.warn(LOG_INVALID_NETWORK_CONNECTION, translateTo.getResourceId(), - translateTo.getResource().getType(), virtualNetworkValue.toString()); + logger.warn(LOG_INVALID_NETWORK_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType(), + virtualNetworkValue.toString()); } } - private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, - String computeNodeTemplateId) { + private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, String computeNodeTemplateId) { NodeTemplate portNodeTemplate = new NodeTemplate(); portNodeTemplate.setType(ToscaNodeType.CONTRAIL_PORT); Map portProperties = new HashMap<>(); - portProperties.put("static_routes", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "static_routes")); - portProperties.put("virtual_network", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "virtual_network")); - portProperties.put("allowed_address_pairs", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, - "allowed_address_pairs")); - portProperties.put("ip_address", DataModelUtil - .createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "ip_address")); - portProperties.put("static_route", - DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); - portProperties.put("shared_ip", - DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); - portProperties.put("interface_type", DataModelUtil - .createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); + portProperties.put("static_routes", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "static_routes")); + portProperties.put("virtual_network", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "virtual_network")); + portProperties + .put("allowed_address_pairs", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "allowed_address_pairs")); + portProperties.put("ip_address", DataModelUtil.createGetInputPropertyValueFromListParameter(INTERFACE_LIST, index, "ip_address")); + portProperties.put("static_route", DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); + portProperties.put("shared_ip", DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); + portProperties.put("interface_type", DataModelUtil.createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); if (orderedInterfaces) { portProperties.put("order", index); } @@ -388,10 +337,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return portNodeTemplate; } - - private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, - String connectedNodeTranslatedId, - String requirementId) { + private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, String connectedNodeTranslatedId, String requirementId) { if (nodeTemplate == null || connectedNodeTranslatedId == null) { return; } @@ -402,40 +348,35 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran DataModelUtil.addRequirementAssignment(nodeTemplate, requirementId, requirement); } - private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, - String memberId) { + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, String memberId) { serviceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers().add(memberId); } - private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, - String portReqMappingKey, - String portNodeTemplateId) { + private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, String portReqMappingKey, String portNodeTemplateId) { List portReqMappingValue = new ArrayList<>(); portReqMappingValue.add(portNodeTemplateId); portReqMappingValue.add(ToscaConstants.LINK_REQUIREMENT_ID); DataModelUtil.addSubstitutionMappingReq(serviceTemplate, portReqMappingKey, portReqMappingValue); } - private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, - String substitutedNodeTypeId) { + private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, String substitutedNodeTypeId) { SubstitutionMapping substitutionMappings = new SubstitutionMapping(); substitutionMappings.setNode_type(substitutedNodeTypeId); DataModelUtil.addSubstitutionMapping(nestedSubstitutionServiceTemplate, substitutionMappings); } - private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, - TranslateTo translateTo) { + private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, TranslateTo translateTo) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional contrailAbstractNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType - .CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); + Optional contrailAbstractNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo.getContext().getGlobalServiceTemplates().values()); Map nestedSubstitutionServiceTemplateInputs = new HashMap<>(); if (contrailAbstractNodeType.isPresent()) { Map contrailAbstractProperties = contrailAbstractNodeType.get().getProperties(); for (Map.Entry propertyEntry : contrailAbstractProperties.entrySet()) { PropertyDefinition abstractPropertyDef = contrailAbstractProperties.get(propertyEntry.getKey()); if (abstractPropertyDef != null) { - nestedSubstitutionServiceTemplateInputs.put(propertyEntry.getKey(), - DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); + nestedSubstitutionServiceTemplateInputs + .put(propertyEntry.getKey(), DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); } } } @@ -444,12 +385,11 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } - private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, - ServiceTemplate nestedSubstitutionServiceTemplate, + private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, ServiceTemplate nestedSubstitutionServiceTemplate, String heatStackGroupKey) { ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - Optional contrailComputeNodeType = toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, - translateTo.getContext().getGlobalServiceTemplates().values()); + Optional contrailComputeNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, translateTo.getContext().getGlobalServiceTemplates().values()); Map computeNodeTemplateProperties = null; if (contrailComputeNodeType.isPresent()) { Map contrailComputeProperties = contrailComputeNodeType.get().getProperties(); @@ -462,7 +402,6 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } } } - NodeTemplate computeNodeTemplate = new NodeTemplate(); computeNodeTemplate.setType(computeNodeTypeId); if (computeNodeTemplateProperties != null && !computeNodeTemplateProperties.isEmpty()) { @@ -470,8 +409,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran } String computeNodeTemplateId = translateTo.getTranslatedId(); DataModelUtil.addNodeTemplate(nestedSubstitutionServiceTemplate, computeNodeTemplateId, computeNodeTemplate); - nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey) - .getMembers().add(computeNodeTemplateId); + nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers().add(computeNodeTemplateId); return computeNodeTemplateId; } @@ -479,47 +417,34 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran GroupDefinition serviceInstanceGroupDefinition = new GroupDefinition(); serviceInstanceGroupDefinition.setType(ToscaGroupType.HEAT_STACK); Map groupProperties = new HashMap<>(); - groupProperties.put("heat_file", - "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" - + translateTo.getHeatFileName()); + groupProperties + .put("heat_file", "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" + translateTo.getHeatFileName()); serviceInstanceGroupDefinition.setProperties(groupProperties); serviceInstanceGroupDefinition.setMembers(new ArrayList<>()); String heatStackGroupKey = translateTo.getTranslatedId() + "_group"; - DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, - serviceInstanceGroupDefinition); + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, serviceInstanceGroupDefinition); return heatStackGroupKey; } - - private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, - ServiceTemplate - nestedSubstitutionServiceTemplate) { + private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, ServiceTemplate nestedSubstitutionServiceTemplate) { Map nestedTemplateMetadata = new HashMap<>(); String nestedTemplateName = new ContrailTranslationHelper() - .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), - translateTo.getResourceId()); + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), translateTo.getResourceId()); nestedTemplateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, nestedTemplateName); nestedSubstitutionServiceTemplate.setMetadata(nestedTemplateMetadata); nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); List> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList(); - globalTypesImportList.addAll( - HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + globalTypesImportList.addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); } - private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, - Resource contrailServiceTemplateResource, - String contrailServiceTemplateTranslatedId, - int numberOfPorts) { - boolean isImportAddedToServiceTemplate = - DataModelUtil - .isImportAddedToServiceTemplate(translateTo.getServiceTemplate().getImports(), Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, Resource contrailServiceTemplateResource, + String contrailServiceTemplateTranslatedId, int numberOfPorts) { + boolean isImportAddedToServiceTemplate = DataModelUtil + .isImportAddedToServiceTemplate(translateTo.getServiceTemplate().getImports(), Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (!isImportAddedToServiceTemplate) { - translateTo.getServiceTemplate().getImports() - .addAll(HeatToToscaUtil - .createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + translateTo.getServiceTemplate().getImports().addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); } NodeTemplate substitutesNodeTemplate = new NodeTemplate(); substitutesNodeTemplate.setType(contrailServiceTemplateTranslatedId); @@ -527,74 +452,53 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); substitutesNodeTemplate.setDirectives(directiveList); substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), contrailServiceTemplateResource.getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + contrailServiceTemplateResource.getProperties(), substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.AVAILABILITY_ZONE_ENABLE_PROPERTY_NAME)); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.AVAILABILITY_ZONE_ENABLE_PROPERTY_NAME)); HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.ORDERED_INTERFACES_PROPERTY_NAME)); - - Object sharedIpListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.ORDERED_INTERFACES_PROPERTY_NAME)); + Object sharedIpListPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); String toscaSharedIpListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); - Optional>> sharedIpTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + Optional>> sharedIpTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); if (sharedIpTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put(toscaSharedIpListPropertyName, sharedIpTranslatedSplitFun.get()); + substitutesNodeTemplate.getProperties().put(toscaSharedIpListPropertyName, sharedIpTranslatedSplitFun.get()); } else { HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaSharedIpListPropertyName); } - - Object staticRouteListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + Object staticRouteListPropertyValue = contrailServiceTemplateResource.getProperties().get(HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); String toscaStaticRoutesListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); - Optional>> staticRouteTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + Optional>> staticRouteTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); if (staticRouteTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put(toscaStaticRoutesListPropertyName, staticRouteTranslatedSplitFun.get()); + substitutesNodeTemplate.getProperties().put(toscaStaticRoutesListPropertyName, staticRouteTranslatedSplitFun.get()); } else { HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaStaticRoutesListPropertyName); } - - Object serviceInterfaceTypeListPropertyValue = - contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + Object serviceInterfaceTypeListPropertyValue = contrailServiceTemplateResource.getProperties() + .get(HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); String toscaServiceInterfaceTypeListPropertyName = HeatToToscaUtil - .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), - HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); - Optional>> serviceInterfaceTypeTranslatedSplitFun = - new ContrailTranslationHelper() - .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); - serviceInterfaceTypeTranslatedSplitFun - .ifPresent(translatedSplitFun -> substitutesNodeTemplate.getProperties() - .put(toscaServiceInterfaceTypeListPropertyName, translatedSplitFun)); - + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + Optional>> serviceInterfaceTypeTranslatedSplitFun = new ContrailTranslationHelper() + .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); + serviceInterfaceTypeTranslatedSplitFun.ifPresent( + translatedSplitFun -> substitutesNodeTemplate.getProperties().put(toscaServiceInterfaceTypeListPropertyName, translatedSplitFun)); String substitutedNodeTemplateId = translateTo.getTranslatedId(); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, - substitutesNodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, substitutesNodeTemplate); return substitutesNodeTemplate; } @@ -603,10 +507,9 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran List> requirementList = new ArrayList<>(); for (int i = 0; i < numberOfPorts; i++) { Map requirementDefinitionMap = new HashMap<>(); - requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, - DataModelUtil.createRequirement(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, - ToscaNodeType.NATIVE_ROOT, - ToscaRelationshipType.NATIVE_NETWORK_LINK_TO, null)); + requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, DataModelUtil + .createRequirement(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, ToscaNodeType.NATIVE_ROOT, + ToscaRelationshipType.NATIVE_NETWORK_LINK_TO, null)); requirementList.add(requirementDefinitionMap); } if (numberOfPorts > 0) { @@ -617,8 +520,7 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran private int getServiceInstanceNumberOfPorts(Resource serviceInstanceResource) { int numberOfPorts; - Object interfaceTypeProperty = - serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + Object interfaceTypeProperty = serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); if (interfaceTypeProperty == null) { numberOfPorts = 0; } else if (interfaceTypeProperty instanceof List) { @@ -631,20 +533,15 @@ public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTran return numberOfPorts; } - private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, - Resource serviceInstanceResource) { - Object serviceTemplateProperty = - serviceInstanceResource.getProperties().get("service_template"); + private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, Resource serviceInstanceResource) { + Object serviceTemplateProperty = serviceInstanceResource.getProperties().get("service_template"); Optional serviceTemplateId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - serviceTemplateProperty); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + serviceTemplateProperty); if (serviceTemplateId.isPresent()) { return serviceTemplateId.get(); } else { throw new CoreException(new MissingMandatoryPropertyErrorBuilder("service_template").build()); } } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java index a5eac91acb..456a499119 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.common.errors.CoreException; @@ -30,18 +33,12 @@ import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatory import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTranslationBase { private static final String IMAGE_NAME = "image_name"; static String getContrailSubstitutedNodeTypeId(String serviceTemplateTranslatedId) { - return ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + ToscaConstants.HEAT_NODE_TYPE_SUFFIX - + serviceTemplateTranslatedId; + return ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + ToscaConstants.HEAT_NODE_TYPE_SUFFIX + serviceTemplateTranslatedId; } @Override @@ -60,45 +57,39 @@ public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTran return true; } - private void addComputeNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate, - TranslationContext context) { + private void addComputeNodeType(TranslateTo translateTo, ServiceTemplate globalSubstitutionServiceTemplate, TranslationContext context) { NodeType computeNodeType = new NodeType(); computeNodeType.setDerived_from(ToscaNodeType.CONTRAIL_COMPUTE); - String computeNodeTypeId = new ContrailTranslationHelper().getComputeNodeTypeId(translateTo.getResource(), - translateTo.getResourceId(), translateTo.getTranslatedId(), context); + String computeNodeTypeId = new ContrailTranslationHelper() + .getComputeNodeTypeId(translateTo.getResource(), translateTo.getResourceId(), translateTo.getTranslatedId(), context); DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, computeNodeTypeId, computeNodeType); } - private void addSubstitutedNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate) { + private void addSubstitutedNodeType(TranslateTo translateTo, ServiceTemplate globalSubstitutionServiceTemplate) { NodeType substitutedNodeType = new NodeType(); substitutedNodeType.setDerived_from(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, - getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); + DataModelUtil + .addNodeType(globalSubstitutionServiceTemplate, getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); } @Override - protected Optional getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } private ServiceTemplate getGlobalSubstitutionTypesServiceTemplate(TranslateTo translateTo) { ServiceTemplate globalSubstitutionServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); if (globalSubstitutionServiceTemplate == null) { globalSubstitutionServiceTemplate = new ServiceTemplate(); Map templateMetadata = new HashMap<>(); - templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); globalSubstitutionServiceTemplate.setMetadata(templateMetadata); globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - translateTo.getContext().getTranslatedServiceTemplates().put(Constants - .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); + translateTo.getContext().getTranslatedServiceTemplates() + .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate); } return globalSubstitutionServiceTemplate; } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java index 32aaabc482..3cc4c0945d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -33,11 +32,9 @@ public class ResourceTranslationContrailV2NetworkPolicyImpl extends ResourceTran NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_NETWORK_RULE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java index 556124baba..e7ccd2ba4e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java @@ -13,9 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_INVALID_PROPERTY_VALUE_FORMAT; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -33,11 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.*; - -import static org.openecomp.sdc.tosca.services.DataModelUtil.createAttachmentRequirementAssignment; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.*; - public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTranslationBase { private static final String FQ_NAME = "fq_name"; @@ -48,13 +54,10 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_NETWORK); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); linkToPolicyNodeTemplate(translateTo); } @@ -64,10 +67,10 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return; } for (AttachedResourceId attachedResourceId : networkPolicyIdList) { - NodeTemplate policyNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), - (String) attachedResourceId.getTranslatedId()); + NodeTemplate policyNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), (String) attachedResourceId.getTranslatedId()); DataModelUtil.addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createAttachmentRequirementAssignment(translateTo.getTranslatedId())); + createAttachmentRequirementAssignment(translateTo.getTranslatedId())); } } @@ -79,8 +82,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return Collections.emptyList(); } - private List extractNetworkPolicyId(Object propertyValue, - TranslateTo translateTo) { + private List extractNetworkPolicyId(Object propertyValue, TranslateTo translateTo) { List attachedResourceIdList = new ArrayList<>(); if (propertyValue instanceof List) { for (Object value : (List) propertyValue) { @@ -101,20 +103,16 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (policyResourceId == null) { return null; } - - Resource policyResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - policyResourceId, translateTo.getHeatFileName()); - if (!policyResource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE - .getHeatResource())) { + Resource policyResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, translateTo.getHeatFileName()); + if (!policyResource.getType().equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE.getHeatResource())) { return null; } translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + policyResource, policyResourceId, translateTo.getContext()); if (!translatedPolicyResourceId.isPresent()) { - logger.warn(LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE, - translateTo.getResourceId(), translateTo.getResource().getType()); + logger.warn(LOG_INVALID_NETWORK_POLICY_REFS_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); return null; } return new AttachedResourceId(translatedPolicyResourceId.get(), policyResourceId, ReferenceType.GET_ATTR); @@ -129,8 +127,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra return resourceId; } } - logger.warn(LOG_INVALID_PROPERTY_VALUE_FORMAT, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_VALUE_FORMAT, translateTo.getResourceId(), translateTo.getResource().getType()); return null; } @@ -155,8 +152,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (value.get(0) instanceof String) { return true; } else { - logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_ATTR_FQ_NAME, translateTo.getResourceId(), translateTo.getResource().getType()); } } return false; @@ -189,8 +185,7 @@ public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTra if (value instanceof String) { return (String) value; } else { - logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE, translateTo.getResourceId(), - translateTo.getResource().getType()); + logger.warn(LOG_INVALID_PROPERTY_FORMAT_GET_RESOURCE, translateTo.getResourceId(), translateTo.getResource().getType()); } return null; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java index 5e20d96ca8..3a80b9dfe4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Resource; @@ -29,16 +35,8 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_MULTIPLE_INTERFACE_VALUES; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION; - - public class ResourceTranslationContrailV2VlanSubInterfaceImpl extends ResourceTranslationBase { + protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationContrailV2VlanSubInterfaceImpl.class); @Override @@ -46,59 +44,45 @@ public class ResourceTranslationContrailV2VlanSubInterfaceImpl extends ResourceT NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); new ContrailV2VirtualMachineInterfaceHelper().connectVmiToNetwork(this, translateTo, nodeTemplate); connectSubInterfaceToInterface(translateTo, nodeTemplate); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } //connection to shared interface is not supported - private void connectSubInterfaceToInterface(TranslateTo translateTo, - NodeTemplate vlanSubInterfaceNodeTemplate) { + private void connectSubInterfaceToInterface(TranslateTo translateTo, NodeTemplate vlanSubInterfaceNodeTemplate) { Object interfaceRefs = translateTo.getResource().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) - || ((List) interfaceRefs).isEmpty()) { + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) || ((List) interfaceRefs).isEmpty()) { return; } - List acceptableResourceTypes = Arrays - .asList(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); + List acceptableResourceTypes = Arrays.asList(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); if (((List) interfaceRefs).size() > 1) { logger.warn(LOG_MULTIPLE_INTERFACE_VALUES, translateTo.getResourceId(), translateTo.getResource().getType(), - HeatConstants.VMI_REFS_PROPERTY_NAME); + HeatConstants.VMI_REFS_PROPERTY_NAME); } Object interfaceRef = ((List) interfaceRefs).get(0); - Optional interfaceResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(interfaceRef); + Optional interfaceResourceId = HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(interfaceRef); if (interfaceResourceId.isPresent()) { // get_resource - Resource interfaceResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - interfaceResourceId.get(), translateTo.getHeatFileName()); - - if (acceptableResourceTypes.contains(interfaceResource.getType()) - && !(new ContrailV2VirtualMachineInterfaceHelper() - .isVlanSubInterfaceResource(interfaceResource))) { - Optional interfaceResourceTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), - translateTo.getContext()); + Resource interfaceResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), translateTo.getHeatFileName()); + if (acceptableResourceTypes.contains(interfaceResource.getType()) && !(new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(interfaceResource))) { + Optional interfaceResourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), translateTo.getContext()); interfaceResourceTranslatedId.ifPresent(interfaceResourceTranslatedIdVal -> HeatToToscaUtil - .addBindingReqFromSubInterfaceToInterface(vlanSubInterfaceNodeTemplate, - interfaceResourceTranslatedIdVal)); + .addBindingReqFromSubInterfaceToInterface(vlanSubInterfaceNodeTemplate, interfaceResourceTranslatedIdVal)); } else { - logger.warn(LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo - .getResource().getType(), HeatConstants.VMI_REFS_PROPERTY_NAME, - getLogMessage(interfaceResource), interfaceResourceId.get(), interfaceResource.getType()); + logger.warn(LOG_UNSUPPORTED_VLAN_RESOURCE_CONNECTION, translateTo.getResourceId(), translateTo.getResource().getType(), + HeatConstants.VMI_REFS_PROPERTY_NAME, getLogMessage(interfaceResource), interfaceResourceId.get(), interfaceResource.getType()); } } } private String getLogMessage(Resource interfaceResource) { - return (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(interfaceResource)) - ? "Vlan Sub interface " : ""; + return (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(interfaceResource)) ? "Vlan Sub interface " : ""; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java index ebf107a385..6019e9f0b1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.heat.services.HeatConstants; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; @@ -25,74 +26,57 @@ import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.List; -import java.util.Map; - - public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTranslationBase { - private final ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = - new ContrailV2VirtualMachineInterfaceHelper(); + + private final ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper = new ContrailV2VirtualMachineInterfaceHelper(); @Override protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { - if (contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource(translateTo.getResource())) { - return contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceConnectedToPortIndirectly(translateTo); + if (contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(translateTo.getResource())) { + return contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceConnectedToPortIndirectly(translateTo); } return true; } @Override protected void translate(TranslateTo translateTo) { - if (contrailV2VirtualMachineInterfaceHelper - .isVlanSubInterfaceResource(translateTo.getResource())) { + if (contrailV2VirtualMachineInterfaceHelper.isVlanSubInterfaceResource(translateTo.getResource())) { translateVlanSubInterfaceResource(translateTo); } else { translateVirtualMachineInterfaceResource(translateTo); } } - private void translateVirtualMachineInterfaceResource(TranslateTo translateTo) { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - String toscaVmiRefsPropertyName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_REFS_PROPERTY_NAME); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + String toscaVmiRefsPropertyName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_REFS_PROPERTY_NAME); nodeTemplate.getProperties().remove(toscaVmiRefsPropertyName); handleVmiMacAddressesInProperties(translateTo, nodeTemplate); contrailV2VirtualMachineInterfaceHelper.connectVmiToNetwork(this, translateTo, nodeTemplate); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - private void handleVmiMacAddressesInProperties(TranslateTo translateTo, - NodeTemplate nodeTemplate) { - String toscaVmiMacAddressesName = - HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES); + private void handleVmiMacAddressesInProperties(TranslateTo translateTo, NodeTemplate nodeTemplate) { + String toscaVmiMacAddressesName = HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES); String toscaVmiMacAddressesMacAddressesName = HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES_MAC_ADDRESSES); + .getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES_MAC_ADDRESSES); if (nodeTemplate.getProperties().containsKey(toscaVmiMacAddressesName)) { Object macAddressesValue = nodeTemplate.getProperties().get(toscaVmiMacAddressesName); - if (macAddressesValue instanceof Map && ((Map) macAddressesValue).containsKey( - toscaVmiMacAddressesMacAddressesName)) { - updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, - toscaVmiMacAddressesMacAddressesName, (Map) macAddressesValue); + if (macAddressesValue instanceof Map && ((Map) macAddressesValue).containsKey(toscaVmiMacAddressesMacAddressesName)) { + updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, toscaVmiMacAddressesMacAddressesName, + (Map) macAddressesValue); } } } - private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, - String toscaVmiMacAddressesName, - String toscaVmiMacAddressesMacAddressesName, - Map macAddressesValue) { - Object macAddressesMacAddressesValue = - macAddressesValue.get(toscaVmiMacAddressesMacAddressesName); + private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, String toscaVmiMacAddressesName, + String toscaVmiMacAddressesMacAddressesName, Map macAddressesValue) { + Object macAddressesMacAddressesValue = macAddressesValue.get(toscaVmiMacAddressesMacAddressesName); if (macAddressesMacAddressesValue instanceof List) { nodeTemplate.getProperties().put(toscaVmiMacAddressesName, macAddressesMacAddressesValue); } else { @@ -103,5 +87,4 @@ public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTransl private void translateVlanSubInterfaceResource(TranslateTo translateTo) { new ResourceTranslationContrailV2VlanSubInterfaceImpl().translate(translateTo); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java index 0dea8b7172..6523f8092d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -29,11 +28,9 @@ public class ResourceTranslationContrailVirtualNetworkImpl extends ResourceTrans NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.CONTRAIL_VIRTUAL_NETWORK); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java index f5571c9804..05b5a6b87e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java @@ -13,21 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.Optional; import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import java.util.Optional; - public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { @Override public void translate(TranslateTo translateTo) { //no translation is needed, this default is used for unsupported resources - logger.warn("Heat resource: '{}' with type: '{}' is not supported, will be ignored in TOSCA translation", - translateTo.getResourceId(), translateTo.getResource().getType()); + logger.warn("Heat resource: '{}' with type: '{}' is not supported, will be ignored in TOSCA translation", translateTo.getResourceId(), + translateTo.getResource().getType()); } @Override @@ -36,9 +34,7 @@ public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { } @Override - protected Optional getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional getTranslatedToscaTopologyElement(TranslateTo translateTo) { return Optional.empty(); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java index c6c444c135..063cbf40a6 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -42,10 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.TranslationService; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class ResourceTranslationNestedImpl extends ResourceTranslationBase { private static final String SUB_INTERFACE_COUNT = "count"; @@ -56,8 +54,8 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { TranslationContext context = translateTo.getContext(); FileData nestedFileData = HeatToToscaUtil.getFileData(translateTo.getResource().getType(), context); if (nestedFileData == null) { - log.warn("Nested File '{}' is not exist, therefore, the nested resource with the ID '{}' will be ignored " - + "in TOSCA translation", translateTo.getResource().getType(), translateTo.getResourceId()); + log.warn("Nested File '{}' is not exist, therefore, the nested resource with the ID '{}' will be ignored " + "in TOSCA translation", + translateTo.getResource().getType(), translateTo.getResourceId()); return; } String templateName = FileUtils.getFileWithoutExtention(translateTo.getResource().getType()); @@ -65,18 +63,15 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { if (!context.getTranslatedServiceTemplates().containsKey(translateTo.getResource().getType())) { translateNestedHeat(translateTo, nestedFileData, templateName, substitutionNodeTypeKey); } - ServiceTemplate substitutionServiceTemplate = context.getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()); + ServiceTemplate substitutionServiceTemplate = context.getTranslatedServiceTemplates().get(translateTo.getResource().getType()); if (DataModelUtil.isNodeTemplateSectionMissingFromServiceTemplate(substitutionServiceTemplate)) { handleSubstitutionServiceTemplateWithoutNodeTemplates(templateName, translateTo); return; } - NodeTemplate substitutionNodeTemplate = HeatToToscaUtil.createAbstractSubstitutionNodeTemplate(translateTo, - templateName, substitutionNodeTypeKey); - manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, substitutionNodeTemplate, - substitutionNodeTypeKey); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - substitutionNodeTemplate); + NodeTemplate substitutionNodeTemplate = HeatToToscaUtil + .createAbstractSubstitutionNodeTemplate(translateTo, templateName, substitutionNodeTypeKey); + manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, substitutionNodeTemplate, substitutionNodeTypeKey); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), substitutionNodeTemplate); //Add nested node template id to consolidation data ConsolidationDataUtil.updateNestedNodeTemplateId(translateTo); //Gather consolidation data if the resource group represents a sub interface @@ -86,69 +81,48 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { } private boolean isResourceGroupSubInterface(String substitutionNodeTypeKey) { - return StringUtils.isNotBlank(substitutionNodeTypeKey) - && substitutionNodeTypeKey.contains(ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX); + return StringUtils.isNotBlank(substitutionNodeTypeKey) && substitutionNodeTypeKey + .contains(ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX); } - private void translateNestedHeat(TranslateTo translateTo, FileData nestedFileData, String templateName, - String substitutionNodeTypeKey) { + private void translateNestedHeat(TranslateTo translateTo, FileData nestedFileData, String templateName, String substitutionNodeTypeKey) { TranslationContext context = translateTo.getContext(); //substitution service template - ServiceTemplate nestedSubstitutionServiceTemplate = - createSubstitutionServiceTemplate(translateTo, nestedFileData, templateName); + ServiceTemplate nestedSubstitutionServiceTemplate = createSubstitutionServiceTemplate(translateTo, nestedFileData, templateName); //global substitution service template ServiceTemplate globalSubstitutionServiceTemplate = HeatToToscaUtil - .fetchGlobalSubstitutionServiceTemplate(translateTo.getServiceTemplate(), context); + .fetchGlobalSubstitutionServiceTemplate(translateTo.getServiceTemplate(), context); //substitution node type NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() - .createInitSubstitutionNodeType(nestedSubstitutionServiceTemplate, ToscaNodeType.ABSTRACT_SUBSTITUTE); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, - substitutionNodeType); + .createInitSubstitutionNodeType(nestedSubstitutionServiceTemplate, ToscaNodeType.ABSTRACT_SUBSTITUTE); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, substitutionNodeType); //substitution mapping - HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeKey, - nestedSubstitutionServiceTemplate, substitutionNodeType); + HeatToToscaUtil.handleSubstitutionMapping(context, substitutionNodeTypeKey, nestedSubstitutionServiceTemplate, substitutionNodeType); //add new nested service template - context.getTranslatedServiceTemplates().put(translateTo.getResource().getType(), - nestedSubstitutionServiceTemplate); + context.getTranslatedServiceTemplates().put(translateTo.getResource().getType(), nestedSubstitutionServiceTemplate); } - private void populateSubInterfaceTemplateConsolidationData(TranslateTo translateTo, - NodeTemplate nodeTemplate) { - - SubInterfaceConsolidationDataHandler consolidationDataHandler = - translateTo.getContext().getSubInterfaceConsolidationDataHandler(); - + private void populateSubInterfaceTemplateConsolidationData(TranslateTo translateTo, NodeTemplate nodeTemplate) { + SubInterfaceConsolidationDataHandler consolidationDataHandler = translateTo.getContext().getSubInterfaceConsolidationDataHandler(); String translatedId = translateTo.getTranslatedId(); - Optional subInterfaceNetworkRole = - HeatToToscaUtil.getNetworkRoleFromSubInterfaceId(translateTo.getResource(), translateTo.getContext()); - subInterfaceNetworkRole.ifPresent(networkRole -> consolidationDataHandler.setNetworkRole(translateTo, - translatedId, networkRole)); - - consolidationDataHandler.setResourceGroupCount(translateTo, translatedId, - getSubInterfaceCountFromResourceProperties(translateTo)); - + Optional subInterfaceNetworkRole = HeatToToscaUtil + .getNetworkRoleFromSubInterfaceId(translateTo.getResource(), translateTo.getContext()); + subInterfaceNetworkRole.ifPresent(networkRole -> consolidationDataHandler.setNetworkRole(translateTo, translatedId, networkRole)); + consolidationDataHandler.setResourceGroupCount(translateTo, translatedId, getSubInterfaceCountFromResourceProperties(translateTo)); if (CollectionUtils.isEmpty(nodeTemplate.getRequirements())) { return; } //Add connectivity to network in consolidation data based on resource group link requirements - nodeTemplate.getRequirements().forEach((Map requirementMap) -> - requirementMap.entrySet().stream() - .filter(requirementAssignmentEntry -> ToscaCapabilityType.NATIVE_NETWORK_LINKABLE - .equals(requirementAssignmentEntry.getValue().getCapability())) - .forEach(requirementAssignmentEntry -> - consolidationDataHandler.addNodesConnectedOut(translateTo, - requirementAssignmentEntry.getValue().getNode(), - requirementAssignmentEntry.getKey(), - requirementAssignmentEntry.getValue()) - ) - ); + nodeTemplate.getRequirements().forEach((Map requirementMap) -> requirementMap.entrySet().stream().filter( + requirementAssignmentEntry -> ToscaCapabilityType.NATIVE_NETWORK_LINKABLE.equals(requirementAssignmentEntry.getValue().getCapability())) + .forEach(requirementAssignmentEntry -> consolidationDataHandler + .addNodesConnectedOut(translateTo, requirementAssignmentEntry.getValue().getNode(), requirementAssignmentEntry.getKey(), + requirementAssignmentEntry.getValue()))); } private Object getSubInterfaceCountFromResourceProperties(TranslateTo translateTo) { - if (Objects.nonNull(translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo - .getResourceId()))) { - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo - .getResourceId()); + if (Objects.nonNull(translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo.getResourceId()))) { + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources().get(translateTo.getResourceId()); if (HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource().equals(resource.getType())) { return resource.getProperties().get(SUB_INTERFACE_COUNT); } else if (HeatToToscaUtil.isYamlFile(resource.getType())) { @@ -158,102 +132,69 @@ public class ResourceTranslationNestedImpl extends ResourceTranslationBase { return null; } - private void handleSubstitutionServiceTemplateWithoutNodeTemplates(String templateName, - TranslateTo translateTo) { + private void handleSubstitutionServiceTemplateWithoutNodeTemplates(String templateName, TranslateTo translateTo) { translateTo.getContext().addServiceTemplateWithoutNodeTemplates(templateName); - translateTo.getContext() - .addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(translateTo.getTranslatedId()); + translateTo.getContext().addNestedNodeTemplateIdPointsToStWithoutNodeTemplates(translateTo.getTranslatedId()); translateTo.getContext().getTranslatedServiceTemplates().remove(translateTo.getResource().getType()); } - private ServiceTemplate createSubstitutionServiceTemplate(TranslateTo translateTo, - FileData nestedFileData, - String templateName) { - ServiceTemplate nestedSubstitutionServiceTemplate = - HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); - translateTo.getContext().addNestedHeatFileName(ToscaUtil.getServiceTemplateFileName(templateName), - translateTo.getResource().getType()); - new TranslationService().translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, translateTo - .getContext()); + private ServiceTemplate createSubstitutionServiceTemplate(TranslateTo translateTo, FileData nestedFileData, String templateName) { + ServiceTemplate nestedSubstitutionServiceTemplate = HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + translateTo.getContext().addNestedHeatFileName(ToscaUtil.getServiceTemplateFileName(templateName), translateTo.getResource().getType()); + new TranslationService().translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, translateTo.getContext()); return nestedSubstitutionServiceTemplate; } - - private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - String substitutionNodeTypeId) { - ServiceTemplate globalSubstitutionTemplate = - translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, String substitutionNodeTypeId) { + ServiceTemplate globalSubstitutionTemplate = translateTo.getContext().getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); NodeType nodeType = globalSubstitutionTemplate.getNode_types().get(substitutionNodeTypeId); handlePortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); handleNovaToVolConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); - handleContrailPortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - handleVlanSubInterfaceToInterfaceConnections(translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleContrailPortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleVlanSubInterfaceToInterfaceConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } - private void handleVlanSubInterfaceToInterfaceConnections(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleVlanSubInterfaceToInterfaceConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - ContrailV2VlanToInterfaceResourceConnection linker = - new ContrailV2VlanToInterfaceResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + ContrailV2VlanToInterfaceResourceConnection linker = new ContrailV2VlanToInterfaceResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - - private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - ContrailV2VmInterfaceToNetResourceConnection linker = - new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + ContrailV2VmInterfaceToNetResourceConnection linker = new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - NovaToVolResourceConnection linker = - new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + NovaToVolResourceConnection linker = new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleSecurityRulesToPortConnections(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleSecurityRulesToPortConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - SecurityRulesToPortResourceConnection linker = - new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + SecurityRulesToPortResourceConnection linker = new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - PortToNetResourceConnection linker = - new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + PortToNetResourceConnection linker = new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); linker.connect(); } - private void handleContrailPortToNetConnections(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, + private void handleContrailPortToNetConnections(TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - ContrailPortToNetResourceConnection linker = - new ContrailPortToNetResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); + ContrailPortToNetResourceConnection linker = new ContrailPortToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); linker.connect(); } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java index 3fc05f43a1..798ed46d33 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -24,7 +23,6 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { @Override @@ -32,22 +30,13 @@ public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_NET); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.PORT_SECURITY_ENABLED_PROPERTY_NAME)); - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.SHARED_PROPERTY_NAME)); - HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.ADMIN_STATE_UP_PROPERTY_NAME)); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + HeatToToscaUtil + .mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.PORT_SECURITY_ENABLED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.SHARED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.ADMIN_STATE_UP_PROPERTY_NAME)); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java index ee5097eb7a..939a5306ac 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java @@ -13,10 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.SECURITY_GROUPS_PROPERTY_NAME; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION; + import com.google.common.collect.ImmutableList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -37,12 +44,6 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.helper.ResourceTranslationNeutronPortHelper; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.*; - -import static org.openecomp.sdc.translator.services.heattotosca.Constants.SECURITY_GROUPS_PROPERTY_NAME; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION; - - public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase { @Override @@ -50,17 +51,13 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_PORT); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - new ResourceTranslationNeutronPortHelper().setAdditionalProperties(nodeTemplate - .getProperties()); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + new ResourceTranslationNeutronPortHelper().setAdditionalProperties(nodeTemplate.getProperties()); handleNetworkRequirement(translateTo, nodeTemplate); String resourceTranslatedId = handleSecurityRulesRequirement(translateTo); - DataModelUtil - .addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); } private String handleSecurityRulesRequirement(TranslateTo translateTo) { @@ -71,19 +68,18 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase List securityGroupsList = (List) securityGroups.get(); securityGroupsList.forEach(resourceValue -> { Optional securityGroupResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), resourceValue); - securityGroupResourceId.ifPresent(attachedResourceId -> handleSecurityGroupResourceId(translateTo, - resourceTranslatedId, attachedResourceId)); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + resourceValue); + securityGroupResourceId + .ifPresent(attachedResourceId -> handleSecurityGroupResourceId(translateTo, resourceTranslatedId, attachedResourceId)); }); } return resourceTranslatedId; } - private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId) { + private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId) { List supportedSecurityGroupsTypes = Collections - .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); if (securityGroupResourceId.isGetResource()) { handleGetResource(translateTo, resourceTranslatedId, securityGroupResourceId, supportedSecurityGroupsTypes); } else if (securityGroupResourceId.isGetParam()) { @@ -91,77 +87,64 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, + private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId, List supportedSecurityGroupsTypes) { if (!(securityGroupResourceId.getEntityId() instanceof String)) { return; } - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam().get(securityGroupResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - translatedSharedResourceId.getHeatResource(), SECURITY_GROUPS_PROPERTY_NAME)) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(securityGroupResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, translatedSharedResourceId.getHeatResource(), + SECURITY_GROUPS_PROPERTY_NAME)) { return; } final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - translatedSharedResourceId.getTranslatedId()); + .getNodeTemplate(translateTo.getServiceTemplate(), translatedSharedResourceId.getTranslatedId()); RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirement.setNode(resourceTranslatedId); requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); - DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, translatedSharedResourceId.getTranslatedId(), - ConsolidationEntityType.PORT, translateTo.getResourceId(), - ToscaConstants.PORT_REQUIREMENT_ID, requirement); + DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, requirement); + ConsolidationDataUtil.updateNodesConnectedIn(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + translateTo.getResourceId(), ToscaConstants.PORT_REQUIREMENT_ID, requirement); } } - private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, + private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, AttachedResourceId securityGroupResourceId, List supportedSecurityGroupsTypes) { String resourceId = (String) securityGroupResourceId.getEntityId(); - Resource securityGroupResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - resourceId, translateTo.getHeatFileName()); + Resource securityGroupResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceId, translateTo.getHeatFileName()); Optional securityGroupTranslatedId = ResourceTranslationFactory.getInstance(securityGroupResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), securityGroupResource, resourceId, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + securityGroupResource, resourceId, translateTo.getContext()); if (!securityGroupTranslatedId.isPresent()) { return; } - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - securityGroupResource, SECURITY_GROUPS_PROPERTY_NAME)) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, securityGroupResource, + SECURITY_GROUPS_PROPERTY_NAME)) { return; } final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); + .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); RequirementAssignment requirement = new RequirementAssignment(); requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirement.setNode(resourceTranslatedId); requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); - DataModelUtil - .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - - ConsolidationDataUtil.updateNodesConnectedIn(translateTo, securityGroupTranslatedId.get(), - ConsolidationEntityType.PORT, translateTo.getResourceId(), + DataModelUtil.addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, requirement); + ConsolidationDataUtil + .updateNodesConnectedIn(translateTo, securityGroupTranslatedId.get(), ConsolidationEntityType.PORT, translateTo.getResourceId(), ToscaConstants.PORT_REQUIREMENT_ID, requirement); } private void handleNetworkRequirement(TranslateTo translateTo, NodeTemplate nodeTemplate) { - Optional networkResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); + Optional networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); if (networkResourceId.isPresent()) { AttachedResourceId attachedResourceId = networkResourceId.get(); addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); } else { - networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants - .NETWORK_ID_PROPERTY_NAME); + networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); if (networkResourceId.isPresent()) { AttachedResourceId attachedResourceId = networkResourceId.get(); addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); @@ -169,8 +152,7 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, - NodeTemplate nodeTemplate, + private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { if (attachedResourceId.isGetResource()) { addLinkRequirementForGetResource(translateTo, nodeTemplate, attachedResourceId); @@ -179,60 +161,49 @@ public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase } } - private void addLinkRequirementForGetParam(TranslateTo translateTo, NodeTemplate nodeTemplate, - AttachedResourceId attachedResourceId) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam().get(attachedResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + private void addLinkRequirementForGetParam(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { + TranslatedHeatResource translatedSharedResourceId = translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), - translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { + translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { return; } - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - nodeTemplate, translatedSharedResourceId.getTranslatedId()); - - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, - translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, - ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + RequirementAssignment requirementAssignment = HeatToToscaUtil + .addLinkReqFromPortToNetwork(nodeTemplate, translatedSharedResourceId.getTranslatedId()); + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); } } - private void addLinkRequirementForGetResource(TranslateTo translateTo, NodeTemplate nodeTemplate, - AttachedResourceId attachedResourceId) { + private void addLinkRequirementForGetResource(TranslateTo translateTo, NodeTemplate nodeTemplate, AttachedResourceId attachedResourceId) { String networkTranslatedId; - Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate() - .getResources().get(attachedResourceId.getEntityId()); - if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), - networkHeatResource, "network'\\'network_id")) { + Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate().getResources().get(attachedResourceId.getEntityId()); + if (validateResourceTypeSupportedForReqCreation(translateTo, getSupportedNetworkResourceTypes(), networkHeatResource, + "network'\\'network_id")) { return; } networkTranslatedId = (String) attachedResourceId.getTranslatedId(); - RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( - nodeTemplate, networkTranslatedId); - - ConsolidationDataUtil.updateNodesConnectedOut(translateTo, networkTranslatedId, - ConsolidationEntityType.PORT, ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork(nodeTemplate, networkTranslatedId); + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, networkTranslatedId, ConsolidationEntityType.PORT, ToscaConstants.LINK_REQUIREMENT_ID, + requirementAssignment); } - - private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, - List supportedTypes, - Resource heatResource, + private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, List supportedTypes, Resource heatResource, final String propertyName) { if (isUnsupportedResourceType(heatResource, supportedTypes)) { String supportedResourceTypes = supportedTypes.toString(); - logger.warn(LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION, propertyName, translateTo - .getResourceId(), heatResource.getType(), supportedResourceTypes); + logger.warn(LOG_UNSUPPORTED_RESOURCE_REQUIREMENT_CONNECTION, propertyName, translateTo.getResourceId(), heatResource.getType(), + supportedResourceTypes); return true; } return false; } - private List getSupportedNetworkResourceTypes() { return ImmutableList.of(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java index 060544fd1b..35f274e023 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -22,7 +21,6 @@ import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTranslationBase { @Override @@ -30,15 +28,9 @@ public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTransla NodeTemplate nodeTemplate = new NodeTemplate(); nodeTemplate.setType(ToscaNodeType.NEUTRON_SECURITY_RULES); nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), nodeTemplate); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java index 7dedc6b9cf..37d39aa046 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; import org.onap.sdc.tosca.datatypes.model.PropertyType; @@ -35,10 +37,6 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBase { private static final Logger logger = LoggerFactory.getLogger(ResourceTranslationNeutronSubnetImpl.class); @@ -50,47 +48,39 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas if (!subnetNetwork.get().isGetResource()) { return; } - Resource networkResource = HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), - (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); Optional translatedNetworkId = ResourceTranslationFactory.getInstance(networkResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), networkResource, - (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + networkResource, (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); if (!translatedNetworkId.isPresent()) { return; } - NodeTemplate networkNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), - translatedNetworkId.get()); - Map> subNetMap = (Map>) networkNodeTemplate - .getProperties().get(HeatConstants.SUBNETS_PROPERTY_NAME); + NodeTemplate networkNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), translatedNetworkId.get()); + Map> subNetMap = (Map>) networkNodeTemplate.getProperties() + .get(HeatConstants.SUBNETS_PROPERTY_NAME); if (subNetMap == null) { subNetMap = addSubnetProperties(translateTo, networkNodeTemplate); } Map properties = TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), null, translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); subNetMap.put(translateTo.getResourceId(), properties); } - private Map> addSubnetProperties(TranslateTo translateTo, - NodeTemplate networkNodeTemplate) { + private Map> addSubnetProperties(TranslateTo translateTo, NodeTemplate networkNodeTemplate) { Map> subNetMap = new HashMap<>(); networkNodeTemplate.getProperties().put(HeatConstants.SUBNETS_PROPERTY_NAME, subNetMap); TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), HeatConstants.ENABLE_DHCP_PROPERTY_NAME, - ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled + .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getContext(), networkNodeTemplate.getProperties(), HeatConstants.ENABLE_DHCP_PROPERTY_NAME, + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), IP_VERSION_PROPERTY_NAME, null, networkNodeTemplate); + .setSimpleProperty(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getContext(), networkNodeTemplate.getProperties(), IP_VERSION_PROPERTY_NAME, null, networkNodeTemplate); handleDhcpProperty(translateTo, networkNodeTemplate); return subNetMap; } @@ -100,8 +90,8 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas Optional subnetNetwork = getAttachedNetworkResource(translateTo); if (!subnetNetwork.get().isGetResource()) { logger.warn("Heat resource: '{}' with type: '{}' include 'network_id/'network'' property without " - + "'get_resource' function, therefore this resource will be ignored in TOSCA translation.", - translateTo.getResourceId(), translateTo.getResource().getType()); + + "'get_resource' function, therefore this resource will be ignored in TOSCA translation.", translateTo.getResourceId(), + translateTo.getResource().getType()); return null; } return (String) subnetNetwork.get().getTranslatedId(); @@ -118,8 +108,7 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas } ParameterDefinition dhcpParameterDefinition = null; if (translateTo.getServiceTemplate().getTopology_template().getInputs() != null) { - dhcpParameterDefinition = - translateTo.getServiceTemplate().getTopology_template().getInputs().get(dhcpEnabledParameterName); + dhcpParameterDefinition = translateTo.getServiceTemplate().getTopology_template().getInputs().get(dhcpEnabledParameterName); } if (dhcpParameterDefinition == null) { logger.warn("Missing input parameter : {} ", dhcpEnabledParameterName); @@ -134,29 +123,24 @@ public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBas } catch (CoreException coreException) { dhcpParameterDefinition.set_default(true); logger.warn("Parameter '{}' used for {} boolean property, but it's value is not a valid boolean " - + "value, therefore {} property will be set with default value of 'true'.", - dhcpEnabledParameterName, ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, ToscaConstants - .DHCP_ENABLED_PROPERTY_NAME, coreException); + + "value, therefore {} property will be set with default value of 'true'.", dhcpEnabledParameterName, + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, coreException); } dhcpParameterDefinition.setType(PropertyType.BOOLEAN.getDisplayName()); } } private Optional getAttachedNetworkResource(TranslateTo translateTo) { - Optional attachedNetworkId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); + Optional attachedNetworkId = HeatToToscaUtil + .extractAttachedResourceId(translateTo, HeatConstants.NETWORK_ID_PROPERTY_NAME); if (attachedNetworkId.isPresent()) { return attachedNetworkId; } - Optional attachedNetwork = - HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); + Optional attachedNetwork = HeatToToscaUtil.extractAttachedResourceId(translateTo, HeatConstants.NETWORK_PROPERTY_NAME); if (attachedNetwork.isPresent()) { return attachedNetwork; } throw new CoreException( - new MissingMandatoryPropertyErrorBuilder(HeatConstants.NETWORK_ID_PROPERTY_NAME + "/" - + HeatConstants.NETWORK_PROPERTY_NAME).build()); + new MissingMandatoryPropertyErrorBuilder(HeatConstants.NETWORK_ID_PROPERTY_NAME + "/" + HeatConstants.NETWORK_PROPERTY_NAME).build()); } } - - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java index ccd02955cd..1ad038f718 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import java.util.ArrayList; @@ -23,7 +22,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.GroupDefinition; import org.onap.sdc.tosca.datatypes.model.PolicyDefinition; @@ -37,14 +35,14 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase { + private static final String AFFINITY = "affinity"; private static final String ANTI_AFFINITY = "anti-affinity"; private static final List supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY); @Override protected String generateTranslatedId(TranslateTo translateTo) { - return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId( - translateTo.getResourceId()) : null; + return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId(translateTo.getResourceId()) : null; } @Override @@ -53,8 +51,7 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation } @Override - protected Optional getTranslatedToscaTopologyElement( - TranslateTo translateTo) { + protected Optional getTranslatedToscaTopologyElement(TranslateTo translateTo) { if (isEssentialRequirementsValid(translateTo)) { return Optional.of(ToscaTopologyTemplateElements.GROUP); } else { @@ -64,16 +61,13 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation private boolean validatePolicyType(TranslateTo translateTo) { Map properties = translateTo.getResource().getProperties(); - if (Objects.isNull(properties) - || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { + if (Objects.isNull(properties) || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { return true; } - Object policies = properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME); if (!(policies instanceof List)) { return false; } - for (Object policy : (List) policies) { if (!isValidPolicyType(policy, translateTo.getResourceId(), translateTo.getResource())) { return false; @@ -86,14 +80,12 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation if (!(policy instanceof String)) { return false; } - if (!supportedPolicies.contains(policy)) { String unsupportedPolicy = policy.toString(); - logger.warn("Resource '{}'({}) contains unsupported policy '{}'. This resource is been ignored during " - + "the translation", resourceId, resource.getType(), unsupportedPolicy); + logger.warn("Resource '{}'({}) contains unsupported policy '{}'. This resource is been ignored during " + "the translation", resourceId, + resource.getType(), unsupportedPolicy); return false; } - return true; } @@ -107,10 +99,8 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation } } - private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId, - List toscaPolicyTypes) { - logger.info("******** Start creating policies for resource '%s' ********", - translateTo.getResourceId()); + private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId, List toscaPolicyTypes) { + logger.info("******** Start creating policies for resource '%s' ********", translateTo.getResourceId()); for (int i = 0; i < toscaPolicyTypes.size(); i++) { String policy = toscaPolicyTypes.get(i); logger.info("******** Creating policy '%s' ********", policy); @@ -118,29 +108,19 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation policyDefinition.setType(policy); policyDefinition.setTargets(Collections.singletonList(policyTargetEntityId)); policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), - translateTo.getResourceId(), translateTo.getResource().getProperties(), - policyDefinition.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - policyDefinition, translateTo.getContext())); - policyDefinition.getProperties().put( - policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type" - : AFFINITY, "host"); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), + translateTo.getResource().getProperties(), policyDefinition.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), policyDefinition, translateTo.getContext())); + policyDefinition.getProperties().put(policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type" : AFFINITY, "host"); String policyId = getTranslatedPolicyId(translateTo, toscaPolicyTypes, i); - DataModelUtil - .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); + DataModelUtil.addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); logger.info("******** Policy '%s' created ********", policy); } - - logger - .info("******** All policies for resource '%s' created successfully ********", - translateTo.getResourceId()); + logger.info("******** All policies for resource '%s' created successfully ********", translateTo.getResourceId()); } - private String getTranslatedPolicyId(TranslateTo translateTo, List toscaPolicyTypes, - int policyIndex) { - return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "") - + "_policy"; + private String getTranslatedPolicyId(TranslateTo translateTo, List toscaPolicyTypes, int policyIndex) { + return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "") + "_policy"; } private String addGroupToTopology(TranslateTo translateTo, String resourceId) { @@ -149,9 +129,7 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation group.setMembers(new ArrayList<>()); group.setType(ToscaGroupType.NATIVE_ROOT); String translatedGroupId = getTranslatedGroupId(resourceId); - DataModelUtil - .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), - translatedGroupId, group); + DataModelUtil.addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), translatedGroupId, group); logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId); return translatedGroupId; } @@ -162,11 +140,9 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation private List getToscaPolicies(Resource resource, String resourceId) { Map properties = resource.getProperties(); - if (Objects.isNull(properties) - || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { + if (Objects.isNull(properties) || Objects.isNull(properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME))) { return Collections.singletonList(ToscaPolicyType.PLACEMENT_ANTILOCATE); } - List policies = (List) properties.get(HeatConstants.SERVER_GROUP_POLICIES_PROPERTY_NAME); List retList = new ArrayList<>(); policies.forEach(policy -> { @@ -184,5 +160,4 @@ public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslation return ToscaPolicyType.PLACEMENT_ANTILOCATE; } } - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java index 71dfeb9f53..a934f00aa0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.heat.services.HeatConstants.SNAPSHOT_ID_PROPERTY_NAME; @@ -27,16 +26,15 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.onap.sdc.tosca.datatypes.model.GroupDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; import org.onap.sdc.tosca.datatypes.model.RelationshipTemplate; import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; -import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -66,11 +64,11 @@ import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFact import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { + private static final Logger logger = LoggerFactory.getLogger(ResourceTranslationNovaServerImpl.class); private static final String BLOCK_DEVICE_MAPPING_DEVICE_NAME = "device_name"; private static final String VOL_ATTACH_DEVICE_PROPERTY_NAME = "device"; private static final String FABRIC_CONFIGURATION_KEY = "fabric_configuration_monitoring"; - @Override protected void translate(TranslateTo translateTo) { @@ -78,52 +76,39 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { Map properties = translateTo.getResource().getProperties(); String heatFileName = translateTo.getHeatFileName(); ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - String nodeTypeRef = createLocalNodeType(serviceTemplate, translateTo.getResource(), - translateTo.getResourceId(), translateTo.getTranslatedId()); + String nodeTypeRef = createLocalNodeType(serviceTemplate, translateTo.getResource(), translateTo.getResourceId(), + translateTo.getTranslatedId()); String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); - - context.getComputeConsolidationDataHandler().addConsolidationData( - serviceTemplateFileName, nodeTypeRef, translateTo.getTranslatedId()); - + context.getComputeConsolidationDataHandler().addConsolidationData(serviceTemplateFileName, nodeTypeRef, translateTo.getTranslatedId()); NodeTemplate novaNodeTemplate = new NodeTemplate(); novaNodeTemplate.setType(nodeTypeRef); - HeatOrchestrationTemplate heatOrchestrationTemplate = - translateTo.getHeatOrchestrationTemplate(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); novaNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(serviceTemplate, translateTo.getResourceId(), - properties, novaNodeTemplate.getProperties(), heatFileName, - heatOrchestrationTemplate, translateTo.getResource().getType(), - novaNodeTemplate, context)); - HeatToToscaUtil.mapBoolean(novaNodeTemplate, HeatToToscaUtil - .getToscaPropertyName(translateTo, HeatConstants.CONFIG_DRIVE_PROPERTY_NAME)); + .getToscaPropertiesSimpleConversion(serviceTemplate, translateTo.getResourceId(), properties, novaNodeTemplate.getProperties(), + heatFileName, heatOrchestrationTemplate, translateTo.getResource().getType(), novaNodeTemplate, context)); + HeatToToscaUtil.mapBoolean(novaNodeTemplate, HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.CONFIG_DRIVE_PROPERTY_NAME)); manageNovaServerNetwork(translateTo, novaNodeTemplate); manageNovaServerBlockDeviceMapping(translateTo, novaNodeTemplate); manageNovaServerGroupMapping(translateTo, novaNodeTemplate); DataModelUtil.addNodeTemplate(serviceTemplate, translateTo.getTranslatedId(), novaNodeTemplate); } - private void manageNovaServerGroupMapping(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerGroupMapping(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Map properties = translateTo.getResource().getProperties(); if (isSchedulerHintsPropExist(properties)) { Object schedulerHints = properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); if (schedulerHints instanceof Map) { - addServerGroupHintsToPoliciesGroups(translateTo, - novaNodeTemplate, (Map) schedulerHints); + addServerGroupHintsToPoliciesGroups(translateTo, novaNodeTemplate, (Map) schedulerHints); } else { - logger.warn("'scheduler_hints' property of resource '{}' is not valid. This property should be a map", - translateTo.getResourceId()); + logger.warn("'scheduler_hints' property of resource '{}' is not valid. This property should be a map", translateTo.getResourceId()); } } } - private void addServerGroupHintsToPoliciesGroups(TranslateTo translateTo, - NodeTemplate novaNodeTemplate, - Map schedulerHints) { + private void addServerGroupHintsToPoliciesGroups(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Map schedulerHints) { for (Object hint : schedulerHints.values()) { Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo - .getHeatOrchestrationTemplate(), translateTo.getContext(), hint); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), hint); if (attachedResourceId.isPresent()) { AttachedResourceId serverGroupResourceId = attachedResourceId.get(); Object serverGroupResourceToTranslate = serverGroupResourceId.getEntityId(); @@ -136,77 +121,59 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } } - private void addServerGroupHintGetParam(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object serverGroupResourceToTranslate) { - TranslatedHeatResource translatedServerGroupResource = translateTo.getContext() - .getHeatSharedResourcesByParam().get(serverGroupResourceToTranslate); - if (Objects.nonNull(translatedServerGroupResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) - && isResourceTypeServerGroup(translatedServerGroupResource)) { - Map groups = - translateTo.getServiceTemplate().getTopology_template().getGroups(); - if (MapUtils.isNotEmpty(groups) && Objects.nonNull(groups.get(translatedServerGroupResource - .getTranslatedId()))) { - groups.get(translatedServerGroupResource.getTranslatedId()).getMembers() - .add(translateTo.getTranslatedId()); + private void addServerGroupHintGetParam(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object serverGroupResourceToTranslate) { + TranslatedHeatResource translatedServerGroupResource = translateTo.getContext().getHeatSharedResourcesByParam() + .get(serverGroupResourceToTranslate); + if (Objects.nonNull(translatedServerGroupResource) && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) + && isResourceTypeServerGroup(translatedServerGroupResource)) { + Map groups = translateTo.getServiceTemplate().getTopology_template().getGroups(); + if (MapUtils.isNotEmpty(groups) && Objects.nonNull(groups.get(translatedServerGroupResource.getTranslatedId()))) { + groups.get(translatedServerGroupResource.getTranslatedId()).getMembers().add(translateTo.getTranslatedId()); //Add group Id to compute consolidation data - updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, - translatedServerGroupResource.getTranslatedId()); + updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, translatedServerGroupResource.getTranslatedId()); } } } - private void addServerGroupHintGetResource(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object serverGroupResourceToTranslate) { - boolean isHintOfTypeNovaServerGroup = isHintOfTypeNovaServerGroup(translateTo - .getHeatOrchestrationTemplate(), serverGroupResourceToTranslate); + private void addServerGroupHintGetResource(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object serverGroupResourceToTranslate) { + boolean isHintOfTypeNovaServerGroup = isHintOfTypeNovaServerGroup(translateTo.getHeatOrchestrationTemplate(), serverGroupResourceToTranslate); if (isHintOfTypeNovaServerGroup) { addNovaServerToPolicyGroup(translateTo, (String) serverGroupResourceToTranslate, novaNodeTemplate); } } private boolean isResourceTypeServerGroup(TranslatedHeatResource translatedServerGroupResource) { - return translatedServerGroupResource.getHeatResource().getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + return translatedServerGroupResource.getHeatResource().getType().equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); } - private void updateComputeConsolidationDataGroup(TranslateTo translateTo, - NodeTemplate novaNodeTemplate, String groupId) { + private void updateComputeConsolidationDataGroup(TranslateTo translateTo, NodeTemplate novaNodeTemplate, String groupId) { ComputeConsolidationDataHandler handler = translateTo.getContext().getComputeConsolidationDataHandler(); - handler.addGroupIdToConsolidationData(translateTo,novaNodeTemplate.getType(), - translateTo.getTranslatedId(), groupId); + handler.addGroupIdToConsolidationData(translateTo, novaNodeTemplate.getType(), translateTo.getTranslatedId(), groupId); } - private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, - Object resourceToTranslate) { + private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, Object resourceToTranslate) { return heatOrchestrationTemplate.getResources().get(resourceToTranslate).getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); } - private void addNovaServerToPolicyGroup(TranslateTo translateTo, - String resourceToTranslate, - NodeTemplate novaNodeTemplate) { - Resource serverGroup = - HeatToToscaUtil.getResource(translateTo.getHeatOrchestrationTemplate(), resourceToTranslate, - translateTo.getHeatFileName()); + private void addNovaServerToPolicyGroup(TranslateTo translateTo, String resourceToTranslate, NodeTemplate novaNodeTemplate) { + Resource serverGroup = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceToTranslate, translateTo.getHeatFileName()); Optional serverGroupTranslatedId = ResourceTranslationFactory.getInstance(serverGroup) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), serverGroup, resourceToTranslate, - translateTo.getContext()); + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), + serverGroup, resourceToTranslate, translateTo.getContext()); if (serverGroupTranslatedId.isPresent()) { - translateTo.getServiceTemplate().getTopology_template().getGroups().get(serverGroupTranslatedId.get()) - .getMembers().add(translateTo.getTranslatedId()); + translateTo.getServiceTemplate().getTopology_template().getGroups().get(serverGroupTranslatedId.get()).getMembers() + .add(translateTo.getTranslatedId()); updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, serverGroupTranslatedId.get()); } } private boolean isSchedulerHintsPropExist(Map properties) { - return !MapUtils.isEmpty(properties) - && Objects.nonNull(properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction())); + return !MapUtils.isEmpty(properties) && Objects.nonNull(properties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction())); } - private void manageNovaServerBlockDeviceMapping(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerBlockDeviceMapping(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Resource resource = translateTo.getResource(); List> blockDeviceMappingList = getBlockDeviceMappingList(resource); if (CollectionUtils.isEmpty(blockDeviceMappingList)) { @@ -219,20 +186,17 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } private int connectBlockDeviceToNovaServer(TranslateTo translateTo, NodeTemplate novaNodeTemplate, int index, - Map blockDeviceMapping) { + Map blockDeviceMapping) { Object volumeIdObject = blockDeviceMapping.get(VOL_ID_PROPERTY_NAME); Object snapshotIdObject = blockDeviceMapping.get(SNAPSHOT_ID_PROPERTY_NAME); - if (volumeIdObject == null && snapshotIdObject == null) { logger.warn("Resource '{}' has block_device_mapping property with empty/missing volume_id and snapshot_id " - + "properties. Entry number {}, this entry will be ignored in TOSCA translation.", - translateTo.getResourceId(), (index + 1)); + + "properties. Entry number {}, this entry will be ignored in TOSCA translation.", translateTo.getResourceId(), (index + 1)); index++; return index; } if (volumeIdObject == null) { - connectBlockDeviceUsingSnapshotId(translateTo, novaNodeTemplate, snapshotIdObject, index, - blockDeviceMapping); + connectBlockDeviceUsingSnapshotId(translateTo, novaNodeTemplate, snapshotIdObject, index, blockDeviceMapping); } else { connectBlockDeviceUsingVolumeId(translateTo, novaNodeTemplate, volumeIdObject); } @@ -240,72 +204,60 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { return index; } - private void connectBlockDeviceUsingVolumeId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object volumeIdObject) { + private void connectBlockDeviceUsingVolumeId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object volumeIdObject) { Optional attachedVolumeId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), volumeIdObject); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + volumeIdObject); if (attachedVolumeId.isPresent() && attachedVolumeId.get().isGetResource()) { - connectNovaServerToVolume(novaNodeTemplate, (String) attachedVolumeId.get().getTranslatedId(), null, - translateTo); + connectNovaServerToVolume(novaNodeTemplate, (String) attachedVolumeId.get().getTranslatedId(), null, translateTo); } } - private void connectBlockDeviceUsingSnapshotId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, - Object snapshotIdObject, int index, - Map blockDeviceMapping) { + private void connectBlockDeviceUsingSnapshotId(TranslateTo translateTo, NodeTemplate novaNodeTemplate, Object snapshotIdObject, int index, + Map blockDeviceMapping) { String novaServerTranslatedId = translateTo.getTranslatedId(); String volumeResourceId; Optional attachedSnapshotId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getContext(), snapshotIdObject); + .extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + snapshotIdObject); if (attachedSnapshotId.isPresent()) { volumeResourceId = novaServerTranslatedId + "_" + attachedSnapshotId.get().getEntityId(); String deviceName = (String) blockDeviceMapping.get(BLOCK_DEVICE_MAPPING_DEVICE_NAME); String relationshipId = novaServerTranslatedId + "_" + index; - createVolumeAttachesToRelationship(translateTo.getServiceTemplate(), deviceName, novaServerTranslatedId, - volumeResourceId, relationshipId); + createVolumeAttachesToRelationship(translateTo.getServiceTemplate(), deviceName, novaServerTranslatedId, volumeResourceId, + relationshipId); createCinderVolumeNodeTemplate(translateTo, volumeResourceId, blockDeviceMapping); - connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId, - translateTo); + connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId, translateTo); } } - private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, - String relationshipId, TranslateTo translateTo) { + private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, String relationshipId, TranslateTo translateTo) { RequirementAssignment requirementAssignment = new RequirementAssignment(); requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); requirementAssignment.setNode(volumeResourceId); if (relationshipId != null) { requirementAssignment.setRelationship(relationshipId); } else { - requirementAssignment - .setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO); + requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO); } - DataModelUtil.addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, - requirementAssignment); + DataModelUtil.addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); //Add volume consolidation data - ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaNodeTemplate.getType(), - translateTo.getTranslatedId(), ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaNodeTemplate.getType(), translateTo.getTranslatedId(), + ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, requirementAssignment); } - private void createCinderVolumeNodeTemplate(TranslateTo translateTo, - String volumeResourceId, - Map blockDeviceMapping) { + private void createCinderVolumeNodeTemplate(TranslateTo translateTo, String volumeResourceId, Map blockDeviceMapping) { NodeTemplate cinderVolumeNodeTemplate = new NodeTemplate(); cinderVolumeNodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); cinderVolumeNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), - blockDeviceMapping, null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - cinderVolumeNodeTemplate, translateTo.getContext())); + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo.getResourceId(), blockDeviceMapping, null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), cinderVolumeNodeTemplate, translateTo.getContext())); DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), volumeResourceId, cinderVolumeNodeTemplate); } - private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, - String deviceName, String novaServerTranslatedId, - String volumeId, String relationshipId) { + private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, String deviceName, String novaServerTranslatedId, + String volumeId, String relationshipId) { RelationshipTemplate relationshipTemplate = new RelationshipTemplate(); relationshipTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); Map properties = new HashMap<>(); @@ -322,29 +274,23 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { if (Objects.isNull(resource.getProperties())) { return Collections.emptyList(); } - List> blockDeviceMappingList = - (List>) resource.getProperties().get(HeatConstants.BLOCK_DEVICE_MAPPING); - List> blockDeviceMappingV2List = - (List>) resource.getProperties().get(HeatConstants.BLOCK_DEVICE_MAPPING_V2); - + List> blockDeviceMappingList = (List>) resource.getProperties() + .get(HeatConstants.BLOCK_DEVICE_MAPPING); + List> blockDeviceMappingV2List = (List>) resource.getProperties() + .get(HeatConstants.BLOCK_DEVICE_MAPPING_V2); if (blockDeviceMappingList != null && blockDeviceMappingV2List != null) { blockDeviceMappingList.addAll(blockDeviceMappingV2List); - } else if (CollectionUtils.isEmpty(blockDeviceMappingList) - && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { + } else if (CollectionUtils.isEmpty(blockDeviceMappingList) && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { return Collections.emptyList(); - } else { - blockDeviceMappingList = - blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; + blockDeviceMappingList = blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; } return blockDeviceMappingList; } - private void manageNovaServerNetwork(TranslateTo translateTo, - NodeTemplate novaNodeTemplate) { + private void manageNovaServerNetwork(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { Resource resource = translateTo.getResource(); String translatedId = translateTo.getTranslatedId(); - if (resource.getProperties() == null) { return; } @@ -352,30 +298,22 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { if (Objects.isNull(networks) || !(networks instanceof List)) { return; } - List> heatNetworkList = (List>) networks; - - for (Map heatNetwork : heatNetworkList) { - - Optional portResourceOp = getOrTranslatePortTemplate(translateTo, heatNetwork.get( - Constants.PORT_PROPERTY_NAME), translatedId, novaNodeTemplate); + Optional portResourceOp = getOrTranslatePortTemplate(translateTo, heatNetwork.get(Constants.PORT_PROPERTY_NAME), translatedId, + novaNodeTemplate); portResourceOp.ifPresent(portResource -> handleFabricConfiguration(translateTo, novaNodeTemplate.getType(), portResource)); } - - } - - private void handleFabricConfiguration(TranslateTo translateTo, String resourceType, Resource portResource ){ - - Optional valueSpacesProperty = HeatToToscaUtil.getResourceProperty(portResource, HeatConstants.VALUE_SPECS_PROPERTY_NAME); - - valueSpacesProperty.filter(props -> props instanceof Map && MapUtils.isNotEmpty((Map)props)).ifPresent(valueSpecs ->{ - if(valueSpecs instanceof Map && (isAttFabricConfigurationFlagSet((Map)valueSpecs) || isBindingProfileFabricConfigSet((Map)valueSpecs))) { - addFabricConfigurationCapability(translateTo, resourceType); - } - - }); - + } + + private void handleFabricConfiguration(TranslateTo translateTo, String resourceType, Resource portResource) { + Optional valueSpacesProperty = HeatToToscaUtil.getResourceProperty(portResource, HeatConstants.VALUE_SPECS_PROPERTY_NAME); + valueSpacesProperty.filter(props -> props instanceof Map && MapUtils.isNotEmpty((Map) props)).ifPresent(valueSpecs -> { + if (valueSpecs instanceof Map && (isAttFabricConfigurationFlagSet((Map) valueSpecs) || isBindingProfileFabricConfigSet( + (Map) valueSpecs))) { + addFabricConfigurationCapability(translateTo, resourceType); + } + }); } private boolean isValueFoundAndTrue(Object value) { @@ -389,48 +327,44 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private boolean isBindingProfileFabricConfigSet(Map valueSpecs) { Object binding_profile = valueSpecs.get(HeatConstants.VALUE_SPECS_BINDING_PROFILE_PROPERTY_NAME); if (Objects.nonNull(binding_profile) && binding_profile instanceof Map) { - return !MapUtils.isEmpty((Map)binding_profile) - && isValueFoundAndTrue(((Map)binding_profile).get(HeatConstants.VALUE_SPECS_FABRIC_CONFIG_PROPERTY_NAME)); + return !MapUtils.isEmpty((Map) binding_profile) && isValueFoundAndTrue( + ((Map) binding_profile).get(HeatConstants.VALUE_SPECS_FABRIC_CONFIG_PROPERTY_NAME)); } return false; } - - private void addFabricConfigurationCapability(TranslateTo translateTo, String localType){ - + + private void addFabricConfigurationCapability(TranslateTo translateTo, String localType) { ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); Map mapCapabilities = new HashMap<>(); - CapabilityDefinition fabricConfigurationCap = new CapabilityDefinition(); + CapabilityDefinition fabricConfigurationCap = new CapabilityDefinition(); fabricConfigurationCap.setType(ToscaCapabilityType.FABRIC_CONFIGURATION); mapCapabilities.put(FABRIC_CONFIGURATION_KEY, fabricConfigurationCap); - DataModelUtil.addNodeTypeCapabilitiesDef (DataModelUtil.getNodeType(serviceTemplate, localType), mapCapabilities); + DataModelUtil.addNodeTypeCapabilitiesDef(DataModelUtil.getNodeType(serviceTemplate, localType), mapCapabilities); if (logger.isDebugEnabled()) { - logger.debug("New capability of type {} will be added to resource {}", ToscaCapabilityType.FABRIC_CONFIGURATION, translateTo.getResourceId()); + logger.debug("New capability of type {} will be added to resource {}", ToscaCapabilityType.FABRIC_CONFIGURATION, + translateTo.getResourceId()); } } - private Optional getOrTranslatePortTemplate(TranslateTo translateTo, - Object port, - String novaServerResourceId, - NodeTemplate novaNodeTemplate) { + private Optional getOrTranslatePortTemplate(TranslateTo translateTo, Object port, String novaServerResourceId, + NodeTemplate novaNodeTemplate) { String heatFileName = translateTo.getHeatFileName(); HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo.getHeatOrchestrationTemplate(); TranslationContext context = translateTo.getContext(); Optional attachedPortId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); if (!attachedPortId.isPresent() || !attachedPortId.get().isGetResource()) { return Optional.empty(); } String resourceId = (String) attachedPortId.get().getEntityId(); Resource portResource = HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); if (!isSupportedPortResource(portResource)) { - logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type is " - + "not " + "supported, therefore the connection to the port is ignored. " - + "Supported types are: {}, {}", resourceId, portResource.getType(), - HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); + logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type is " + "not " + + "supported, therefore the connection to the port is ignored. " + "Supported types are: {}, {}", resourceId, portResource.getType(), + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()); return Optional.empty(); - } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource().equals(portResource.getType())) { + } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource().equals(portResource.getType())) { Map properties = portResource.getProperties(); if (!MapUtils.isEmpty(properties) && Objects.nonNull(properties.get(HeatConstants.PORT_TUPLE_REFS))) { novaNodeTemplate.getProperties().put(ToscaConstants.CONTRAIL_SERVICE_INSTANCE_IND, true); @@ -438,19 +372,16 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { } ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); Optional translatedPortId = ResourceTranslationFactory.getInstance(portResource) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, - resourceId, context); + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, resourceId, context); if (translatedPortId.isPresent()) { - NodeTemplate portNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); DataModelUtil.addBindingReqFromPortToCompute(novaServerResourceId, portNodeTemplate); // Add ports - ConsolidationDataUtil.updatePortInConsolidationData(translateTo, novaNodeTemplate.getType(), resourceId, - portResource.getType(), translatedPortId.get()); + ConsolidationDataUtil + .updatePortInConsolidationData(translateTo, novaNodeTemplate.getType(), resourceId, portResource.getType(), translatedPortId.get()); } else { logger.warn("NovaServer connect to port resource with id : {} and type : {}. This resource type" - + " is not supported, therefore the connection to the port is ignored.", resourceId, - portResource.getType()); + + " is not supported, therefore the connection to the port is ignored.", resourceId, portResource.getType()); return Optional.empty(); } return Optional.ofNullable(portResource); @@ -458,17 +389,12 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private boolean isSupportedPortResource(Resource portResource) { return Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) - .contains(portResource.getType()); + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()).contains(portResource.getType()); } - - private String createLocalNodeType(ServiceTemplate serviceTemplate, Resource resource, - String resourceId, String translatedId) { + private String createLocalNodeType(ServiceTemplate serviceTemplate, Resource resource, String resourceId, String translatedId) { NameExtractor nodeTypeNameExtractor = TranslationContext.getNameExtractorImpl(resource.getType()); - String nodeTypeName = - nodeTypeNameExtractor.extractNodeTypeName(resource, resourceId, translatedId); - + String nodeTypeName = nodeTypeNameExtractor.extractNodeTypeName(resource, resourceId, translatedId); if (!isNodeTypeCreated(serviceTemplate, nodeTypeName)) { DataModelUtil.addNodeType(serviceTemplate, nodeTypeName, createNodeType()); } @@ -478,26 +404,19 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { /** * Get property Regex matcher list. * - * @return Regex expression per nova resource property, while nova node type name is consider when - * setting the name value. + * @return Regex expression per nova resource property, while nova node type name is consider when setting the name value. */ public List getPropertyRegexMatchersForNovaNodeType() { List propertyRegexMatchers = new ArrayList<>(3); propertyRegexMatchers - .add(new PropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, - Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), - "_image_name")); - propertyRegexMatchers - .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), - "_flavor_name")); + .add(new PropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), "_image_name")); + propertyRegexMatchers.add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), "_flavor_name")); return propertyRegexMatchers; } private boolean isNodeTypeCreated(ServiceTemplate serviceTemplate, String nodeTypeName) { - return !MapUtils.isEmpty(serviceTemplate.getNode_types()) - && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); + return !MapUtils.isEmpty(serviceTemplate.getNode_types()) && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); } private NodeType createNodeType() { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java index 779550e99d..d976434e06 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.heat.services.HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME; @@ -25,7 +24,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; - import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; @@ -48,61 +46,51 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas @Override protected void translate(TranslateTo translateTo) { final String heatFileName = translateTo.getHeatFileName(); - Object resourceDef = - translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + Object resourceDef = translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); Resource nestedResource = new Resource(); Object typeDefinition = ((Map) resourceDef).get(RESOURCE_DEF_TYPE_PROPERTY_NAME); if (!(typeDefinition instanceof String)) { logger.warn("Resource '{}' of type '{}' with resourceDef which is not pointing to nested heat file is not" - + " supported and will be ignored in the translation ", translateTo.getResourceId(), - HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); + + " supported and will be ignored in the translation ", translateTo.getResourceId(), + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); return; } String type = (String) typeDefinition; if (!HeatToToscaUtil.isYmlFileType(type)) { logger.warn("Resource '{}' of type '{}' with resourceDef which is not pointing to nested heat file is not" - + " supported and will be ignored in the translation ", translateTo.getResourceId(), - HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); + + " supported and will be ignored in the translation ", translateTo.getResourceId(), + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource()); return; } - nestedResource.setType(type); - nestedResource.setProperties((Map) ((Map) resourceDef).get(HeatConstants - .RESOURCE_DEF_PROPERTIES)); + nestedResource.setProperties((Map) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_PROPERTIES)); nestedResource.setMetadata(((Map) resourceDef).get(NESTED_RESOURCE_METADATA)); - - Optional substitutionNodeTemplateId = - ResourceTranslationFactory.getInstance(nestedResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), nestedResource, - translateTo.getResourceId(), translateTo.getContext()); - - substitutionNodeTemplateId.ifPresent(nodeTemplateId -> addSubstitutionNodeTemplate(translateTo, - nodeTemplateId)); + Optional substitutionNodeTemplateId = ResourceTranslationFactory.getInstance(nestedResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), translateTo.getHeatOrchestrationTemplate(), nestedResource, + translateTo.getResourceId(), translateTo.getContext()); + substitutionNodeTemplateId.ifPresent(nodeTemplateId -> addSubstitutionNodeTemplate(translateTo, nodeTemplateId)); } private void addSubstitutionNodeTemplate(TranslateTo translateTo, String substitutionNodeTemplateId) { - NodeTemplate substitutionNodeTemplate = - DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId); + NodeTemplate substitutionNodeTemplate = DataModelUtil.getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId); if (Objects.isNull(substitutionNodeTemplate)) { return; } - Map serviceTemplateFilter = (Map) substitutionNodeTemplate - .getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + Map serviceTemplateFilter = (Map) substitutionNodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); populateServiceTemplateFilterProperties(translateTo, substitutionNodeTemplate, serviceTemplateFilter); handlingIndexVar(translateTo, substitutionNodeTemplate); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId, - substitutionNodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId, substitutionNodeTemplate); } private void handlingIndexVar(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate) { List indexVarProperties = new ArrayList<>(); String indexVarValue = getIndexVarValue(translateTo); - replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties(), indexVarProperties, - translateTo); + replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties(), indexVarProperties, translateTo); //Add index var properties to context for unified model later - translateTo.getContext().addIndexVarProperties(ToscaUtil.getServiceTemplateFileName(translateTo - .getServiceTemplate()), translateTo.getTranslatedId(), indexVarProperties); + translateTo.getContext() + .addIndexVarProperties(ToscaUtil.getServiceTemplateFileName(translateTo.getServiceTemplate()), translateTo.getTranslatedId(), + indexVarProperties); } private Map> getNewIndexVarValue() { @@ -115,55 +103,47 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas return newIndexVarValue; } - private void replacePropertiesIndexVarValue(String indexVarValue, - Map properties, - List indexVarProperties, + private void replacePropertiesIndexVarValue(String indexVarValue, Map properties, List indexVarProperties, TranslateTo translateTo) { if (properties == null || properties.isEmpty()) { return; } - for (Map.Entry propertyEntry : properties.entrySet()) { Object propertyValue = propertyEntry.getValue(); if (propertyValue != null && propertyValue.equals(RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE)) { indexVarProperties.add(propertyEntry.getKey()); } - Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue, - indexVarProperties, translateTo); + Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue, indexVarProperties, translateTo); if (newPropertyValue != null) { properties.put(propertyEntry.getKey(), newPropertyValue); } } } - private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue, - List indexVarProperties, + private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue, List indexVarProperties, TranslateTo translateTo) { if (propertyValue instanceof String) { return handleStringPropertyValueWithIndex(indexVarValue, propertyValue); } else if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { return handleMapPropertyValueWithIndex(indexVarValue, propertyValue, indexVarProperties, translateTo); } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - return handleListPropertyValueWithIndex(indexVarValue, (List) propertyValue, indexVarProperties, - translateTo); + return handleListPropertyValueWithIndex(indexVarValue, (List) propertyValue, indexVarProperties, translateTo); } return propertyValue; } - private Object handleListPropertyValueWithIndex(String indexVarValue, List propertyValue, - List indexVarProperties, TranslateTo translateTo) { + private Object handleListPropertyValueWithIndex(String indexVarValue, List propertyValue, List indexVarProperties, + TranslateTo translateTo) { List newPropertyValueList = new ArrayList<>(); for (Object entry : propertyValue) { - newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry, - indexVarProperties, translateTo)); + newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry, indexVarProperties, translateTo)); } return newPropertyValueList; } - private Object handleMapPropertyValueWithIndex(String indexVarValue, Object propertyValue, - List indexVarProperties, TranslateTo translateTo) { - replacePropertiesIndexVarValue(indexVarValue, (Map) propertyValue, indexVarProperties, - translateTo); + private Object handleMapPropertyValueWithIndex(String indexVarValue, Object propertyValue, List indexVarProperties, + TranslateTo translateTo) { + replacePropertiesIndexVarValue(indexVarValue, (Map) propertyValue, indexVarProperties, translateTo); return propertyValue; } @@ -175,7 +155,6 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas Map> concatMap = new HashMap<>(); List concatList = new ArrayList<>(); String value = (String) propertyValue; - while (value.contains(indexVarValue)) { if (value.indexOf(indexVarValue) == 0) { concatList.add(getNewIndexVarValue()); @@ -189,7 +168,6 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas if (!value.isEmpty()) { concatList.add(value); } - concatMap.put(ToscaFunctions.CONCAT.getFunctionName(), concatList); return concatMap; } @@ -201,26 +179,19 @@ public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBas if (indexVar == null) { return HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE; } - if (indexVar instanceof String) { return (String) indexVar; } - throw new CoreException( - new InvalidPropertyValueErrorBuilder(HeatConstants.INDEX_PROPERTY_NAME, - indexVar.toString(), "String").build()); + throw new CoreException(new InvalidPropertyValueErrorBuilder(HeatConstants.INDEX_PROPERTY_NAME, indexVar.toString(), "String").build()); } - private void populateServiceTemplateFilterProperties(TranslateTo translateTo, - NodeTemplate substitutionNodeTemplate, + private void populateServiceTemplateFilterProperties(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate, Map serviceTemplateFilter) { boolean mandatory = false; Object countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getResourceId(), - ToscaConstants.COUNT_PROPERTY_NAME, translateTo.getResource().getProperties() - .get(ToscaConstants.COUNT_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - substitutionNodeTemplate, translateTo.getContext()); - + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getResourceId(), ToscaConstants.COUNT_PROPERTY_NAME, + translateTo.getResource().getProperties().get(ToscaConstants.COUNT_PROPERTY_NAME), null, translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), substitutionNodeTemplate, translateTo.getContext()); if (countValue != null) { serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); } else { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java index 7573374b65..93cd1c4156 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaLogConstants.LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION; @@ -24,7 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Predicate; - import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; import org.onap.sdc.tosca.datatypes.model.NodeType; @@ -42,13 +40,11 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapabilityHelper { - SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, - TranslateTo translateTo, FileData nestedFileData, + + SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, TranslateTo translateTo, FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); + super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); } @Override @@ -64,31 +60,22 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } @Override - protected Optional> getConnectorPropertyParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, + protected Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, String nestedHeatFileName) { - - - Object securityGroups = - heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); + Object securityGroups = heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); List paramsList = new ArrayList<>(); if (securityGroups instanceof List) { ((List) securityGroups).forEach(group -> { Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), group); - if (attachedResourceId.isPresent() - && attachedResourceId.get().isGetParam() - && attachedResourceId.get().getEntityId() instanceof String) { + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, translateTo.getContext(), group); + if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() && attachedResourceId.get() + .getEntityId() instanceof String) { paramsList.add((String) attachedResourceId.get().getEntityId()); } }); - return Optional.of(paramsList); } - return Optional.empty(); } @@ -98,45 +85,30 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } @Override - void addRequirementToConnectResources( - Map.Entry connectionPointEntry, List paramNames) { - - + void addRequirementToConnectResources(Map.Entry connectionPointEntry, List paramNames) { if (paramNames == null || paramNames.isEmpty()) { return; } List supportedSecurityRulesTypes = Collections - .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); - + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); for (String paramName : paramNames) { addRequirementToConnectResource(connectionPointEntry, supportedSecurityRulesTypes, paramName); } - } @Override - boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, - String nestedPropertyName, - String connectionPointId, - Resource connectedResource, - List supportedTypes) { - - + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, String nestedPropertyName, String connectionPointId, + Resource connectedResource, List supportedTypes) { if (resourceTranslationBase.isUnsupportedResourceType(connectedResource, supportedTypes)) { - logger.warn(LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION, - nestedResourceId, nestedPropertyName, connectedResource.getType(), - connectionPointId, supportedTypes.toString()); - + logger.warn(LOG_UNSUPPORTED_SECURITY_RULE_PORT_CAPABILITY_CONNECTION, nestedResourceId, nestedPropertyName, connectedResource.getType(), + connectionPointId, supportedTypes.toString()); return false; } - return true; } @Override Map.Entry createRequirementDefinition(String capabilityKey) { - - RequirementDefinition definition = new RequirementDefinition(); definition.setCapability(capabilityKey); definition.setRelationship(ToscaRelationshipType.ATTACHES_TO); @@ -157,6 +129,4 @@ class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapab } }; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java index 85a3f1df27..194d3fdb4f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java @@ -13,69 +13,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - public class UnifiedCompositionCatalogInstance implements UnifiedComposition { - - // There is consolidation in ScalingInstance implementation. - // In case of scaling instance, if there is more than one entry in the - // unifiedCompositionDataList, we should have consolidation between them. - // (all entries in the list are the once which need to be consolidated) - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - - UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - unifiedCompositionDataList.get(0), null, context); - // create one substitution ST for all computes - Optional substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - unifiedCompositionDataList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - return; - } - - - // create abstract NT for each compute - for (int i = 0; i < unifiedCompositionDataList.size(); i++) { - List catalogInstanceUnifiedList = new ArrayList<>(); - catalogInstanceUnifiedList.add(unifiedCompositionDataList.get(i)); - - Integer index = unifiedCompositionDataList.size() > 1 ? i : null; - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - catalogInstanceUnifiedList, substitutionNodeTypeId, context, index); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, catalogInstanceUnifiedList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, catalogInstanceUnifiedList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, catalogInstanceUnifiedList, context); + // There is consolidation in ScalingInstance implementation. + + // In case of scaling instance, if there is more than one entry in the + + // unifiedCompositionDataList, we should have consolidation between them. + + // (all entries in the list are the once which need to be consolidated) + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionDataList.get(0), null, context); + // create one substitution ST for all computes + Optional substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, unifiedCompositionDataList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + return; + } + // create abstract NT for each compute + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List catalogInstanceUnifiedList = new ArrayList<>(); + catalogInstanceUnifiedList.add(unifiedCompositionDataList.get(i)); + Integer index = unifiedCompositionDataList.size() > 1 ? i : null; + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), catalogInstanceUnifiedList, + substitutionNodeTypeId, context, index); + unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, catalogInstanceUnifiedList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, catalogInstanceUnifiedList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, catalogInstanceUnifiedList, context); + } + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); } - - unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java index 12d94720d6..e23ccfe6ee 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java @@ -19,6 +19,7 @@ */ package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -27,34 +28,30 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.List; - public class UnifiedCompositionNestedSingleCompute implements UnifiedComposition { + // There is no consolidation in NestedSingleCompute implementation. - // There is no consolidation in NestedSingleCompute implementation. - // In case of nested single compute, if there is more than one entry in the - // unifiedCompositionDataList, each one should be handed separately, no consolidation between - // them. - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { - return; - } + // In case of nested single compute, if there is more than one entry in the + + // unifiedCompositionDataList, each one should be handed separately, no consolidation between - UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, nestedServiceTemplate, - unifiedCompositionDataList, context, null); - for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { - unifiedCompositionService.handleUnifiedNestedDefinition(unifiedCompositionTo, unifiedCompositionData); - String nestedNodeTemplateId = unifiedCompositionData.getNestedTemplateConsolidationData().getNodeTemplateId(); - unifiedCompositionService - .createNestedVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.updateUnifiedNestedConnectivity(unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.cleanUnifiedNestedEntities(unifiedCompositionTo, unifiedCompositionData); - unifiedCompositionService.updateSubstitutionNodeTypePrefix(nestedServiceTemplate); + // them. + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return; + } + UnifiedCompositionTo unifiedCompositionTo = new UnifiedCompositionTo(serviceTemplate, nestedServiceTemplate, unifiedCompositionDataList, + context, null); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + unifiedCompositionService.handleUnifiedNestedDefinition(unifiedCompositionTo, unifiedCompositionData); + String nestedNodeTemplateId = unifiedCompositionData.getNestedTemplateConsolidationData().getNodeTemplateId(); + unifiedCompositionService.createNestedVfcInstanceGroup(nestedNodeTemplateId, unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.updateUnifiedNestedConnectivity(unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.cleanUnifiedNestedEntities(unifiedCompositionTo, unifiedCompositionData); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(nestedServiceTemplate); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java index 2d6360d5ab..759dc21414 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -23,51 +24,31 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.List; -import java.util.Optional; - public class UnifiedCompositionScalingInstances implements UnifiedComposition { - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList) - || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { - return; + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList) || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { + return; + } + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionDataList.get(0), null, context); + Optional substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, unifiedCompositionDataList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + return; + } + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), unifiedCompositionDataList, + substitutionNodeTypeId, context, null); + unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); } - - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - unifiedCompositionDataList.get(0), null, context); - Optional substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - unifiedCompositionDataList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - return; - } - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - unifiedCompositionDataList, substitutionNodeTypeId, context, null); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java index 45326d0727..fda4cebc22 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; @@ -23,70 +25,49 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.compositi import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - - /** * The type Unified composition single substitution. */ public class UnifiedCompositionSingleSubstitution implements UnifiedComposition { - private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); - - // There is no consolidation in SingleSubstitution implementation. - // In case of single substitution, if there is more than one entry in the - // unifiedCompositionDataList, they all should contain the same compute type but the - // consolidation between them was canceled. - // For different compute type, this implementation will be called more than once, each time - // per diff compute type, while sending one entry in the unifiedCompositionDataList. - @Override - public void createUnifiedComposition(ServiceTemplate serviceTemplate, - ServiceTemplate nestedServiceTemplate, - List unifiedCompositionDataList, - TranslationContext context) { - if (CollectionUtils.isEmpty(unifiedCompositionDataList) - || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { - return; + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + // There is no consolidation in SingleSubstitution implementation. + + // In case of single substitution, if there is more than one entry in the + + // unifiedCompositionDataList, they all should contain the same compute type but the + + // consolidation between them was canceled. + + // For different compute type, this implementation will be called more than once, each time + + // per diff compute type, while sending one entry in the unifiedCompositionDataList. + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, TranslationContext context) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList) || context.isUnifiedHandledServiceTemplate(serviceTemplate)) { + return; + } + unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List singleSubstitutionUnifiedList = new ArrayList<>(); + singleSubstitutionUnifiedList.add(unifiedCompositionDataList.get(i)); + String substitutionNodeTypeId = unifiedCompositionService + .getSubstitutionNodeTypeId(serviceTemplate, singleSubstitutionUnifiedList.get(0), null, context); + Optional substitutionServiceTemplate = unifiedCompositionService + .createUnifiedSubstitutionServiceTemplate(serviceTemplate, singleSubstitutionUnifiedList, context, substitutionNodeTypeId, null); + if (!substitutionServiceTemplate.isPresent()) { + continue; + } + String abstractSubstituteNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), singleSubstitutionUnifiedList, + substitutionNodeTypeId, context, null); + unifiedCompositionService + .createVfcInstanceGroup(abstractSubstituteNodeTemplateId, serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.updateCompositionConnectivity(serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.cleanUnifiedCompositionEntities(serviceTemplate, singleSubstitutionUnifiedList, context); + unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); + } + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); } - - unifiedCompositionService.handleComplexVfcType(serviceTemplate, context); - - for (int i = 0; i < unifiedCompositionDataList.size(); i++) { - List singleSubstitutionUnifiedList = new ArrayList<>(); - singleSubstitutionUnifiedList.add(unifiedCompositionDataList.get(i)); - - String substitutionNodeTypeId = - unifiedCompositionService.getSubstitutionNodeTypeId(serviceTemplate, - singleSubstitutionUnifiedList.get(0), null, context); - - Optional substitutionServiceTemplate = - unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, - singleSubstitutionUnifiedList, context, substitutionNodeTypeId, null); - - if (!substitutionServiceTemplate.isPresent()) { - continue; - } - - String abstractSubstituteNodeTemplateId = unifiedCompositionService - .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), - singleSubstitutionUnifiedList, substitutionNodeTypeId, context, null); - - unifiedCompositionService.createVfcInstanceGroup(abstractSubstituteNodeTemplateId, - serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService - .updateCompositionConnectivity(serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService - .cleanUnifiedCompositionEntities(serviceTemplate, singleSubstitutionUnifiedList, context); - - unifiedCompositionService.updateSubstitutionNodeTypePrefix(substitutionServiceTemplate.get()); - } - - unifiedCompositionService - .cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); - - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java index 386b2e1ea9..64915a0af7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.services.heattotosca.mapping; import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; @@ -52,321 +51,268 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslatio public class TranslatorHeatToToscaParameterConverter { - - private static Map parameterTypeMapping; - private static Map parameterEntrySchemaTypeMapping; - private static final String RANGE = "range"; - private static final String LENGTH = "length"; - private static final String MIN = "min"; - private static final String MAX = "max"; - private static final String ALLOWED_VALUES = "allowed_values"; - private static final String ALLOWED_PATTERN = "allowed_pattern"; - - - static { - parameterEntrySchemaTypeMapping = new HashMap<>(); - parameterEntrySchemaTypeMapping.put("list", "string"); - } - - static { - parameterTypeMapping = new HashMap<>(); - parameterTypeMapping.put("string", "string"); - parameterTypeMapping.put("number", "float"); - parameterTypeMapping.put("comma_delimited_list", "list"); - parameterTypeMapping.put("json", "json"); - parameterTypeMapping.put("boolean", "boolean"); - } - - /** - * Parameter converter map. - * - * @param parameters the parameters - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the map - */ - public static Map parameterConverter(ServiceTemplate serviceTemplate, - Map parameters, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, String parentHeatFileName, - TranslationContext context, - Map heatEnvParameters) { - Map parameterDefinitionMap = new HashMap<>(); - for (Map.Entry entry : parameters.entrySet()) { - String heatParamName = entry.getKey(); - parameterDefinitionMap.put(heatParamName, - getToscaParameter(serviceTemplate,heatParamName, entry.getValue(), heatOrchestrationTemplate, heatFileName, - parentHeatFileName, context, heatEnvParameters)); + private static final String RANGE = "range"; + private static final String LENGTH = "length"; + private static final String MIN = "min"; + private static final String MAX = "max"; + private static final String ALLOWED_VALUES = "allowed_values"; + private static final String ALLOWED_PATTERN = "allowed_pattern"; + private static Map parameterTypeMapping; + private static Map parameterEntrySchemaTypeMapping; + + static { + parameterEntrySchemaTypeMapping = new HashMap<>(); + parameterEntrySchemaTypeMapping.put("list", "string"); } - return parameterDefinitionMap; - } - /** - * Parameter output converter map. - * - * @param parameters the parameters - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the map - */ - public static Map parameterOutputConverter(ServiceTemplate serviceTemplate, - Map parameters, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, TranslationContext context) { - Map parameterDefinitionMap = new HashMap<>(); - for (Map.Entry entry : parameters.entrySet()) { - parameterDefinitionMap.put(entry.getKey(), - getToscaOutputParameter(serviceTemplate,entry.getKey(),entry.getValue(), - heatOrchestrationTemplate, - heatFileName, - context)); + static { + parameterTypeMapping = new HashMap<>(); + parameterTypeMapping.put("string", "string"); + parameterTypeMapping.put("number", "float"); + parameterTypeMapping.put("comma_delimited_list", "list"); + parameterTypeMapping.put("json", "json"); + parameterTypeMapping.put("boolean", "boolean"); } - return parameterDefinitionMap; - } - - /** - * Gets tosca parameter. - * - * @param heatParameter the heat parameter - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the tosca parameter - */ - private static ParameterDefinitionExt getToscaParameter(ServiceTemplate serviceTemplate, - String heatParameterName, - Parameter heatParameter, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String heatFileName, - String parentHeatFileName, - TranslationContext context, - Map heatEnvParameters) { - - ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); - toscaParameter.setType(getToscaParameterType(heatParameter.getType(), heatEnvParameters)); - toscaParameter.setEntry_schema(getToscaParameterEntrySchema(toscaParameter.getType())); - toscaParameter.setLabel(heatParameter.getLabel()); - toscaParameter.setDescription(heatParameter.getDescription()); - toscaParameter.set_default( - getToscaParameterDefaultValue(serviceTemplate, heatParameterName, heatParameter.get_default(), - toscaParameter.getType(), heatFileName, heatOrchestrationTemplate, context)); - toscaParameter.setHidden(heatParameter.isHidden()); - toscaParameter.setImmutable(heatParameter.isImmutable()); - toscaParameter.setConstraints(getToscaConstrains(heatParameter.getConstraints())); - Optional> annotations = getToscaAnnotations(context, heatFileName, parentHeatFileName, heatParameterName); - annotations.ifPresent(ant->toscaParameter.setAnnotations(annotations.get())); - - return toscaParameter; - } - - private static Optional > getToscaAnnotations (TranslationContext context, String heatFileName, String parentHeatFileName, String heatParameterName){ - - if(parentHeatFileName != null){ - heatFileName = parentHeatFileName; + /** + * Parameter converter map. + * + * @param parameters the parameters + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the map + */ + public static Map parameterConverter(ServiceTemplate serviceTemplate, Map parameters, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + String parentHeatFileName, TranslationContext context, + Map heatEnvParameters) { + Map parameterDefinitionMap = new HashMap<>(); + for (Map.Entry entry : parameters.entrySet()) { + String heatParamName = entry.getKey(); + parameterDefinitionMap.put(heatParamName, + getToscaParameter(serviceTemplate, heatParamName, entry.getValue(), heatOrchestrationTemplate, heatFileName, parentHeatFileName, + context, heatEnvParameters)); + } + return parameterDefinitionMap; } - if(!isAnnotationRequired(context, heatFileName)){ - return Optional.empty(); + /** + * Parameter output converter map. + * + * @param parameters the parameters + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the map + */ + public static Map parameterOutputConverter(ServiceTemplate serviceTemplate, Map parameters, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + TranslationContext context) { + Map parameterDefinitionMap = new HashMap<>(); + for (Map.Entry entry : parameters.entrySet()) { + parameterDefinitionMap.put(entry.getKey(), + getToscaOutputParameter(serviceTemplate, entry.getKey(), entry.getValue(), heatOrchestrationTemplate, heatFileName, context)); + } + return parameterDefinitionMap; } - AnnotationDefinition annotationDefinition = new AnnotationDefinition(); - annotationDefinition.setType(ToscaAnnotationType.SOURCE); - annotationDefinition.setProperties(new HashMap<>()); - List vfModuleList = new ArrayList<>(); - vfModuleList.add( FileUtils.getFileWithoutExtention(heatFileName)); - annotationDefinition.getProperties().put(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME, vfModuleList); - annotationDefinition.getProperties().put(ToscaConstants.SOURCE_TYPE_PROPERTY_NAME, ToscaConstants.HEAT_SOURCE_TYPE); - annotationDefinition.getProperties().put(ToscaConstants.PARAM_NAME_PROPERTY_NAME, heatParameterName); - Map annotationMap = new HashMap<>(); - annotationMap.put(ToscaConstants.SOURCE_ANNOTATION_ID, annotationDefinition); - return Optional.of(annotationMap); - - } - - private static boolean isAnnotationRequired(TranslationContext context, String heatFileName){ - return !isNestedServiceTemplate(context, heatFileName); - } - - private static boolean isNestedServiceTemplate(TranslationContext context, String heatFileName) { - return HeatToToscaUtil.isHeatFileNested(context, heatFileName); - } - - - /** - * Gets tosca output parameter. - * - * @param heatOutputParameter the heat output parameter - * @param heatOrchestrationTemplate the heat orchestration template - * @param heatFileName the heat file name - * @param context the context - * @return the tosca output parameter - */ - private static ParameterDefinitionExt getToscaOutputParameter(ServiceTemplate serviceTemplate, - String parameterName, - Output heatOutputParameter, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String heatFileName, - TranslationContext context) { - - ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); - toscaParameter.setDescription(heatOutputParameter.getDescription()); - toscaParameter.setValue( - getToscaParameterDefaultValue(serviceTemplate,parameterName,heatOutputParameter.getValue(), - toscaParameter.getType(), - heatFileName, heatOrchestrationTemplate, context)); - return toscaParameter; - } - - /** - * Gets tosca parameter default value. - * - * @param obj the a default - * @param type the type - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param context the context - * @return the tosca parameter default value - */ - public static Object getToscaParameterDefaultValue(ServiceTemplate serviceTemplate, - String parameterName, - Object obj, String type, - String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - TranslationContext context) { - - if (obj == null) { - return null; - } - Object toscaDefaultValue = obj; - if ("list".equals(type)) { - if (obj instanceof String) { - return Arrays.asList(((String) obj).split(",")); - } else { - return toscaDefaultValue; - } + /** + * Gets tosca parameter. + * + * @param heatParameter the heat parameter + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the tosca parameter + */ + private static ParameterDefinitionExt getToscaParameter(ServiceTemplate serviceTemplate, String heatParameterName, Parameter heatParameter, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + String parentHeatFileName, TranslationContext context, + Map heatEnvParameters) { + ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); + toscaParameter.setType(getToscaParameterType(heatParameter.getType(), heatEnvParameters)); + toscaParameter.setEntry_schema(getToscaParameterEntrySchema(toscaParameter.getType())); + toscaParameter.setLabel(heatParameter.getLabel()); + toscaParameter.setDescription(heatParameter.getDescription()); + toscaParameter.set_default( + getToscaParameterDefaultValue(serviceTemplate, heatParameterName, heatParameter.get_default(), toscaParameter.getType(), heatFileName, + heatOrchestrationTemplate, context)); + toscaParameter.setHidden(heatParameter.isHidden()); + toscaParameter.setImmutable(heatParameter.isImmutable()); + toscaParameter.setConstraints(getToscaConstrains(heatParameter.getConstraints())); + Optional> annotations = getToscaAnnotations(context, heatFileName, parentHeatFileName, heatParameterName); + annotations.ifPresent(ant -> toscaParameter.setAnnotations(annotations.get())); + return toscaParameter; } - return getToscaParameterValue(serviceTemplate,parameterName,toscaDefaultValue, heatFileName, - heatOrchestrationTemplate, - context); - } - - private static Object getToscaParameterValue(ServiceTemplate serviceTemplate, - String parameterName, - Object paramValue, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - if (paramValue instanceof Map) { - if(MapUtils.isEmpty((Map) paramValue)){ - return new HashMap<>(); - } - Map.Entry functionMapEntry = - (Map.Entry) ((Map) paramValue).entrySet().iterator().next(); - if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { - - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(serviceTemplate, null, - heatFileName, heatOrchestrationTemplate, context), parameterName, functionMapEntry.getValue(), null); - return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() - .translateFunction(functionTranslator); - } + private static Optional> getToscaAnnotations(TranslationContext context, String heatFileName, + String parentHeatFileName, String heatParameterName) { + if (parentHeatFileName != null) { + heatFileName = parentHeatFileName; + } + if (!isAnnotationRequired(context, heatFileName)) { + return Optional.empty(); + } + AnnotationDefinition annotationDefinition = new AnnotationDefinition(); + annotationDefinition.setType(ToscaAnnotationType.SOURCE); + annotationDefinition.setProperties(new HashMap<>()); + List vfModuleList = new ArrayList<>(); + vfModuleList.add(FileUtils.getFileWithoutExtention(heatFileName)); + annotationDefinition.getProperties().put(ToscaConstants.VF_MODULE_LABEL_PROPERTY_NAME, vfModuleList); + annotationDefinition.getProperties().put(ToscaConstants.SOURCE_TYPE_PROPERTY_NAME, ToscaConstants.HEAT_SOURCE_TYPE); + annotationDefinition.getProperties().put(ToscaConstants.PARAM_NAME_PROPERTY_NAME, heatParameterName); + Map annotationMap = new HashMap<>(); + annotationMap.put(ToscaConstants.SOURCE_ANNOTATION_ID, annotationDefinition); + return Optional.of(annotationMap); } - return paramValue; - } - - private static List getToscaConstrains(List> constraints) { - if (constraints == null) { - return null; + private static boolean isAnnotationRequired(TranslationContext context, String heatFileName) { + return !isNestedServiceTemplate(context, heatFileName); } - List constraintList = new ArrayList<>(); - - for (Map constraint : constraints) { - constraintList.addAll(getToscaParameterConstraint(constraint)); + private static boolean isNestedServiceTemplate(TranslationContext context, String heatFileName) { + return HeatToToscaUtil.isHeatFileNested(context, heatFileName); } - return constraintList; - } - - private static List getToscaParameterConstraint(Map constraint) { - List convertedConstraintList = new ArrayList<>(); - Constraint convertedConstraint; - - if (constraint.containsKey(RANGE)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - Integer min = (Integer) ((Map) constraint.get(RANGE)).get(MIN); - Integer max = (Integer) ((Map) constraint.get(RANGE)).get(MAX); - convertedConstraint.setIn_range(new Integer[]{min, max}); - - } else if (constraint.containsKey(LENGTH)) { - Integer min = (Integer) ((Map) constraint.get(LENGTH)).get(MIN); - Integer max = (Integer) ((Map) constraint.get(LENGTH)).get(MAX); - if (max != null) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setMax_length(max); - } - if (min != null) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setMin_length(min); - } - } else if (constraint.containsKey(ALLOWED_VALUES)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setValid_values((List) constraint.get(ALLOWED_VALUES)); - } else if (constraint.containsKey(ALLOWED_PATTERN)) { - convertedConstraint = new Constraint(); - convertedConstraintList.add(convertedConstraint); - convertedConstraint.setPattern(constraint.get(ALLOWED_PATTERN)); + /** + * Gets tosca output parameter. + * + * @param heatOutputParameter the heat output parameter + * @param heatOrchestrationTemplate the heat orchestration template + * @param heatFileName the heat file name + * @param context the context + * @return the tosca output parameter + */ + private static ParameterDefinitionExt getToscaOutputParameter(ServiceTemplate serviceTemplate, String parameterName, Output heatOutputParameter, + HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, + TranslationContext context) { + ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); + toscaParameter.setDescription(heatOutputParameter.getDescription()); + toscaParameter.setValue( + getToscaParameterDefaultValue(serviceTemplate, parameterName, heatOutputParameter.getValue(), toscaParameter.getType(), heatFileName, + heatOrchestrationTemplate, context)); + return toscaParameter; } - return convertedConstraintList; - } - - private static EntrySchema getToscaParameterEntrySchema(String type) { + /** + * Gets tosca parameter default value. + * + * @param obj the a default + * @param type the type + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param context the context + * @return the tosca parameter default value + */ + public static Object getToscaParameterDefaultValue(ServiceTemplate serviceTemplate, String parameterName, Object obj, String type, + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context) { + if (obj == null) { + return null; + } + Object toscaDefaultValue = obj; + if ("list".equals(type)) { + if (obj instanceof String) { + return Arrays.asList(((String) obj).split(",")); + } else { + return toscaDefaultValue; + } + } + return getToscaParameterValue(serviceTemplate, parameterName, toscaDefaultValue, heatFileName, heatOrchestrationTemplate, context); + } - if (!parameterEntrySchemaTypeMapping.containsKey(type)) { - return null; + private static Object getToscaParameterValue(ServiceTemplate serviceTemplate, String parameterName, Object paramValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + if (paramValue instanceof Map) { + if (MapUtils.isEmpty((Map) paramValue)) { + return new HashMap<>(); + } + Map.Entry functionMapEntry = (Map.Entry) ((Map) paramValue).entrySet().iterator().next(); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(serviceTemplate, null, heatFileName, heatOrchestrationTemplate, context), parameterName, + functionMapEntry.getValue(), null); + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get().translateFunction(functionTranslator); + } + } + return paramValue; } - EntrySchema entrySchema = new EntrySchema(); - entrySchema.setType(parameterEntrySchemaTypeMapping.get(type)); - return entrySchema; - } + private static List getToscaConstrains(List> constraints) { + if (constraints == null) { + return null; + } + List constraintList = new ArrayList<>(); + for (Map constraint : constraints) { + constraintList.addAll(getToscaParameterConstraint(constraint)); + } + return constraintList; + } - protected static String getToscaParameterType(final String heatParameterType, - final Map heatEnvParameters) { - if (heatEnvParameters != null && DefinedHeatParameterTypes.NUMBER.getType().equals(heatParameterType)) { - if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitSize.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_SIZE.getType(); - } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitTime.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_TIME.getType(); - } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitFrequency.class) != null) { - return ToscaScalarUnitTypes.SCALAR_UNIT_FREQUENCY.getType(); - } + private static List getToscaParameterConstraint(Map constraint) { + List convertedConstraintList = new ArrayList<>(); + Constraint convertedConstraint; + if (constraint.containsKey(RANGE)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + Integer min = (Integer) ((Map) constraint.get(RANGE)).get(MIN); + Integer max = (Integer) ((Map) constraint.get(RANGE)).get(MAX); + convertedConstraint.setIn_range(new Integer[]{min, max}); + } else if (constraint.containsKey(LENGTH)) { + Integer min = (Integer) ((Map) constraint.get(LENGTH)).get(MIN); + Integer max = (Integer) ((Map) constraint.get(LENGTH)).get(MAX); + if (max != null) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setMax_length(max); + } + if (min != null) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setMin_length(min); + } + } else if (constraint.containsKey(ALLOWED_VALUES)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setValid_values((List) constraint.get(ALLOWED_VALUES)); + } else if (constraint.containsKey(ALLOWED_PATTERN)) { + convertedConstraint = new Constraint(); + convertedConstraintList.add(convertedConstraint); + convertedConstraint.setPattern(constraint.get(ALLOWED_PATTERN)); + } + return convertedConstraintList; } - return parameterTypeMapping.get(heatParameterType); - } + private static EntrySchema getToscaParameterEntrySchema(String type) { + if (!parameterEntrySchemaTypeMapping.containsKey(type)) { + return null; + } + EntrySchema entrySchema = new EntrySchema(); + entrySchema.setType(parameterEntrySchemaTypeMapping.get(type)); + return entrySchema; + } - private static > String getScalarUnitType(final Map heatEnvParameters, - final Class enumClass) { - final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); - if (Arrays.stream(enumClass.getEnumConstants()).anyMatch(unitType -> - heatEnvParameters.values().stream().filter(Objects::nonNull) - .anyMatch(parameterValue -> scalarUnitValidator.isScalarUnit(parameterValue.toString()) && - Arrays.stream(StringUtils.split(parameterValue.toString())) - .anyMatch(strParamValue -> strParamValue.equalsIgnoreCase(unitType.name()))))) { - return enumClass.getTypeName(); + protected static String getToscaParameterType(final String heatParameterType, final Map heatEnvParameters) { + if (heatEnvParameters != null && DefinedHeatParameterTypes.NUMBER.getType().equals(heatParameterType)) { + if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitSize.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_SIZE.getType(); + } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitTime.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_TIME.getType(); + } else if (getScalarUnitType(heatEnvParameters, ToscaScalarUnitFrequency.class) != null) { + return ToscaScalarUnitTypes.SCALAR_UNIT_FREQUENCY.getType(); + } + } + return parameterTypeMapping.get(heatParameterType); } - return null; - } + private static > String getScalarUnitType(final Map heatEnvParameters, final Class enumClass) { + final ScalarUnitValidator scalarUnitValidator = ScalarUnitValidator.getInstance(); + if (Arrays.stream(enumClass.getEnumConstants()).anyMatch(unitType -> heatEnvParameters.values().stream().filter(Objects::nonNull).anyMatch( + parameterValue -> scalarUnitValidator.isScalarUnit(parameterValue.toString()) && Arrays + .stream(StringUtils.split(parameterValue.toString())).anyMatch(strParamValue -> strParamValue.equalsIgnoreCase(unitType.name()))))) { + return enumClass.getTypeName(); + } + return null; + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java index 967f1f92ce..b9cad2f474 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.translator.services.heattotosca.mapping; +import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.onap.sdc.tosca.datatypes.model.Template; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -29,138 +34,110 @@ import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo; - public class TranslatorHeatToToscaPropertyConverter { - /** - * Gets tosca properties simple conversion. - * - * @param heatProperties the heat properties - * @param toscaProperties the tosca properties - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param resourceType the resource type - * @param template the template - * @param context the context - * @return the tosca properties simple conversion - */ - //Convert property assuming the property type in heat is same as the property type in tosca - public static Map getToscaPropertiesSimpleConversion(ServiceTemplate - serviceTemplate, - String resourceId,Map heatProperties, Map toscaProperties, - String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, String - resourceType, Template template, TranslationContext context) { - - toscaProperties = toscaProperties != null ? toscaProperties : new HashMap<>(); + /** + * Gets tosca properties simple conversion. + * + * @param heatProperties the heat properties + * @param toscaProperties the tosca properties + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceType the resource type + * @param template the template + * @param context the context + * @return the tosca properties simple conversion + */ - for (String heatPropertyName : context.getElementSet(resourceType, Constants.PROP)) { - - setSimpleProperty(serviceTemplate, resourceId, heatProperties, heatFileName, resourceType, - heatOrchestrationTemplate, - context, toscaProperties, heatPropertyName, null, template); + //Convert property assuming the property type in heat is same as the property type in tosca + public static Map getToscaPropertiesSimpleConversion(ServiceTemplate serviceTemplate, String resourceId, + Map heatProperties, Map toscaProperties, + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceType, Template template, TranslationContext context) { + toscaProperties = toscaProperties != null ? toscaProperties : new HashMap<>(); + for (String heatPropertyName : context.getElementSet(resourceType, Constants.PROP)) { + setSimpleProperty(serviceTemplate, resourceId, heatProperties, heatFileName, resourceType, heatOrchestrationTemplate, context, + toscaProperties, heatPropertyName, null, template); + } + return toscaProperties; } - return toscaProperties; - } - /** - * Sets simple property. - * - * @param heatProperties the heat properties - * @param heatFileName the heat file name - * @param resourceType the resource type - * @param heatOrchestrationTemplate the heat orchestration template - * @param context the context - * @param toscaProperties the tosca properties - * @param heatPropertyName the heat property name - * @param toscaPropertyName the tosca property name - * @param template the template - */ - public static void setSimpleProperty(ServiceTemplate serviceTemplate,String resourceId, - Map heatProperties, - String heatFileName, - String resourceType, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - Map toscaProperties, String heatPropertyName, - String toscaPropertyName, Template template) { - Object propertyValue = null; - if (heatProperties != null) { - propertyValue = heatProperties.get(heatPropertyName); - } - if (propertyValue == null) { - return; + /** + * Sets simple property. + * + * @param heatProperties the heat properties + * @param heatFileName the heat file name + * @param resourceType the resource type + * @param heatOrchestrationTemplate the heat orchestration template + * @param context the context + * @param toscaProperties the tosca properties + * @param heatPropertyName the heat property name + * @param toscaPropertyName the tosca property name + * @param template the template + */ + public static void setSimpleProperty(ServiceTemplate serviceTemplate, String resourceId, Map heatProperties, String heatFileName, + String resourceType, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, + Map toscaProperties, String heatPropertyName, String toscaPropertyName, Template template) { + Object propertyValue = null; + if (heatProperties != null) { + propertyValue = heatProperties.get(heatPropertyName); + } + if (propertyValue == null) { + return; + } + if (toscaPropertyName == null) { + toscaPropertyName = resourceType == null ? heatPropertyName : context.getElementMapping(resourceType, Constants.PROP, heatPropertyName); + if (toscaPropertyName == null) { + return; + } + } + toscaProperties.put(toscaPropertyName, + getToscaPropertyValue(serviceTemplate, resourceId, heatPropertyName, propertyValue, resourceType, heatFileName, heatOrchestrationTemplate, + template, context)); } - if (toscaPropertyName == null) { - toscaPropertyName = resourceType == null ? heatPropertyName - : context.getElementMapping(resourceType, Constants.PROP, heatPropertyName); - if (toscaPropertyName == null) { - return; - } - } - toscaProperties.put(toscaPropertyName, - getToscaPropertyValue(serviceTemplate, resourceId,heatPropertyName, propertyValue, - resourceType, - heatFileName, heatOrchestrationTemplate, template, context)); - } - - - /** - * Gets tosca property value. - * - * @param propertyName the property name - * @param propertyValue the property value - * @param resourceType the resource type - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param template the template - * @param context the context - * @return the tosca property value - */ - public static Object getToscaPropertyValue(ServiceTemplate serviceTemplate, String resourceId, - String propertyName, Object propertyValue, - String resourceType, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Template template, TranslationContext context) { - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map.Entry functionMapEntry = - (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); - if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { - FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(serviceTemplate, - resourceId, heatFileName, heatOrchestrationTemplate, context), propertyName, - functionMapEntry.getValue(), template); - return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() - .translateFunction(functionTranslator); - } - Map propertyValueMap = new HashMap<>(); - for (Map.Entry entry : ((Map) propertyValue).entrySet()) { - String toscaPropertyName = resourceType == null ? null : context - .getElementMapping(resourceType, Constants.PROP, propertyName - + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey()); - toscaPropertyName = toscaPropertyName != null ? toscaPropertyName : entry.getKey(); - propertyValueMap.put(toscaPropertyName, - getToscaPropertyValue(serviceTemplate, resourceId, - propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR - + entry.getKey(), entry.getValue(), resourceType, heatFileName, - heatOrchestrationTemplate, template, context)); - } - return propertyValueMap; - } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - List propertyValueArray = new ArrayList<>(); - for (int i = 0; i < ((List) propertyValue).size(); i++) { - propertyValueArray.add( - getToscaPropertyValue(serviceTemplate, resourceId, propertyName, ((List) - propertyValue).get(i), - resourceType, heatFileName, heatOrchestrationTemplate, template, context)); - } - return propertyValueArray; + /** + * Gets tosca property value. + * + * @param propertyName the property name + * @param propertyValue the property value + * @param resourceType the resource type + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param template the template + * @param context the context + * @return the tosca property value + */ + public static Object getToscaPropertyValue(ServiceTemplate serviceTemplate, String resourceId, String propertyName, Object propertyValue, + String resourceType, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + Template template, TranslationContext context) { + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map.Entry functionMapEntry = (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + FunctionTranslator functionTranslator = new FunctionTranslator( + getFunctionTranslateTo(serviceTemplate, resourceId, heatFileName, heatOrchestrationTemplate, context), propertyName, + functionMapEntry.getValue(), template); + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get().translateFunction(functionTranslator); + } + Map propertyValueMap = new HashMap<>(); + for (Map.Entry entry : ((Map) propertyValue).entrySet()) { + String toscaPropertyName = resourceType == null ? null : context + .getElementMapping(resourceType, Constants.PROP, propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey()); + toscaPropertyName = toscaPropertyName != null ? toscaPropertyName : entry.getKey(); + propertyValueMap.put(toscaPropertyName, + getToscaPropertyValue(serviceTemplate, resourceId, propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey(), + entry.getValue(), resourceType, heatFileName, heatOrchestrationTemplate, template, context)); + } + return propertyValueMap; + } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + List propertyValueArray = new ArrayList<>(); + for (int i = 0; i < ((List) propertyValue).size(); i++) { + propertyValueArray.add( + getToscaPropertyValue(serviceTemplate, resourceId, propertyName, ((List) propertyValue).get(i), resourceType, heatFileName, + heatOrchestrationTemplate, template, context)); + } + return propertyValueArray; + } + return propertyValue; } - return propertyValue; - } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java index c3c1febf40..50738e9404 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.translator.utils; import java.io.BufferedReader; @@ -33,7 +32,6 @@ import java.util.function.BiConsumer; import java.util.function.Predicate; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; - import org.apache.commons.io.IOUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -41,119 +39,103 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class ResourceWalker { - private static final String RESOURCE_FILE_READ_ERROR = "Can't read resource file from class path."; - - private ResourceWalker() { - } - - /** - * Read resources from directory map. - * - * @param resourceDirectoryToStart the resource directory to start - * @return the map of file where key is file name and value is its data - * @throws Exception the exception - */ - public static Map readResourcesFromDirectory(String resourceDirectoryToStart) - throws - Exception { - Map filesContent = new HashMap<>(); - traverse(resourceDirectoryToStart, (fileName, stream) -> { - try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { - filesContent.put(fileName, IOUtils.toString(reader)); - } catch (IOException exception) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(RESOURCE_FILE_READ_ERROR - + " File name = " + fileName) - .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(), - exception); - } - }); - return filesContent; - } + private static final String RESOURCE_FILE_READ_ERROR = "Can't read resource file from class path."; - private static void traverse(String start, BiConsumer handler) throws - Exception { - - URL url = ResourceWalker.class.getClassLoader().getResource(start); - if (url == null) { - throw new FileNotFoundException("Resource not found: " + start); + private ResourceWalker() { } - switch (url.getProtocol().toLowerCase()) { + /** + * Read resources from directory map. + * + * @param resourceDirectoryToStart the resource directory to start + * @return the map of file where key is file name and value is its data + * @throws Exception the exception + */ + public static Map readResourcesFromDirectory(String resourceDirectoryToStart) throws Exception { + Map filesContent = new HashMap<>(); + traverse(resourceDirectoryToStart, (fileName, stream) -> { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { + filesContent.put(fileName, IOUtils.toString(reader)); + } catch (IOException exception) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(RESOURCE_FILE_READ_ERROR + " File name = " + fileName) + .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(), exception); + } + }); + return filesContent; + } - case "file": - traverseFile(new File(url.getPath()), handler); - break; - case "zip": - case "jar": - String path = url.getPath(); - int resourcePosition = path.lastIndexOf("!/" + start); - traverseArchive(path.substring(0, resourcePosition), start, handler); - break; - default: - throw new IllegalArgumentException("Unknown protocol"); + private static void traverse(String start, BiConsumer handler) throws Exception { + URL url = ResourceWalker.class.getClassLoader().getResource(start); + if (url == null) { + throw new FileNotFoundException("Resource not found: " + start); + } + switch (url.getProtocol().toLowerCase()) { + case "file": + traverseFile(new File(url.getPath()), handler); + break; + case "zip": + case "jar": + String path = url.getPath(); + int resourcePosition = path.lastIndexOf("!/" + start); + traverseArchive(path.substring(0, resourcePosition), start, handler); + break; + default: + throw new IllegalArgumentException("Unknown protocol"); + } } - } - private static void traverseArchive(String file, String resource, BiConsumer - handler) - throws URISyntaxException, IOException { + private static void traverseArchive(String file, String resource, BiConsumer handler) + throws URISyntaxException, IOException { + // There is what looks like a bug in Java: - // There is what looks like a bug in Java: - // if "abc" is a directory in an archive, - // both "abc" and "abc/" will be found successfully. - // However, calling isDirectory() will return "true" for "abc/", - // but "false" for "abc". - try (ZipFile zip = new ZipFile(new URI(file).getPath())) { + // if "abc" is a directory in an archive, - Predicate predicate = buildPredicate(resource); - Enumeration entries = zip.entries(); - while (entries.hasMoreElements()) { - handleZipEntry(predicate, zip, entries.nextElement(), handler); - } - } - } + // both "abc" and "abc/" will be found successfully. - private static Predicate buildPredicate(String resource) { + // However, calling isDirectory() will return "true" for "abc/", - if (resource.endsWith("/")) { - return zipEntry -> - zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory(); - } else { - return zipEntry -> { - String name = zipEntry.getName(); - return (name.equals(resource) || name.startsWith(resource + "/")) - && !zipEntry.isDirectory() && !name.contains("../"); - }; + // but "false" for "abc". + try (ZipFile zip = new ZipFile(new URI(file).getPath())) { + Predicate predicate = buildPredicate(resource); + Enumeration entries = zip.entries(); + while (entries.hasMoreElements()) { + handleZipEntry(predicate, zip, entries.nextElement(), handler); + } + } } - } - - private static void handleZipEntry(Predicate predicate, ZipFile zip, ZipEntry zipEntry, - BiConsumer handler) - throws IOException { - - if (predicate.test(zipEntry)) { - try (InputStream input = zip.getInputStream(zipEntry)) { - handler.accept(zipEntry.getName(), input); - } + private static Predicate buildPredicate(String resource) { + if (resource.endsWith("/")) { + return zipEntry -> zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory(); + } else { + return zipEntry -> { + String name = zipEntry.getName(); + return (name.equals(resource) || name.startsWith(resource + "/")) && !zipEntry.isDirectory() && !name.contains("../"); + }; + } } - } - private static void traverseFile(File file, BiConsumer handler) throws - IOException { + private static void handleZipEntry(Predicate predicate, ZipFile zip, ZipEntry zipEntry, BiConsumer handler) + throws IOException { + if (predicate.test(zipEntry)) { + try (InputStream input = zip.getInputStream(zipEntry)) { + handler.accept(zipEntry.getName(), input); + } + } + } - if (file.isDirectory()) { - File[] files = file.listFiles(); - if (files != null) { - for (File sub : files) { - traverseFile(sub, handler); + private static void traverseFile(File file, BiConsumer handler) throws IOException { + if (file.isDirectory()) { + File[] files = file.listFiles(); + if (files != null) { + for (File sub : files) { + traverseFile(sub, handler); + } + } + } else { + try (FileInputStream stream = new FileInputStream(file)) { + handler.accept(file.getPath(), stream); + } } - } - } else { - try (FileInputStream stream = new FileInputStream(file)) { - handler.accept(file.getPath(), stream); - } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/ErrorMessageCode.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/ErrorMessageCode.java index ac31bd4a1e..8fa2494fed 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/ErrorMessageCode.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/ErrorMessageCode.java @@ -22,10 +22,10 @@ package org.openecomp.core.validation; import java.util.Objects; public final class ErrorMessageCode { + private final String messageCode; public ErrorMessageCode(String messageCode) { - this.messageCode = messageCode; } @@ -46,9 +46,7 @@ public final class ErrorMessageCode { if (o == null || getClass() != o.getClass()) { return false; } - ErrorMessageCode that = (ErrorMessageCode) o; - return Objects.equals(this.messageCode, that.messageCode); } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/api/ValidationManager.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/api/ValidationManager.java index 9f75a08051..0408f64447 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/api/ValidationManager.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/api/ValidationManager.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.api; - -import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.List; import java.util.Map; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public interface ValidationManager { - Map> validate(); + Map> validate(); - void addFile(String fileName, byte[] validationContent); + void addFile(String fileName, byte[] validationContent); - void updateGlobalContext(GlobalValidationContext globalContext); + void updateGlobalContext(GlobalValidationContext globalContext); } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/errors/ErrorMessagesFormatBuilder.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/errors/ErrorMessagesFormatBuilder.java index e3ed721fdd..4c1ed2173e 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/errors/ErrorMessagesFormatBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/errors/ErrorMessagesFormatBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.errors; - import org.openecomp.core.validation.ErrorMessageCode; public class ErrorMessagesFormatBuilder { - private static final String MESSAGE_PATTERN = "[%s]: %s"; - public static String getErrorWithParameters(String error, Object... params) { - return String.format(error, params); - } - /** - * Formatted message with error code. - * - * @param messageCode error code. - * @param errorMessage error message. - * @param params parameters used in formatting message. - * @return formatted message string. - */ - public static String getErrorWithParameters(ErrorMessageCode messageCode, - String errorMessage, String... params) { - String message = getErrorWithParameters(errorMessage, params); + private static final String MESSAGE_PATTERN = "[%s]: %s"; - return ( null != messageCode && null != messageCode.getMessageCode() ) ? - String.format(MESSAGE_PATTERN, messageCode.getMessageCode(), message) : message; - } + public static String getErrorWithParameters(String error, Object... params) { + return String.format(error, params); + } + /** + * Formatted message with error code. + * + * @param messageCode error code. + * @param errorMessage error message. + * @param params parameters used in formatting message. + * @return formatted message string. + */ + public static String getErrorWithParameters(ErrorMessageCode messageCode, String errorMessage, String... params) { + String message = getErrorWithParameters(errorMessage, params); + return (null != messageCode && null != messageCode.getMessageCode()) ? String.format(MESSAGE_PATTERN, messageCode.getMessageCode(), message) + : message; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/factory/ValidationManagerFactory.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/factory/ValidationManagerFactory.java index 36beab10cf..3aac95f733 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/factory/ValidationManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/factory/ValidationManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.core.validation.api.ValidationManager; - public abstract class ValidationManagerFactory extends AbstractComponentFactory { - public static ValidationManagerFactory getInstance() { - return AbstractFactory.getInstance(ValidationManagerFactory.class); - } + public static ValidationManagerFactory getInstance() { + return AbstractFactory.getInstance(ValidationManagerFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/FileValidationContext.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/FileValidationContext.java index 3bc760c805..9b8e53744c 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/FileValidationContext.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/FileValidationContext.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,35 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.types; - import java.io.ByteArrayInputStream; import java.io.InputStream; - public class FileValidationContext { - private String fileName; - private MessageContainer messageContainer = new MessageContainer(); - private byte[] content; - public FileValidationContext(String fileName, byte[] fileContent) { - this.fileName = fileName; - this.content = fileContent; - } + private String fileName; + private MessageContainer messageContainer = new MessageContainer(); + private byte[] content; + public FileValidationContext(String fileName, byte[] fileContent) { + this.fileName = fileName; + this.content = fileContent; + } - MessageContainer getMessageContainer() { - return this.messageContainer; - } + MessageContainer getMessageContainer() { + return this.messageContainer; + } - public InputStream getContent() { - return new ByteArrayInputStream(content); - } + public InputStream getContent() { + return new ByteArrayInputStream(content); + } - public String getFileName() { - return this.fileName; - } + public String getFileName() { + return this.fileName; + } - public boolean isEmpty() { - return content == null || content.length == 0; - } + public boolean isEmpty() { + return content == null || content.length == 0; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java index 42ea681b1b..b5ebf11240 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java @@ -13,15 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.validation.types; -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; - import java.io.InputStream; import java.util.Collection; import java.util.HashMap; @@ -29,95 +22,89 @@ import java.util.Map; import java.util.Optional; import java.util.function.BiPredicate; import java.util.stream.Collectors; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.validation.ErrorMessageCode; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; public class GlobalValidationContext { - private static final Logger LOGGER = LoggerFactory.getLogger(GlobalValidationContext.class); - private final Map fileContextMap = new HashMap<>(); - private final Map messageContainerMap = new HashMap<>(); - private ErrorMessageCode messageCode; + private static final Logger LOGGER = LoggerFactory.getLogger(GlobalValidationContext.class); + private final Map fileContextMap = new HashMap<>(); + private final Map messageContainerMap = new HashMap<>(); + private ErrorMessageCode messageCode; - public ErrorMessageCode getMessageCode() { - return messageCode; - } - - public void setMessageCode(ErrorMessageCode messageCode) { - this.messageCode = messageCode; - } - - - /** - * Add message. - * - * @param fileName the file name - * @param level the level - * @param message the message - */ - public void addMessage(String fileName, ErrorLevel level, String message) { - - LOGGER.debug("'{}' [{}] in file '{}' ", message, level, fileName); - - if (fileContextMap.containsKey(fileName)) { - fileContextMap.get(fileName).getMessageContainer().getMessageBuilder() - .setMessage(level.toString() + ": " + message).setLevel(level).create(); - } else { - MessageContainer messageContainer; - synchronized (this) { - messageContainer = messageContainerMap.computeIfAbsent(fileName, k -> new MessageContainer()); - } - messageContainer.getMessageBuilder().setMessage(level.toString() + ": " + message) - .setLevel(level).create(); + public ErrorMessageCode getMessageCode() { + return messageCode; } - } - /** - * Gets file content. - * - * @param fileName the file name - * @return the file content - */ - public Optional getFileContent(String fileName) { - FileValidationContext fileContext = fileContextMap.get(fileName); - if (fileContext == null || fileContext.isEmpty()) { - return Optional.empty(); + public void setMessageCode(ErrorMessageCode messageCode) { + this.messageCode = messageCode; } - return Optional.of(fileContext.getContent()); - } - public void addFileContext(String fileName, byte[] fileContent) { - fileContextMap.put(fileName, new FileValidationContext(fileName, fileContent)); - } + /** + * Add message. + * + * @param fileName the file name + * @param level the level + * @param message the message + */ + public void addMessage(String fileName, ErrorLevel level, String message) { + LOGGER.debug("'{}' [{}] in file '{}' ", message, level, fileName); + if (fileContextMap.containsKey(fileName)) { + fileContextMap.get(fileName).getMessageContainer().getMessageBuilder().setMessage(level.toString() + ": " + message).setLevel(level) + .create(); + } else { + MessageContainer messageContainer; + synchronized (this) { + messageContainer = messageContainerMap.computeIfAbsent(fileName, k -> new MessageContainer()); + } + messageContainer.getMessageBuilder().setMessage(level.toString() + ": " + message).setLevel(level).create(); + } + } - /** - * Gets context message containers. - * - * @return the context message containers - */ - public Map getContextMessageContainers() { + /** + * Gets file content. + * + * @param fileName the file name + * @return the file content + */ + public Optional getFileContent(String fileName) { + FileValidationContext fileContext = fileContextMap.get(fileName); + if (fileContext == null || fileContext.isEmpty()) { + return Optional.empty(); + } + return Optional.of(fileContext.getContent()); + } - Map contextMessageContainer = new HashMap<>(); - fileContextMap.entrySet().stream().filter(entry -> CollectionUtils - .isNotEmpty(entry.getValue().getMessageContainer().getErrorMessageList())).forEach( - entry -> contextMessageContainer.put( - entry.getKey(), entry.getValue() - .getMessageContainer())); - messageContainerMap.entrySet().stream() - .filter(entry -> CollectionUtils.isNotEmpty(entry.getValue().getErrorMessageList())) - .forEach(entry -> contextMessageContainer.put(entry.getKey(), entry.getValue())); - return contextMessageContainer; - } + public void addFileContext(String fileName, byte[] fileContent) { + fileContextMap.put(fileName, new FileValidationContext(fileName, fileContent)); + } - public Map getFileContextMap() { - return fileContextMap; - } + /** + * Gets context message containers. + * + * @return the context message containers + */ + public Map getContextMessageContainers() { + Map contextMessageContainer = new HashMap<>(); + fileContextMap.entrySet().stream().filter(entry -> CollectionUtils.isNotEmpty(entry.getValue().getMessageContainer().getErrorMessageList())) + .forEach(entry -> contextMessageContainer.put(entry.getKey(), entry.getValue().getMessageContainer())); + messageContainerMap.entrySet().stream().filter(entry -> CollectionUtils.isNotEmpty(entry.getValue().getErrorMessageList())) + .forEach(entry -> contextMessageContainer.put(entry.getKey(), entry.getValue())); + return contextMessageContainer; + } - public Collection files(BiPredicate func) { - return fileContextMap.keySet().stream().filter(t -> func.test(t, this)) - .collect(Collectors.toList()); - } + public Map getFileContextMap() { + return fileContextMap; + } - public Collection getFiles() { - return this.getFileContextMap().keySet(); - } + public Collection files(BiPredicate func) { + return fileContextMap.keySet().stream().filter(t -> func.test(t, this)).collect(Collectors.toList()); + } + public Collection getFiles() { + return this.getFileContextMap().keySet(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/MessageContainer.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/MessageContainer.java index eb57672315..bbe6247b76 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/MessageContainer.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/MessageContainer.java @@ -17,15 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.types; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public class MessageContainer { @@ -40,16 +38,13 @@ public class MessageContainer { } /** - * Gets error message list by level. - * Only this level, not this level and above + * Gets error message list by level. Only this level, not this level and above * * @param level the level * @return the error message list by level */ public List getErrorMessageListByLevel(ErrorLevel level) { - return errorMessageList.stream() - .filter(message -> message.getLevel().equals(level)) - .collect(Collectors.toList()); + return errorMessageList.stream().filter(message -> message.getLevel().equals(level)).collect(Collectors.toList()); } public class MessageBuilder { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/util/MessageContainerUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/util/MessageContainerUtil.java index aab83837b8..e5ee3f2e95 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/util/MessageContainerUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/util/MessageContainerUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,69 +17,56 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.validation.util; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public class MessageContainerUtil { - /** - * Gets message by level. - * - * @param level the level - * @param messages the messages - * @return the message by level - */ - public static Map> getMessageByLevel(ErrorLevel level, - Map> - messages) { - if (messages == null) { - return null; - } - Map> filteredMessages = new HashMap<>(); - messages.entrySet().forEach( - entry -> entry.getValue().stream().filter(message -> message.getLevel().equals(level)) - .forEach(message -> addMessage(entry.getKey(), message, filteredMessages - ))); - return filteredMessages; - } - private static void addMessage(String fileName, ErrorMessage message, - Map> messages) { - List messageList = messages.computeIfAbsent(fileName, k -> new ArrayList<>()); - messageList.add(message); - } + /** + * Gets message by level. + * + * @param level the level + * @param messages the messages + * @return the message by level + */ + public static Map> getMessageByLevel(ErrorLevel level, Map> messages) { + if (messages == null) { + return null; + } + Map> filteredMessages = new HashMap<>(); + messages.entrySet().forEach(entry -> entry.getValue().stream().filter(message -> message.getLevel().equals(level)) + .forEach(message -> addMessage(entry.getKey(), message, filteredMessages))); + return filteredMessages; + } - public static String getErrorMessagesListAsString(Map> messages) { - StringBuilder concatErrorMessage = new StringBuilder(); + private static void addMessage(String fileName, ErrorMessage message, Map> messages) { + List messageList = messages.computeIfAbsent(fileName, k -> new ArrayList<>()); + messageList.add(message); + } - for (Map.Entry> errorMessageEntry : messages.entrySet()) { - appendErrorMessageAsString(concatErrorMessage, errorMessageEntry.getKey(), - errorMessageEntry.getValue()); + public static String getErrorMessagesListAsString(Map> messages) { + StringBuilder concatErrorMessage = new StringBuilder(); + for (Map.Entry> errorMessageEntry : messages.entrySet()) { + appendErrorMessageAsString(concatErrorMessage, errorMessageEntry.getKey(), errorMessageEntry.getValue()); + } + return concatErrorMessage.toString(); } - return concatErrorMessage.toString(); - } - private static void appendErrorMessageAsString(StringBuilder concatErrorMessage, - String fileName, - List errorMessageList) { - for (ErrorMessage errorMessage : errorMessageList) { - addErrorMessage(concatErrorMessage, fileName, errorMessage); + private static void appendErrorMessageAsString(StringBuilder concatErrorMessage, String fileName, List errorMessageList) { + for (ErrorMessage errorMessage : errorMessageList) { + addErrorMessage(concatErrorMessage, fileName, errorMessage); + } } - } - private static void addErrorMessage(StringBuilder concatErrorMessage, - String fileName, - ErrorMessage errorMessage) { - concatErrorMessage.append(fileName).append(" : "); - concatErrorMessage.append(errorMessage.getMessage()); - concatErrorMessage.append("\n"); - } + private static void addErrorMessage(StringBuilder concatErrorMessage, String fileName, ErrorMessage errorMessage) { + concatErrorMessage.append(fileName).append(" : "); + concatErrorMessage.append(errorMessage.getMessage()); + concatErrorMessage.append("\n"); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerFactoryImpl.java index 87d4dd8118..4605f0251a 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.impl; - import org.openecomp.core.validation.api.ValidationManager; import org.openecomp.core.validation.factory.ValidationManagerFactory; - public class ValidationManagerFactoryImpl extends ValidationManagerFactory { - @Override - public ValidationManager createInterface() { - return new ValidationManagerImpl(); - } + @Override + public ValidationManager createInterface() { + return new ValidationManagerImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java index a25b8ae88f..9937bfb413 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.impl; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.validation.api.ValidationManager; import org.openecomp.core.validation.types.GlobalValidationContext; @@ -28,48 +31,40 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.services.ValidationFactory; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - public class ValidationManagerImpl implements ValidationManager { - private GlobalValidationContext globalContext; - private List validators; + private GlobalValidationContext globalContext; + private List validators; - public ValidationManagerImpl() { - globalContext = new GlobalValidationContext(); - validators = ValidationFactory.getValidators(); - } - - @Override - public Map> validate() { - for (Validator validator : validators) { - if(Objects.nonNull(validator)) { - validator.validate(globalContext); - } + public ValidationManagerImpl() { + globalContext = new GlobalValidationContext(); + validators = ValidationFactory.getValidators(); } - return convertMessageContainsToErrorMessage(globalContext.getContextMessageContainers()); - } - @Override - public void addFile(String fileName, byte[] fileContent) { - globalContext.addFileContext(fileName, fileContent); - } + @Override + public Map> validate() { + for (Validator validator : validators) { + if (Objects.nonNull(validator)) { + validator.validate(globalContext); + } + } + return convertMessageContainsToErrorMessage(globalContext.getContextMessageContainers()); + } - @Override - public void updateGlobalContext(GlobalValidationContext globalContext) { - this.globalContext = globalContext; - } + @Override + public void addFile(String fileName, byte[] fileContent) { + globalContext.addFileContext(fileName, fileContent); + } - private Map> convertMessageContainsToErrorMessage( - Map contextMessageContainers) { - Map> errors = new HashMap<>(); - contextMessageContainers.entrySet().stream() - .filter(entry -> CollectionUtils.isNotEmpty(entry.getValue().getErrorMessageList())) - .forEach(entry -> errors.put(entry.getKey(), entry.getValue().getErrorMessageList())); - return errors; - } + @Override + public void updateGlobalContext(GlobalValidationContext globalContext) { + this.globalContext = globalContext; + } + private Map> convertMessageContainsToErrorMessage(Map contextMessageContainers) { + Map> errors = new HashMap<>(); + contextMessageContainers.entrySet().stream().filter(entry -> CollectionUtils.isNotEmpty(entry.getValue().getErrorMessageList())) + .forEach(entry -> errors.put(entry.getKey(), entry.getValue().getErrorMessageList())); + return errors; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/services/ValidationFactory.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/services/ValidationFactory.java index a6c25fbec6..112f6d2f87 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/services/ValidationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/services/ValidationFactory.java @@ -19,6 +19,10 @@ */ package org.openecomp.sdc.validation.services; +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.CollectionUtils; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; @@ -29,48 +33,37 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.type.ConfigConstants; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public class ValidationFactory { - private static final List validators = new ArrayList<>(); - private static Map validationImplMap; - private static Logger logger = - (Logger) LoggerFactory.getLogger(ValidationFactory.class); - private static File file; + private static final List validators = new ArrayList<>(); + private static Map validationImplMap; + private static Logger logger = (Logger) LoggerFactory.getLogger(ValidationFactory.class); + private static File file; - static { - Configuration config = ConfigurationManager.lookup(); - validationImplMap = config.populateMap(ConfigConstants.Namespace, - ConfigConstants.Validator_Impl_Key, ImplementationConfiguration.class); - validationImplMap.putAll(config.populateMap(ConfigConstants.Mandatory_Namespace, - ConfigConstants.Validator_Impl_Key, ImplementationConfiguration.class)); - } - - /** - * Initialize a validator. - */ - public static List getValidators() { - synchronized (validators) { - if (CollectionUtils.isEmpty(validators)) { - validationImplMap.values().stream() - .filter(implementationConfiguration -> implementationConfiguration - .isEnable()).forEachOrdered(implementationConfiguration -> validators.add - (cerateValidatorImpl(implementationConfiguration))); - } + static { + Configuration config = ConfigurationManager.lookup(); + validationImplMap = config.populateMap(ConfigConstants.Namespace, ConfigConstants.Validator_Impl_Key, ImplementationConfiguration.class); + validationImplMap + .putAll(config.populateMap(ConfigConstants.Mandatory_Namespace, ConfigConstants.Validator_Impl_Key, ImplementationConfiguration.class)); } - return validators; - } - private static Validator cerateValidatorImpl(ImplementationConfiguration validatorConf) { - Validator validator = - CommonMethods.newInstance(validatorConf.getImplementationClass(), Validator.class); - validator.init(validatorConf.getProperties()); + /** + * Initialize a validator. + */ + public static List getValidators() { + synchronized (validators) { + if (CollectionUtils.isEmpty(validators)) { + validationImplMap.values().stream().filter(implementationConfiguration -> implementationConfiguration.isEnable()) + .forEachOrdered(implementationConfiguration -> validators.add(cerateValidatorImpl(implementationConfiguration))); + } + } + return validators; + } - logger.debug("created validator" + validatorConf.getImplementationClass()); - return validator; - } + private static Validator cerateValidatorImpl(ImplementationConfiguration validatorConf) { + Validator validator = CommonMethods.newInstance(validatorConf.getImplementationClass(), Validator.class); + validator.init(validatorConf.getProperties()); + logger.debug("created validator" + validatorConf.getImplementationClass()); + return validator; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java index 6f647bf04b..3a0485cbd5 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java @@ -13,9 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.util; +import java.io.InputStream; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -33,333 +41,251 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.impl.validators.HeatValidator; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; -import java.io.InputStream; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - - public class HeatValidationService { - private static final Logger LOGGER = LoggerFactory.getLogger(HeatValidator.class); - private static final String NO_CONTENT_IN_FILE_MSG = "The file ' %s ' has no content"; - private HeatValidationService(){ - - } - /** - * Check artifacts existence. - * - * @param fileName the file name - * @param artifactsNames the artifacts names - * @param globalContext the global context - */ - public static void checkArtifactsExistence(String fileName, Set artifactsNames, - GlobalValidationContext globalContext) { - artifactsNames - .stream() - .filter(artifactName -> !globalContext.getFileContextMap().containsKey(artifactName)) - .forEach(artifactName -> - globalContext.addMessage(fileName, - ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - globalContext.getMessageCode(), - Messages.MISSING_ARTIFACT.getErrorMessage(), artifactName))); - } + private static final Logger LOGGER = LoggerFactory.getLogger(HeatValidator.class); + private static final String NO_CONTENT_IN_FILE_MSG = "The file ' %s ' has no content"; - /** - * Draw files loop string. - * - * @param filesInPath the files in path - * @return the string - */ - public static String drawFilesLoop(List filesInPath) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("["); - int pathSize = filesInPath.size(); - - for (int i = 0; i < pathSize; i++) { - stringBuilder.append(filesInPath.get(i)); - if (i != pathSize - 1) { - stringBuilder.append(" -- "); - } - } - if (!filesInPath.get(0).equals(filesInPath.get(pathSize - 1))) { - stringBuilder.append(" -- "); - stringBuilder.append(filesInPath.get(0)); + private HeatValidationService() { } - stringBuilder.append("]"); - - return stringBuilder.toString(); - } - - /** - * Check nested parameters. - * - * @param parentFileName the calling nested file name - * @param nestedFileName the nested file name - * @param globalContext the global context - * @param parentParameters parent parameters. - * @param nestedParameters nested parameters. - * @param nestedParametersNames nested parameter names. - */ - private static void checkNestedParameters(String parentFileName, String nestedFileName, - GlobalValidationContext globalContext, - Map parentParameters, - Map nestedParameters, - Set nestedParametersNames) { - HeatOrchestrationTemplate parentHeatOrchestrationTemplate; - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - try { - nestedHeatOrchestrationTemplate = getHeatOrchestrationTemplate(nestedFileName, globalContext); - parentHeatOrchestrationTemplate = getHeatOrchestrationTemplate(parentFileName, globalContext); - } catch (Exception exception) { - return; + /** + * Check artifacts existence. + * + * @param fileName the file name + * @param artifactsNames the artifacts names + * @param globalContext the global context + */ + public static void checkArtifactsExistence(String fileName, Set artifactsNames, GlobalValidationContext globalContext) { + artifactsNames.stream().filter(artifactName -> !globalContext.getFileContextMap().containsKey(artifactName)).forEach( + artifactName -> globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(globalContext.getMessageCode(), Messages.MISSING_ARTIFACT.getErrorMessage(), artifactName))); } - parentParameters.putAll(parentHeatOrchestrationTemplate.getParameters()); - nestedParameters.putAll(nestedHeatOrchestrationTemplate.getParameters()); - if (!nestedParameters.isEmpty()) { - nestedParametersNames.addAll(nestedHeatOrchestrationTemplate.getParameters().keySet()); + /** + * Draw files loop string. + * + * @param filesInPath the files in path + * @return the string + */ + public static String drawFilesLoop(List filesInPath) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("["); + int pathSize = filesInPath.size(); + for (int i = 0; i < pathSize; i++) { + stringBuilder.append(filesInPath.get(i)); + if (i != pathSize - 1) { + stringBuilder.append(" -- "); + } + } + if (!filesInPath.get(0).equals(filesInPath.get(pathSize - 1))) { + stringBuilder.append(" -- "); + stringBuilder.append(filesInPath.get(0)); + } + stringBuilder.append("]"); + return stringBuilder.toString(); } - } - - private static HeatOrchestrationTemplate getHeatOrchestrationTemplate(String fileName, - GlobalValidationContext globalContext) - throws Exception { - Optional fileContent = globalContext.getFileContent(fileName); - if (fileContent.isPresent()) { - return new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); - } else { - Exception exception = new Exception(String.format(NO_CONTENT_IN_FILE_MSG, fileName)); - LOGGER.error("Error while reading file : " + fileName , exception); - throw exception; + /** + * Check nested parameters. + * + * @param parentFileName the calling nested file name + * @param nestedFileName the nested file name + * @param globalContext the global context + * @param parentParameters parent parameters. + * @param nestedParameters nested parameters. + * @param nestedParametersNames nested parameter names. + */ + private static void checkNestedParameters(String parentFileName, String nestedFileName, GlobalValidationContext globalContext, + Map parentParameters, Map nestedParameters, + Set nestedParametersNames) { + HeatOrchestrationTemplate parentHeatOrchestrationTemplate; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + try { + nestedHeatOrchestrationTemplate = getHeatOrchestrationTemplate(nestedFileName, globalContext); + parentHeatOrchestrationTemplate = getHeatOrchestrationTemplate(parentFileName, globalContext); + } catch (Exception exception) { + return; + } + parentParameters.putAll(parentHeatOrchestrationTemplate.getParameters()); + nestedParameters.putAll(nestedHeatOrchestrationTemplate.getParameters()); + if (!nestedParameters.isEmpty()) { + nestedParametersNames.addAll(nestedHeatOrchestrationTemplate.getParameters().keySet()); + } } - } - - public static void checkNestedParametersNoMissingParameterInNested(String parentFileName, - String nestedFileName, - String resourceName, - Set resourceFileProperties, - GlobalValidationContext globalContext) { - Map parentParameters = new HashMap<>(); - Map nestedParameters = new HashMap<>(); - Set nestedParametersNames = new HashSet<>(); - checkNestedParameters(parentFileName, nestedFileName, globalContext, parentParameters, - nestedParameters, nestedParametersNames); - - checkNoMissingParameterInNested(parentFileName, nestedFileName, resourceName, - resourceFileProperties, nestedParametersNames, globalContext); - } - public static void checkNestedInputValuesAlignWithType(String parentFileName, - String nestedFileName, - String resourceName, Resource resource, - Optional indexVarValue, - GlobalValidationContext globalContext) { - Map parentParameters = new HashMap<>(); - Map nestedParameters = new HashMap<>(); - Set nestedParametersNames = new HashSet<>(); - checkNestedParameters(parentFileName, nestedFileName, globalContext, parentParameters, - nestedParameters, nestedParametersNames); + private static HeatOrchestrationTemplate getHeatOrchestrationTemplate(String fileName, GlobalValidationContext globalContext) throws Exception { + Optional fileContent = globalContext.getFileContent(fileName); + if (fileContent.isPresent()) { + return new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + Exception exception = new Exception(String.format(NO_CONTENT_IN_FILE_MSG, fileName)); + LOGGER.error("Error while reading file : " + fileName, exception); + throw exception; + } + } - checkNestedInputValuesAlignWithType(parentFileName, nestedFileName, - nestedParameters, resourceName, resource, indexVarValue, globalContext); - } + public static void checkNestedParametersNoMissingParameterInNested(String parentFileName, String nestedFileName, String resourceName, + Set resourceFileProperties, GlobalValidationContext globalContext) { + Map parentParameters = new HashMap<>(); + Map nestedParameters = new HashMap<>(); + Set nestedParametersNames = new HashSet<>(); + checkNestedParameters(parentFileName, nestedFileName, globalContext, parentParameters, nestedParameters, nestedParametersNames); + checkNoMissingParameterInNested(parentFileName, nestedFileName, resourceName, resourceFileProperties, nestedParametersNames, globalContext); + } - private static void checkNoMissingParameterInNested(String parentFileName, String nestedFileName, - String resourceName, - Set resourceFileProperties, - Set nestedParametersNames, - GlobalValidationContext globalContext) { - if (CollectionUtils.isNotEmpty(nestedParametersNames)) { - resourceFileProperties - .stream() - .filter(propertyName -> !nestedParametersNames.contains(propertyName)) - .forEach(propertyName -> globalContext - .addMessage(parentFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - globalContext.getMessageCode(), - Messages.MISSING_PARAMETER_IN_NESTED.getErrorMessage(), - nestedFileName, resourceName, propertyName))); + public static void checkNestedInputValuesAlignWithType(String parentFileName, String nestedFileName, String resourceName, Resource resource, + Optional indexVarValue, GlobalValidationContext globalContext) { + Map parentParameters = new HashMap<>(); + Map nestedParameters = new HashMap<>(); + Set nestedParametersNames = new HashSet<>(); + checkNestedParameters(parentFileName, nestedFileName, globalContext, parentParameters, nestedParameters, nestedParametersNames); + checkNestedInputValuesAlignWithType(parentFileName, nestedFileName, nestedParameters, resourceName, resource, indexVarValue, globalContext); } - } - private static void checkNestedInputValuesAlignWithType(String parentFileName, - String nestedFileName, - Map nestedParameters, - String resourceName, Resource resource, - Optional indexVarValue, - GlobalValidationContext globalContext) { - Map properties = resource.getProperties(); - for (Map.Entry propertyEntry : properties.entrySet()) { - String parameterName = propertyEntry.getKey(); - Object parameterInputValue = propertyEntry.getValue(); - if (parameterInputValue instanceof String) { - if (indexVarValue.isPresent() && indexVarValue.get().equals(parameterInputValue)) { - parameterInputValue = 3; //indexVarValue is actually number value in runtime + private static void checkNoMissingParameterInNested(String parentFileName, String nestedFileName, String resourceName, + Set resourceFileProperties, Set nestedParametersNames, + GlobalValidationContext globalContext) { + if (CollectionUtils.isNotEmpty(nestedParametersNames)) { + resourceFileProperties.stream().filter(propertyName -> !nestedParametersNames.contains(propertyName)).forEach( + propertyName -> globalContext.addMessage(parentFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(globalContext.getMessageCode(), Messages.MISSING_PARAMETER_IN_NESTED.getErrorMessage(), nestedFileName, + resourceName, propertyName))); } - validateStaticValueForNestedInputParameter(parentFileName, nestedFileName, resourceName, - parameterName, parameterInputValue, nestedParameters.get(parameterName), - globalContext); - } } - } - private static void validateStaticValueForNestedInputParameter(String parentFileName, - String nestedFileName, - String resourceName, - String parameterName, - Object staticValue, - Parameter parameterInNested, - GlobalValidationContext - globalContext) { - if (parameterInNested == null) { - return; - } - if (!DefinedHeatParameterTypes - .isValueIsFromGivenType(staticValue, parameterInNested.getType())) { - globalContext.addMessage(parentFileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(globalContext.getMessageCode(), - Messages.WRONG_VALUE_TYPE_ASSIGNED_NESTED_INPUT.getErrorMessage(), - resourceName, parameterName, nestedFileName)); + private static void checkNestedInputValuesAlignWithType(String parentFileName, String nestedFileName, Map nestedParameters, + String resourceName, Resource resource, Optional indexVarValue, + GlobalValidationContext globalContext) { + Map properties = resource.getProperties(); + for (Map.Entry propertyEntry : properties.entrySet()) { + String parameterName = propertyEntry.getKey(); + Object parameterInputValue = propertyEntry.getValue(); + if (parameterInputValue instanceof String) { + if (indexVarValue.isPresent() && indexVarValue.get().equals(parameterInputValue)) { + parameterInputValue = 3; //indexVarValue is actually number value in runtime + } + validateStaticValueForNestedInputParameter(parentFileName, nestedFileName, resourceName, parameterName, parameterInputValue, + nestedParameters.get(parameterName), globalContext); + } + } } - } - - /** - * Is nested loop exist in file boolean. - * - * @param callingFileName the calling file name - * @param nestedFileName the nested file name - * @param filesInLoop the files in loop - * @param globalContext the global context - * @return the boolean - */ - public static boolean isNestedLoopExistInFile(String callingFileName, String nestedFileName, - List filesInLoop, - GlobalValidationContext globalContext) { - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - try { - nestedHeatOrchestrationTemplate = getNestedHeatOrchestrationTemplate(nestedFileName, - globalContext); - } catch (Exception exception) { - LOGGER.error("Error while reading file : " + nestedFileName, exception); - LOGGER.warn("HEAT Validator will not be executed on file " + nestedFileName - + " due to illegal HEAT format"); - return false; + private static void validateStaticValueForNestedInputParameter(String parentFileName, String nestedFileName, String resourceName, + String parameterName, Object staticValue, Parameter parameterInNested, + GlobalValidationContext globalContext) { + if (parameterInNested == null) { + return; + } + if (!DefinedHeatParameterTypes.isValueIsFromGivenType(staticValue, parameterInNested.getType())) { + globalContext.addMessage(parentFileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(globalContext.getMessageCode(), Messages.WRONG_VALUE_TYPE_ASSIGNED_NESTED_INPUT.getErrorMessage(), + resourceName, parameterName, nestedFileName)); + } } - filesInLoop.add(nestedFileName); - Collection nestedResources = - nestedHeatOrchestrationTemplate.getResources() == null ? null - : nestedHeatOrchestrationTemplate.getResources().values(); - return addNestedFilesInLoopAndCheckIfNestedLoopExist(nestedResources, - callingFileName, filesInLoop, globalContext); - } - private static boolean addNestedFilesInLoopAndCheckIfNestedLoopExist( - Collection nestedResources,String callingFileName, - List filesInLoop, - GlobalValidationContext globalContext){ - if (CollectionUtils.isNotEmpty(nestedResources)) { - for (Resource resource : nestedResources) { - String resourceType = resource.getType(); - if (Objects.nonNull(resourceType) && isNestedResource(resourceType)) { - return resourceType.equals(callingFileName) || !filesInLoop.contains(resourceType) - && isNestedLoopExistInFile(callingFileName, resourceType, filesInLoop, globalContext); + /** + * Is nested loop exist in file boolean. + * + * @param callingFileName the calling file name + * @param nestedFileName the nested file name + * @param filesInLoop the files in loop + * @param globalContext the global context + * @return the boolean + */ + public static boolean isNestedLoopExistInFile(String callingFileName, String nestedFileName, List filesInLoop, + GlobalValidationContext globalContext) { + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + try { + nestedHeatOrchestrationTemplate = getNestedHeatOrchestrationTemplate(nestedFileName, globalContext); + } catch (Exception exception) { + LOGGER.error("Error while reading file : " + nestedFileName, exception); + LOGGER.warn("HEAT Validator will not be executed on file " + nestedFileName + " due to illegal HEAT format"); + return false; } - } + filesInLoop.add(nestedFileName); + Collection nestedResources = + nestedHeatOrchestrationTemplate.getResources() == null ? null : nestedHeatOrchestrationTemplate.getResources().values(); + return addNestedFilesInLoopAndCheckIfNestedLoopExist(nestedResources, callingFileName, filesInLoop, globalContext); } - return false; - } - - - - private static HeatOrchestrationTemplate getNestedHeatOrchestrationTemplate( String nestedFileName, - GlobalValidationContext globalContext) throws Exception { - Optional fileContent = globalContext.getFileContent(nestedFileName); - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - if (fileContent.isPresent()) { - nestedHeatOrchestrationTemplate = - new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); - } else { - throw new Exception(String.format(NO_CONTENT_IN_FILE_MSG, nestedFileName)); + private static boolean addNestedFilesInLoopAndCheckIfNestedLoopExist(Collection nestedResources, String callingFileName, + List filesInLoop, GlobalValidationContext globalContext) { + if (CollectionUtils.isNotEmpty(nestedResources)) { + for (Resource resource : nestedResources) { + String resourceType = resource.getType(); + if (Objects.nonNull(resourceType) && isNestedResource(resourceType)) { + return resourceType.equals(callingFileName) || !filesInLoop.contains(resourceType) && isNestedLoopExistInFile(callingFileName, + resourceType, filesInLoop, globalContext); + } + } + } + return false; } - return nestedHeatOrchestrationTemplate; - } - - public static boolean isNestedResource(String resourceType) { - return resourceType.contains(".yaml") || resourceType.contains(".yml"); - } - - /** - * Validate env content environment. - * - * @param fileName the file name - * @param envFileName the env file name - * @param globalContext the global context - * @return the environment - */ - public static Environment validateEnvContent(String fileName, String envFileName, - GlobalValidationContext globalContext) { - Environment envContent; - try { - Optional fileContent = globalContext.getFileContent(envFileName); - if (fileContent.isPresent()) { - envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class); - } else { - throw new Exception(String.format(NO_CONTENT_IN_FILE_MSG, envFileName)); - } - } catch (Exception exception) { - LOGGER.error("Error while reading env file : " + envFileName, exception); - return null; + private static HeatOrchestrationTemplate getNestedHeatOrchestrationTemplate(String nestedFileName, GlobalValidationContext globalContext) + throws Exception { + Optional fileContent = globalContext.getFileContent(nestedFileName); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + throw new Exception(String.format(NO_CONTENT_IN_FILE_MSG, nestedFileName)); + } + return nestedHeatOrchestrationTemplate; } - return envContent; - } - /** - * This method verifies whether the propertyValue contains a single parent port - * @param fileName on which the validation is currently run - * @param globalContext global validation context - * @param heatResourceValidationContext heat resource validation context - * @param propertyValue the value which is examined - * @return whether the vlan has single parent port - */ - public static boolean hasSingleParentPort(String fileName, GlobalValidationContext globalContext, - HeatResourceValidationContext heatResourceValidationContext, - Object propertyValue) { - final boolean isList = propertyValue instanceof List; - if (!isList || ((List) propertyValue).size() != 1) { - return false; + public static boolean isNestedResource(String resourceType) { + return resourceType.contains(".yaml") || resourceType.contains(".yml"); } - final Object listValue = ((List) propertyValue).get(0); - - final Set getParamValues = - HeatStructureUtil.getReferencedValuesByFunctionName(fileName, "get_param", - listValue, globalContext); + /** + * Validate env content environment. + * + * @param fileName the file name + * @param envFileName the env file name + * @param globalContext the global context + * @return the environment + */ + public static Environment validateEnvContent(String fileName, String envFileName, GlobalValidationContext globalContext) { + Environment envContent; + try { + Optional fileContent = globalContext.getFileContent(envFileName); + if (fileContent.isPresent()) { + envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class); + } else { + throw new Exception(String.format(NO_CONTENT_IN_FILE_MSG, envFileName)); + } + } catch (Exception exception) { + LOGGER.error("Error while reading env file : " + envFileName, exception); + return null; + } + return envContent; + } - return getParamValues.isEmpty() || (getParamValues.size() == 1) && - validateGetParamValueOfType(getParamValues, heatResourceValidationContext, + /** + * This method verifies whether the propertyValue contains a single parent port + * + * @param fileName on which the validation is currently run + * @param globalContext global validation context + * @param heatResourceValidationContext heat resource validation context + * @param propertyValue the value which is examined + * @return whether the vlan has single parent port + */ + public static boolean hasSingleParentPort(String fileName, GlobalValidationContext globalContext, + HeatResourceValidationContext heatResourceValidationContext, Object propertyValue) { + final boolean isList = propertyValue instanceof List; + if (!isList || ((List) propertyValue).size() != 1) { + return false; + } + final Object listValue = ((List) propertyValue).get(0); + final Set getParamValues = HeatStructureUtil.getReferencedValuesByFunctionName(fileName, "get_param", listValue, globalContext); + return getParamValues.isEmpty() || (getParamValues.size() == 1) && validateGetParamValueOfType(getParamValues, heatResourceValidationContext, DefinedHeatParameterTypes.STRING.getType()); + } - } - - - private static boolean validateGetParamValueOfType(Set values, - HeatResourceValidationContext - heatResourceValidationContext, String type) { - - return values.stream().anyMatch(e -> Objects.equals( - heatResourceValidationContext.getHeatOrchestrationTemplate().getParameters().get(e).getType(), type)); - } - + private static boolean validateGetParamValueOfType(Set values, HeatResourceValidationContext heatResourceValidationContext, String type) { + return values.stream() + .anyMatch(e -> Objects.equals(heatResourceValidationContext.getHeatOrchestrationTemplate().getParameters().get(e).getType(), type)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java index bd049b2dfb..9c33c1b97f 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.util; import org.openecomp.sdc.common.errors.Messages; @@ -21,29 +20,25 @@ import org.yaml.snakeyaml.error.MarkedYAMLException; import org.yaml.snakeyaml.parser.ParserException; public class YamlValidatorUtil { - private YamlValidatorUtil() { - - } - - public static String getParserExceptionReason(Exception exception) { - String reason = null; + private YamlValidatorUtil() { + } - if (exception.getCause() instanceof MarkedYAMLException) { - if (exception.getCause() != null) { - if (exception.getCause().getCause() instanceof ParserException) { - reason = exception.getCause().getCause().getMessage(); + public static String getParserExceptionReason(Exception exception) { + String reason = null; + if (exception.getCause() instanceof MarkedYAMLException) { + if (exception.getCause() != null) { + if (exception.getCause().getCause() instanceof ParserException) { + reason = exception.getCause().getCause().getMessage(); + } else { + reason = exception.getCause().getMessage(); + } + } + } else if (exception instanceof MarkedYAMLException) { + reason = exception.getMessage(); } else { - reason = exception.getCause().getMessage(); + reason = Messages.GENERAL_YAML_PARSER_ERROR.getErrorMessage(); } - } - } else if (exception instanceof MarkedYAMLException) { - - reason = exception.getMessage(); - - } else { - reason = Messages.GENERAL_YAML_PARSER_ERROR.getErrorMessage(); + return reason; } - return reason; - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java index 3feeea8c7b..895c5ee56e 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java @@ -12,10 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.validation.impl.validators; +import java.io.InputStream; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.ErrorMessageCode; @@ -35,135 +38,104 @@ import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.io.InputStream; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - - public class ContrailValidator implements Validator { - private static final Logger LOGGER = LoggerFactory.getLogger(ContrailValidator.class); - private static final ErrorMessageCode ERROR_CODE_CTL_1 = new ErrorMessageCode("CTL1"); - private static final ErrorMessageCode ERROR_CODE_CTL_2 = new ErrorMessageCode("CTL2"); - private static final ErrorMessageCode ERROR_CODE_CTL_3 = new ErrorMessageCode("CTL3"); - private static final ErrorMessageCode ERROR_CODE_CTL_4 = new ErrorMessageCode("CTL4"); - @Override - public void validate(GlobalValidationContext globalContext) { - ManifestContent manifestContent; - try { - manifestContent = ValidationUtil.validateManifest(globalContext); - } catch (Exception exception) { - LOGGER.error("Failed to validate manifest file", exception); - return; + private static final Logger LOGGER = LoggerFactory.getLogger(ContrailValidator.class); + private static final ErrorMessageCode ERROR_CODE_CTL_1 = new ErrorMessageCode("CTL1"); + private static final ErrorMessageCode ERROR_CODE_CTL_2 = new ErrorMessageCode("CTL2"); + private static final ErrorMessageCode ERROR_CODE_CTL_3 = new ErrorMessageCode("CTL3"); + private static final ErrorMessageCode ERROR_CODE_CTL_4 = new ErrorMessageCode("CTL4"); + + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.validateManifest(globalContext); + } catch (Exception exception) { + LOGGER.error("Failed to validate manifest file", exception); + return; + } + Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); + globalContext.getFiles().stream().filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, contrailResourcesMappingTo, globalContext)); } - Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); - - globalContext.getFiles().stream() - .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) - .forEach(fileName -> validate(fileName, - contrailResourcesMappingTo, globalContext)); - } - - private void validate(String fileName, - ContrailResourcesMappingTo contrailResourcesMappingTo, - GlobalValidationContext globalContext) { - handleContrailV1AndContrailV2ResourceMerging(fileName, contrailResourcesMappingTo, - globalContext); - validateNoContrailResourceTypeIsInUse(fileName, globalContext); - } - - - private void handleContrailV1AndContrailV2ResourceMerging(String fileName, - ContrailResourcesMappingTo contrailResourcesMappingTo, - GlobalValidationContext globalContext) { - Optional fileContrailResourcesMappingTo = - collectHeatFileContrailResources(globalContext, fileName); - fileContrailResourcesMappingTo.ifPresent(contrailResourcesMappingTo::addAll); - addContrailMergeValidationMessageToGlobalContext(globalContext, contrailResourcesMappingTo); - } - - private void addContrailMergeValidationMessageToGlobalContext( - GlobalValidationContext globalContext, - ContrailResourcesMappingTo contrailResourcesMappingTo) { - if (!MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV1Resources()) - && !MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV2Resources())) { - globalContext.addMessage( - contrailResourcesMappingTo.getContrailV1Resources().keySet().iterator().next(), - ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_CTL_2, Messages.MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES.getErrorMessage(), - contrailResourcesMappingTo.fetchContrailV1Resources(), - contrailResourcesMappingTo.fetchContrailV2Resources())); + private void validate(String fileName, ContrailResourcesMappingTo contrailResourcesMappingTo, GlobalValidationContext globalContext) { + handleContrailV1AndContrailV2ResourceMerging(fileName, contrailResourcesMappingTo, globalContext); + validateNoContrailResourceTypeIsInUse(fileName, globalContext); } - } - private Optional collectHeatFileContrailResources( - GlobalValidationContext globalContext, String fileName) { - Optional fileContent = globalContext.getFileContent(fileName); - if (!fileContent.isPresent()) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_CTL_1, Messages.INVALID_HEAT_FORMAT_REASON - .getErrorMessage(), - "The file '" + fileName + "' has no content")); - return Optional.empty(); + private void handleContrailV1AndContrailV2ResourceMerging(String fileName, ContrailResourcesMappingTo contrailResourcesMappingTo, + GlobalValidationContext globalContext) { + Optional fileContrailResourcesMappingTo = collectHeatFileContrailResources(globalContext, fileName); + fileContrailResourcesMappingTo.ifPresent(contrailResourcesMappingTo::addAll); + addContrailMergeValidationMessageToGlobalContext(globalContext, contrailResourcesMappingTo); } - return fetchContrailResourcesMapping(fileName, fileContent.get()); - } - private Optional fetchContrailResourcesMapping(String fileName, - InputStream fileContent ) { - ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); - HeatOrchestrationTemplate heatOrchestrationTemplate; - try { - heatOrchestrationTemplate = - new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class); - } catch (Exception ignored) { - LOGGER.error("Invalid file content : " + fileContent, ignored); - // the HeatValidator should handle file that is failing to parse - return Optional.empty(); - } - if( !MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { - heatOrchestrationTemplate.getResources().entrySet() - .forEach(entry -> { - if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { - contrailResourcesMappingTo.addContrailV1Resource(fileName, entry.getKey()); - } else if (entry.getValue().getType() - .startsWith(HeatConstants.CONTRAIL_V2_RESOURCE_PREFIX)) { - contrailResourcesMappingTo.addContrailV2Resource(fileName, entry.getKey()); - } - }); + private void addContrailMergeValidationMessageToGlobalContext(GlobalValidationContext globalContext, + ContrailResourcesMappingTo contrailResourcesMappingTo) { + if (!MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV1Resources()) && !MapUtils + .isEmpty(contrailResourcesMappingTo.getContrailV2Resources())) { + globalContext.addMessage(contrailResourcesMappingTo.getContrailV1Resources().keySet().iterator().next(), ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_CTL_2, Messages.MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES.getErrorMessage(), + contrailResourcesMappingTo.fetchContrailV1Resources(), contrailResourcesMappingTo.fetchContrailV2Resources())); + } } - return Optional.of(contrailResourcesMappingTo); - } - - private void validateNoContrailResourceTypeIsInUse(String fileName, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_CTL_4); - HeatOrchestrationTemplate heatOrchestrationTemplate = - ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + private Optional collectHeatFileContrailResources(GlobalValidationContext globalContext, String fileName) { + Optional fileContent = globalContext.getFileContent(fileName); + if (!fileContent.isPresent()) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_CTL_1, Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + "The file '" + fileName + "' has no content")); + return Optional.empty(); + } + return fetchContrailResourcesMapping(fileName, fileContent.get()); + } - if (heatOrchestrationTemplate == null) { - return; + private Optional fetchContrailResourcesMapping(String fileName, InputStream fileContent) { + ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); + HeatOrchestrationTemplate heatOrchestrationTemplate; + try { + heatOrchestrationTemplate = new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class); + } catch (Exception ignored) { + LOGGER.error("Invalid file content : " + fileContent, ignored); + // the HeatValidator should handle file that is failing to parse + return Optional.empty(); + } + if (!MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + heatOrchestrationTemplate.getResources().entrySet().forEach(entry -> { + if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { + contrailResourcesMappingTo.addContrailV1Resource(fileName, entry.getKey()); + } else if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_V2_RESOURCE_PREFIX)) { + contrailResourcesMappingTo.addContrailV2Resource(fileName, entry.getKey()); + } + }); + } + return Optional.of(contrailResourcesMappingTo); } - validateResourcePrefix(fileName, globalContext, heatOrchestrationTemplate); - } - private void validateResourcePrefix(String fileName, GlobalValidationContext globalContext, - HeatOrchestrationTemplate heatOrchestrationTemplate) { - Map resourcesMap = heatOrchestrationTemplate.getResources(); - if(!MapUtils.isEmpty(resourcesMap)) { - for (Map.Entry resourceEntry : resourcesMap.entrySet()) { - String type = resourceEntry.getValue().getType(); - if (Objects.nonNull(type) && type.startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_CTL_3, Messages.CONTRAIL_2_IN_USE.getErrorMessage(), - resourceEntry.getKey())); + private void validateNoContrailResourceTypeIsInUse(String fileName, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_CTL_4); + HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; } - } + validateResourcePrefix(fileName, globalContext, heatOrchestrationTemplate); } - } + private void validateResourcePrefix(String fileName, GlobalValidationContext globalContext, HeatOrchestrationTemplate heatOrchestrationTemplate) { + Map resourcesMap = heatOrchestrationTemplate.getResources(); + if (!MapUtils.isEmpty(resourcesMap)) { + for (Map.Entry resourceEntry : resourcesMap.entrySet()) { + String type = resourceEntry.getValue().getType(); + if (Objects.nonNull(type) && type.startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_CTL_3, Messages.CONTRAIL_2_IN_USE.getErrorMessage(), resourceEntry.getKey())); + } + } + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/FileExtensionUtils.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/FileExtensionUtils.java index c4215c9783..9915f91acf 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/FileExtensionUtils.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/FileExtensionUtils.java @@ -23,16 +23,10 @@ import java.util.Set; class FileExtensionUtils { - private static final Set VALID_YAML_EXTENSIONS = Set.of( - ".yaml", - ".yml", - ".env" - ); + private static final Set VALID_YAML_EXTENSIONS = Set.of(".yaml", ".yml", ".env"); static boolean isYaml(String fileName) { String fileNameLower = fileName.toLowerCase(); - return FileExtensionUtils.VALID_YAML_EXTENSIONS.stream() - .anyMatch(fileNameLower::endsWith); + return FileExtensionUtils.VALID_YAML_EXTENSIONS.stream().anyMatch(fileNameLower::endsWith); } - } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java index 5ce9aa7aa5..9c8c10a7fe 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java @@ -12,10 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.validation.impl.validators; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -32,103 +35,76 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.HashSet; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - public class ForbiddenResourceGuideLineValidator implements Validator { - private static Set forbiddenResources = new HashSet<>(); - private static final ErrorMessageCode ERROR_CODE_FRG_1 = new ErrorMessageCode("FRG1"); - private static final ErrorMessageCode ERROR_CODE_FRG_2 = new ErrorMessageCode("FRG2"); - private static final ErrorMessageCode ERROR_CODE_FRG_3 = new ErrorMessageCode("FRG3"); - - private static final Logger LOGGER = LoggerFactory - .getLogger(ForbiddenResourceGuideLineValidator.class); - - @Override - public void init(Map properties) { - Map> forbiddenResourcesMap = - (Map>) properties.get("forbiddenResourceTypes"); - - forbiddenResourcesMap.entrySet().stream() - .filter(entry -> isResourceEnabled(entry.getValue().get("enable"))) - .forEach(entry -> forbiddenResources.add(entry.getKey())); - } - private boolean isResourceEnabled(Object enableValue) { - if (Objects.isNull(enableValue)) { - return true; + private static final ErrorMessageCode ERROR_CODE_FRG_1 = new ErrorMessageCode("FRG1"); + private static final ErrorMessageCode ERROR_CODE_FRG_2 = new ErrorMessageCode("FRG2"); + private static final ErrorMessageCode ERROR_CODE_FRG_3 = new ErrorMessageCode("FRG3"); + private static final Logger LOGGER = LoggerFactory.getLogger(ForbiddenResourceGuideLineValidator.class); + private static Set forbiddenResources = new HashSet<>(); + + @Override + public void init(Map properties) { + Map> forbiddenResourcesMap = (Map>) properties.get("forbiddenResourceTypes"); + forbiddenResourcesMap.entrySet().stream().filter(entry -> isResourceEnabled(entry.getValue().get("enable"))) + .forEach(entry -> forbiddenResources.add(entry.getKey())); } - if (enableValue instanceof Boolean) { - return (Boolean)enableValue; - } - - return Boolean.valueOf((String) enableValue); - } - - - @Override - public void validate(GlobalValidationContext globalContext) { - ManifestContent manifestContent; - try { - manifestContent = ValidationUtil.validateManifest(globalContext); - } catch (Exception exception) { - LOGGER.error("Failed to validate manifest file", exception); - return; + private boolean isResourceEnabled(Object enableValue) { + if (Objects.isNull(enableValue)) { + return true; + } + if (enableValue instanceof Boolean) { + return (Boolean) enableValue; + } + return Boolean.valueOf((String) enableValue); } - Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - - globalContext.getFiles().stream() - .filter(fileName -> FileData - .isHeatFile(fileTypeMap.get(fileName))) - .forEach(fileName -> validate(fileName, globalContext)); - } - - private void validate(String fileName, GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_FRG_3); - HeatOrchestrationTemplate - heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition( - fileName, globalContext); - if (heatOrchestrationTemplate == null) { - return; + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.validateManifest(globalContext); + } catch (Exception exception) { + LOGGER.error("Failed to validate manifest file", exception); + return; + } + Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + globalContext.getFiles().stream().filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, globalContext)); } - validateResourceTypeIsForbidden(fileName, heatOrchestrationTemplate, globalContext); - } - - private void validateResourceTypeIsForbidden(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map resourcesMap = heatOrchestrationTemplate.getResources(); - if (MapUtils.isEmpty(resourcesMap)) { - return; + private void validate(String fileName, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_FRG_3); + HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; + } + validateResourceTypeIsForbidden(fileName, heatOrchestrationTemplate, globalContext); } - for (Map.Entry resourceEntry : resourcesMap.entrySet()) { - String resourceType = resourceEntry.getValue().getType(); - if (Objects.isNull(resourceType)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_FRG_1, - Messages.INVALID_RESOURCE_TYPE.getErrorMessage(),"null", - resourceEntry.getKey())); - } else { - if (isResourceForbidden(resourceType)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_FRG_2, Messages.FORBIDDEN_RESOURCE_IN_USE - .getErrorMessage(), - resourceType, resourceEntry.getKey())); + private void validateResourceTypeIsForbidden(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map resourcesMap = heatOrchestrationTemplate.getResources(); + if (MapUtils.isEmpty(resourcesMap)) { + return; + } + for (Map.Entry resourceEntry : resourcesMap.entrySet()) { + String resourceType = resourceEntry.getValue().getType(); + if (Objects.isNull(resourceType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_FRG_1, Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", resourceEntry.getKey())); + } else { + if (isResourceForbidden(resourceType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_FRG_2, Messages.FORBIDDEN_RESOURCE_IN_USE.getErrorMessage(), resourceType, + resourceEntry.getKey())); + } + } } - } } - } - private boolean isResourceForbidden(String resourceType) { - return forbiddenResources.contains(resourceType); - } + private boolean isResourceForbidden(String resourceType) { + return forbiddenResources.contains(resourceType); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/GlobalContextUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/GlobalContextUtil.java index 4467bd1311..0e199cc472 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/GlobalContextUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/GlobalContextUtil.java @@ -17,43 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.impl.validators; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.Map; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - class GlobalContextUtil { - private GlobalContextUtil() {} + private GlobalContextUtil() { + } static Set findPmDictionaryFiles(GlobalValidationContext globalContext) { if (isManifestMissing(globalContext)) { return Set.of(); } - Map filesWithTypes = readAllFilesWithTypes(globalContext); return filterPmDictionaryFiles(filesWithTypes); } private static boolean isManifestMissing(GlobalValidationContext globalContext) { - return globalContext.getFileContent("MANIFEST.json") - .isEmpty(); + return globalContext.getFileContent("MANIFEST.json").isEmpty(); } private static Set filterPmDictionaryFiles(Map filesWithTypes) { - return filesWithTypes.entrySet().stream() - .filter(isPmDictionaryType()) - .map(Map.Entry::getKey) - .collect(Collectors.toSet()); + return filesWithTypes.entrySet().stream().filter(isPmDictionaryType()).map(Map.Entry::getKey).collect(Collectors.toSet()); } private static Map readAllFilesWithTypes(GlobalValidationContext globalContext) { @@ -62,7 +56,6 @@ class GlobalContextUtil { } private static Predicate> isPmDictionaryType() { - return entry -> entry.getValue() - .equals(FileData.Type.PM_DICTIONARY); + return entry -> entry.getValue().equals(FileData.Type.PM_DICTIONARY); } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java index e445477498..abdb65670e 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators; import java.util.ArrayList; @@ -24,7 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; - import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Output; @@ -39,210 +37,147 @@ import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; public class HeatResourceValidator extends ResourceBaseValidator { - private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); - private static final String GET_ATTR = "get_attr"; - - @Override - public void init(Map properties) { - super.init((Map) properties.get(ConfigConstants.Resource_Base_Validator)); - } - - @Override - public ValidationContext createValidationContext(String fileName, - String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map resourcesMap = - heatOrchestrationTemplate.getResources() == null ? new HashMap<>() - : heatOrchestrationTemplate.getResources(); - - Map outputMap = heatOrchestrationTemplate.getOutputs() == null ? new HashMap<>() - : heatOrchestrationTemplate.getOutputs(); - - Map>>> - typeToPointingResourcesMap = new HashMap<>(); - - initTypeRelationsMap (fileName, resourcesMap, outputMap, - typeToPointingResourcesMap, globalContext); - - return new HeatResourceValidationContext (heatOrchestrationTemplate, typeToPointingResourcesMap, - envFileName ); - } - - private void initTypeRelationsMap (String fileName, - Map resourceMap, - Map outputMap, - Map>>> typeToPointingResourcesMap, - GlobalValidationContext globalContext ) { - initTypeRelationsMapFromResourcesMap (fileName, resourceMap, - typeToPointingResourcesMap, globalContext); - - initTypeRelationsMapFromOutputsMap (fileName, resourceMap, outputMap, - typeToPointingResourcesMap, globalContext); - } - - private void initTypeRelationsMapFromOutputsMap (String fileName, - Map resourceMap, - Map outputMap, - Map>>> typeToPointingResourcesMap, - GlobalValidationContext globalContext ) { - for (Map.Entry outputEntry : outputMap.entrySet()) { - Object outputValue = outputEntry.getValue().getValue(); - Set referencedResources = HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), outputValue, globalContext); - - updateRelationsMapWithOutputsReferences (outputEntry, resourceMap, referencedResources, typeToPointingResourcesMap); - } - } - private void updateRelationsMapWithOutputsReferences (Map.Entry outputEntry, - Map resourceMap, - Set referencedResources, - Map>>> typeToPointingResourcesMap ) { + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); + private static final String GET_ATTR = "get_attr"; - for (String pointedResourceName : referencedResources) { - Resource pointedResource = resourceMap.get(pointedResourceName); + @Override + public void init(Map properties) { + super.init((Map) properties.get(ConfigConstants.Resource_Base_Validator)); + } - if (Objects.nonNull(pointedResource)) { - initCurrentResourceTypeInMap(pointedResourceName, pointedResource.getType(), - "output", typeToPointingResourcesMap); + @Override + public ValidationContext createValidationContext(String fileName, String envFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map resourcesMap = + heatOrchestrationTemplate.getResources() == null ? new HashMap<>() : heatOrchestrationTemplate.getResources(); + Map outputMap = heatOrchestrationTemplate.getOutputs() == null ? new HashMap<>() : heatOrchestrationTemplate.getOutputs(); + Map>>> typeToPointingResourcesMap = new HashMap<>(); + initTypeRelationsMap(fileName, resourcesMap, outputMap, typeToPointingResourcesMap, globalContext); + return new HeatResourceValidationContext(heatOrchestrationTemplate, typeToPointingResourcesMap, envFileName); + } - typeToPointingResourcesMap - .get(pointedResource.getType()).get(pointedResourceName) - .get("output").add(outputEntry.getKey()); - } + private void initTypeRelationsMap(String fileName, Map resourceMap, Map outputMap, + Map>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + initTypeRelationsMapFromResourcesMap(fileName, resourceMap, typeToPointingResourcesMap, globalContext); + initTypeRelationsMapFromOutputsMap(fileName, resourceMap, outputMap, typeToPointingResourcesMap, globalContext); } - } - private void initTypeRelationsMapFromResourcesMap(String fileName, - Map resourceMap, + private void initTypeRelationsMapFromOutputsMap(String fileName, Map resourceMap, Map outputMap, Map>>> typeToPointingResourcesMap, GlobalValidationContext globalContext) { - for (Map.Entry resourceEntry : resourceMap.entrySet()) { - Resource pointingResource = resourceEntry.getValue(); - Map properties = - pointingResource.getProperties() == null ? new HashMap<>() - : pointingResource.getProperties(); - - Set referencedResourcesByGetResource = - getResourcesIdsPointedByCurrentResource(fileName, ResourceReferenceFunctions.GET_RESOURCE, - properties, globalContext); - - Set referencedResourcesByGetAttr = - handleGetAttrBetweenResources(properties); - - referencedResourcesByGetResource.addAll(referencedResourcesByGetAttr); - - updateRelationsMapWithCurrentResourceReferences - (resourceMap, resourceEntry, referencedResourcesByGetResource, typeToPointingResourcesMap); + for (Map.Entry outputEntry : outputMap.entrySet()) { + Object outputValue = outputEntry.getValue().getValue(); + Set referencedResources = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions.GET_RESOURCE.getFunction(), outputValue, globalContext); + updateRelationsMapWithOutputsReferences(outputEntry, resourceMap, referencedResources, typeToPointingResourcesMap); + } } - } - - private void updateRelationsMapWithCurrentResourceReferences(Map resourceMap, - Map.Entry currentResourceEntry, - Set referencedResourcesFromCurrentResource, - Map>>> typeToPointingResourcesMap) { - - for (String pointedResourceName : referencedResourcesFromCurrentResource) { - Resource pointedResource = resourceMap.get(pointedResourceName); - if (Objects.nonNull(pointedResource)) { - String pointedResourceType = pointedResource.getType(); - updateMapWithRelationsBetweenResources (pointedResourceName, pointedResourceType, - currentResourceEntry, typeToPointingResourcesMap); - } + private void updateRelationsMapWithOutputsReferences(Map.Entry outputEntry, Map resourceMap, + Set referencedResources, + Map>>> typeToPointingResourcesMap) { + for (String pointedResourceName : referencedResources) { + Resource pointedResource = resourceMap.get(pointedResourceName); + if (Objects.nonNull(pointedResource)) { + initCurrentResourceTypeInMap(pointedResourceName, pointedResource.getType(), "output", typeToPointingResourcesMap); + typeToPointingResourcesMap.get(pointedResource.getType()).get(pointedResourceName).get("output").add(outputEntry.getKey()); + } + } } - } - - private void updateMapWithRelationsBetweenResources(String pointedResourceName, - String pointedResourceType, - Map.Entry currentResourceEntry, - Map>>> typeToPointingResourcesMap) { - - initCurrentResourceTypeInMap(pointedResourceName, pointedResourceType, - currentResourceEntry.getValue().getType(), typeToPointingResourcesMap); - - typeToPointingResourcesMap.get(pointedResourceType).get(pointedResourceName) - .get(currentResourceEntry.getValue().getType()).add(currentResourceEntry.getKey()); - } - - private void initCurrentResourceTypeInMap(String resourceName, String resourceType, - String pointingResourceType, - Map>>> typeToPointingResourcesMap) { - - typeToPointingResourcesMap.putIfAbsent(resourceType, new HashMap<>()); - typeToPointingResourcesMap.get(resourceType).putIfAbsent(resourceName, new HashMap<>()); - typeToPointingResourcesMap.get(resourceType).get(resourceName) - .putIfAbsent (pointingResourceType, new ArrayList<>()); - } - - private Set handleGetAttrBetweenResources (Map properties) { - Set referencedResourcesByGetAttr = new HashSet<>(); - for (Map.Entry proprtyEntry : properties.entrySet()) { - referencedResourcesByGetAttr.addAll(getGetAttrReferencesInCaseOfContrail(proprtyEntry - .getValue())); + + private void initTypeRelationsMapFromResourcesMap(String fileName, Map resourceMap, + Map>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + for (Map.Entry resourceEntry : resourceMap.entrySet()) { + Resource pointingResource = resourceEntry.getValue(); + Map properties = pointingResource.getProperties() == null ? new HashMap<>() : pointingResource.getProperties(); + Set referencedResourcesByGetResource = getResourcesIdsPointedByCurrentResource(fileName, ResourceReferenceFunctions.GET_RESOURCE, + properties, globalContext); + Set referencedResourcesByGetAttr = handleGetAttrBetweenResources(properties); + referencedResourcesByGetResource.addAll(referencedResourcesByGetAttr); + updateRelationsMapWithCurrentResourceReferences(resourceMap, resourceEntry, referencedResourcesByGetResource, typeToPointingResourcesMap); + } } - return referencedResourcesByGetAttr; - } + private void updateRelationsMapWithCurrentResourceReferences(Map resourceMap, Map.Entry currentResourceEntry, + Set referencedResourcesFromCurrentResource, + Map>>> typeToPointingResourcesMap) { + for (String pointedResourceName : referencedResourcesFromCurrentResource) { + Resource pointedResource = resourceMap.get(pointedResourceName); + if (Objects.nonNull(pointedResource)) { + String pointedResourceType = pointedResource.getType(); + updateMapWithRelationsBetweenResources(pointedResourceName, pointedResourceType, currentResourceEntry, typeToPointingResourcesMap); + } + } + } + private void updateMapWithRelationsBetweenResources(String pointedResourceName, String pointedResourceType, + Map.Entry currentResourceEntry, + Map>>> typeToPointingResourcesMap) { + initCurrentResourceTypeInMap(pointedResourceName, pointedResourceType, currentResourceEntry.getValue().getType(), typeToPointingResourcesMap); + typeToPointingResourcesMap.get(pointedResourceType).get(pointedResourceName).get(currentResourceEntry.getValue().getType()) + .add(currentResourceEntry.getKey()); + } - private Set getGetAttrReferencesInCaseOfContrail(Object propertyValue) { - Set getAttrReferences = new HashSet<>(); + private void initCurrentResourceTypeInMap(String resourceName, String resourceType, String pointingResourceType, + Map>>> typeToPointingResourcesMap) { + typeToPointingResourcesMap.putIfAbsent(resourceType, new HashMap<>()); + typeToPointingResourcesMap.get(resourceType).putIfAbsent(resourceName, new HashMap<>()); + typeToPointingResourcesMap.get(resourceType).get(resourceName).putIfAbsent(pointingResourceType, new ArrayList<>()); + } - if (propertyValue instanceof Map) { - if (((Map) propertyValue).containsKey(GET_ATTR)) { - if (validatePropertyValueAndAddAttrReferencesInSet(propertyValue, getAttrReferences)) { - return getAttrReferences; + private Set handleGetAttrBetweenResources(Map properties) { + Set referencedResourcesByGetAttr = new HashSet<>(); + for (Map.Entry proprtyEntry : properties.entrySet()) { + referencedResourcesByGetAttr.addAll(getGetAttrReferencesInCaseOfContrail(proprtyEntry.getValue())); } - } else { - Collection valCollection = ((Map) propertyValue).values(); - for (Object entryValue : valCollection) { - getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(entryValue)); + return referencedResourcesByGetAttr; + } + + private Set getGetAttrReferencesInCaseOfContrail(Object propertyValue) { + Set getAttrReferences = new HashSet<>(); + if (propertyValue instanceof Map) { + if (((Map) propertyValue).containsKey(GET_ATTR)) { + if (validatePropertyValueAndAddAttrReferencesInSet(propertyValue, getAttrReferences)) { + return getAttrReferences; + } + } else { + Collection valCollection = ((Map) propertyValue).values(); + for (Object entryValue : valCollection) { + getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(entryValue)); + } + } + } else if (propertyValue instanceof List) { + for (Object prop : (List) propertyValue) { + getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(prop)); + } } - } - } else if (propertyValue instanceof List) { - for (Object prop : (List) propertyValue) { - getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(prop)); - } + return getAttrReferences; } - return getAttrReferences; - } - - private boolean validatePropertyValueAndAddAttrReferencesInSet(Object propertyValue, - Set getAttrReferences) { - Object value = ((Map) propertyValue).get(GET_ATTR ); - if (value instanceof List && ((List) value).size() == 2 - && ("fq_name").equals(((List) value).get(1))) { - if (((List) value).get(0) instanceof String) { - String attrReference = (((List) value).get(0)).toString(); - getAttrReferences.add(attrReference); - return true; - } else { - LOGGER.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); - } - } - return false; - } - - - private Set getResourcesIdsPointedByCurrentResource(String fileName, - ResourceReferenceFunctions function, - Map properties, - GlobalValidationContext globalContext) { - - Set referencedResources = new HashSet<>(); - for (Map.Entry propertyEntry : properties.entrySet()) { - referencedResources - .addAll(HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, - function.getFunction(), - propertyEntry.getValue(), - globalContext)); + private boolean validatePropertyValueAndAddAttrReferencesInSet(Object propertyValue, Set getAttrReferences) { + Object value = ((Map) propertyValue).get(GET_ATTR); + if (value instanceof List && ((List) value).size() == 2 && ("fq_name").equals(((List) value).get(1))) { + if (((List) value).get(0) instanceof String) { + String attrReference = (((List) value).get(0)).toString(); + getAttrReferences.add(attrReference); + return true; + } else { + LOGGER.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); + } + } + return false; } - return referencedResources; - } + private Set getResourcesIdsPointedByCurrentResource(String fileName, ResourceReferenceFunctions function, Map properties, + GlobalValidationContext globalContext) { + Set referencedResources = new HashSet<>(); + for (Map.Entry propertyEntry : properties.entrySet()) { + referencedResources.addAll( + HeatStructureUtil.getReferencedValuesByFunctionName(fileName, function.getFunction(), propertyEntry.getValue(), globalContext)); + } + return referencedResources; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java index 5fb2953b6a..19b8892182 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators; import java.io.InputStream; @@ -51,6 +50,11 @@ import org.openecomp.sdc.validation.impl.util.HeatValidationService; import org.openecomp.sdc.validation.util.ValidationUtil; public class HeatValidator implements Validator { + + // The Artifacts generated by SDC - not allowed to be in HEAT + static final String VF_LICENSE_MODEL_XML = "vf-license-model.xml"; + static final String VENDOR_LICENSE_MODEL_XML = "vendor-license-model.xml"; + static final String HEAT_META = "HEAT.meta"; private static final Logger LOGGER = LoggerFactory.getLogger(HeatValidator.class); private static final ErrorMessageCode ERROR_CODE_HOT_1 = new ErrorMessageCode("HOT1"); private static final ErrorMessageCode ERROR_CODE_HOT_2 = new ErrorMessageCode("HOT2"); @@ -69,224 +73,191 @@ public class HeatValidator implements Validator { private static final ErrorMessageCode ERROR_CODE_HOT_15 = new ErrorMessageCode("HOT15"); private static final ErrorMessageCode ERROR_CODE_HOT_16 = new ErrorMessageCode("HOT16"); private static final ErrorMessageCode ERROR_CODE_HOT_17 = new ErrorMessageCode("HOT17"); - private static final ErrorMessageCode ERROR_CODE_HOT_18 = new ErrorMessageCode("HOT18"); - - // The Artifacts generated by SDC - not allowed to be in HEAT - static final String VF_LICENSE_MODEL_XML = "vf-license-model.xml"; - static final String VENDOR_LICENSE_MODEL_XML = "vendor-license-model.xml"; - static final String HEAT_META = "HEAT.meta"; - private static final Set GENERATED_ARTIFACTS; static { GENERATED_ARTIFACTS = getGeneratedArtifactNames(); } - private static void validateAllRequiredArtifactsExist(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - Set artifacts, - GlobalValidationContext globalContext) { - Collection resourcesValues = heatOrchestrationTemplate.getResources() == null ? null - : heatOrchestrationTemplate.getResources().values(); - - if (CollectionUtils.isNotEmpty(resourcesValues)) { - for (Resource resource : resourcesValues) { - Collection properties = - resource.getProperties() == null ? null : resource.getProperties().values(); - validatePropertiesForAllRequiredArtifactsExist(properties, fileName, - artifacts, globalContext); - } - } - } - - private static void validatePropertiesForAllRequiredArtifactsExist(Collection properties, - String fileName, - Set artifacts, - GlobalValidationContext globalContext) { - if (CollectionUtils.isNotEmpty(properties)) { - for (Object property : properties) { - if (property instanceof Map) { - globalContext.setMessageCode(ERROR_CODE_HOT_14); - Set artifactNames = HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, - ResourceReferenceFunctions.GET_FILE.getFunction(), property, globalContext); - artifacts.addAll(artifactNames); - globalContext.setMessageCode(ERROR_CODE_HOT_15); - HeatValidationService.checkArtifactsExistence(fileName, artifactNames, - globalContext); - } - } - } - } - /* validation 14 */ - - private static void validateAllResourceReferencesExist(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Set resourcesNames = heatOrchestrationTemplate.getResources() == null ? null - : heatOrchestrationTemplate.getResources().keySet(); - Collection resourcesValues = heatOrchestrationTemplate.getResources() == null ? null - : heatOrchestrationTemplate.getResources().values(); - Collection outputsValues = heatOrchestrationTemplate.getOutputs() == null ? null - : heatOrchestrationTemplate.getOutputs().values(); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, - globalContext); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, - globalContext); - } - - private static void checkResourceExistenceFromResourcesMap(String fileName, - Set resourcesNames, - Collection valuesToSearchIn, - GlobalValidationContext globalContext) { - if (CollectionUtils.isNotEmpty(valuesToSearchIn)) { - for (Object value : valuesToSearchIn) { - if (value instanceof Resource) { - extractResourceProperty(fileName, resourcesNames, globalContext, - (Resource) value); - } else if (value instanceof Output) { - Output output = (Output) value; - Object outputsValue = output.getValue(); - handleReferencedResources(fileName, outputsValue, resourcesNames, - globalContext); + private static void validateAllRequiredArtifactsExist(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Set artifacts, + GlobalValidationContext globalContext) { + Collection resourcesValues = + heatOrchestrationTemplate.getResources() == null ? null : heatOrchestrationTemplate.getResources().values(); + if (CollectionUtils.isNotEmpty(resourcesValues)) { + for (Resource resource : resourcesValues) { + Collection properties = resource.getProperties() == null ? null : resource.getProperties().values(); + validatePropertiesForAllRequiredArtifactsExist(properties, fileName, artifacts, globalContext); + } } - } - } - } - - private static void extractResourceProperty(String fileName, Set resourcesNames, - GlobalValidationContext globalContext, - Resource value) { - Collection resourcePropertiesValues = - value.getProperties() == null ? null : value.getProperties() - .values(); - if (CollectionUtils.isNotEmpty(resourcePropertiesValues)) { - for (Object propertyValue : resourcePropertiesValues) { - handleReferencedResources(fileName, propertyValue, resourcesNames, + } + + private static void validatePropertiesForAllRequiredArtifactsExist(Collection properties, String fileName, Set artifacts, + GlobalValidationContext globalContext) { + if (CollectionUtils.isNotEmpty(properties)) { + for (Object property : properties) { + if (property instanceof Map) { + globalContext.setMessageCode(ERROR_CODE_HOT_14); + Set artifactNames = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions.GET_FILE.getFunction(), property, globalContext); + artifacts.addAll(artifactNames); + globalContext.setMessageCode(ERROR_CODE_HOT_15); + HeatValidationService.checkArtifactsExistence(fileName, artifactNames, globalContext); + } + } + } + } + /* validation 14 */ + + private static void validateAllResourceReferencesExist(String fileName, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Set resourcesNames = heatOrchestrationTemplate.getResources() == null ? null + : heatOrchestrationTemplate.getResources().keySet(); + Collection resourcesValues = heatOrchestrationTemplate.getResources() == null ? null + : heatOrchestrationTemplate.getResources().values(); + Collection outputsValues = heatOrchestrationTemplate.getOutputs() == null ? null + : heatOrchestrationTemplate.getOutputs().values(); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, + globalContext); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, globalContext); - } - } - } - - private static void handleReferencedResources(String fileName, Object valueToSearchReferencesIn, - Set resourcesNames, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_HOT_13); - Set referencedResourcesNames = HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), - valueToSearchReferencesIn, globalContext); - if (CollectionUtils.isNotEmpty(referencedResourcesNames)) { - checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, - globalContext); - } - } - - private static void checkIfResourceReferenceExist(String fileName, - Set referencedResourcesNames, - Set referencedResources, - GlobalValidationContext globalContext) { - referencedResources.stream() - .filter(referencedResource -> !referencedResourcesNames + } + + private static void checkResourceExistenceFromResourcesMap(String fileName, + Set resourcesNames, + Collection valuesToSearchIn, + GlobalValidationContext globalContext) { + if (CollectionUtils.isNotEmpty(valuesToSearchIn)) { + for (Object value : valuesToSearchIn) { + if (value instanceof Resource) { + extractResourceProperty(fileName, resourcesNames, globalContext, + (Resource) value); + } else if (value instanceof Output) { + Output output = (Output) value; + Object outputsValue = output.getValue(); + handleReferencedResources(fileName, outputsValue, resourcesNames, + globalContext); + } + } + } + } + + private static void extractResourceProperty(String fileName, Set resourcesNames, + GlobalValidationContext globalContext, + Resource value) { + Collection resourcePropertiesValues = + value.getProperties() == null ? null : value.getProperties() + .values(); + if (CollectionUtils.isNotEmpty(resourcePropertiesValues)) { + for (Object propertyValue : resourcePropertiesValues) { + handleReferencedResources(fileName, propertyValue, resourcesNames, + globalContext); + } + } + } + + private static void handleReferencedResources(String fileName, Object valueToSearchReferencesIn, + Set resourcesNames, + GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_HOT_13); + Set referencedResourcesNames = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), + valueToSearchReferencesIn, globalContext); + if (CollectionUtils.isNotEmpty(referencedResourcesNames)) { + checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, + globalContext); + } + } + + private static void checkIfResourceReferenceExist(String fileName, + Set referencedResourcesNames, + Set referencedResources, + GlobalValidationContext globalContext) { + referencedResources.stream() + .filter(referencedResource -> !referencedResourcesNames .contains(referencedResource)) - .forEach(referencedResource -> - globalContext.addMessage(fileName, - ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_16,Messages - .REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), referencedResource))); - } - - /* validation 16 */ - - private static void validateGetParamPointToParameter(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Set parametersNames = heatOrchestrationTemplate.getParameters() == null ? null - : heatOrchestrationTemplate.getParameters().keySet(); - Map resourcesMap = heatOrchestrationTemplate.getResources(); - - if (CollectionUtils.isNotEmpty(parametersNames) && MapUtils.isNotEmpty(resourcesMap)) { - for (Map.Entry resourceEntry : resourcesMap.entrySet()) { - Resource resource = resourceEntry.getValue(); - Map properties = resource.getProperties(); - validatePropertiesForGetParamPointToParameter(properties, fileName, parametersNames, - resourceEntry, globalContext); - } - } - } - - private static void validatePropertiesForGetParamPointToParameter(Map properties, - String fileName, Set parametersNames, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isNotEmpty(properties)) { - Collection propertiesValues = properties.values(); - if (CollectionUtils.isNotEmpty(propertiesValues)) { - for (Object propertyObject : propertiesValues) { - Set referencedParameterNames = HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, "get_param", propertyObject, - globalContext); - - validateReferenceParams(fileName, resourceEntry.getKey(), parametersNames, - referencedParameterNames, globalContext); - } - } - } - } - - private static void validateReferenceParams(String fileName, String resourceName, - Set parametersNamesFromFile, - Set referencedParametersNames, - GlobalValidationContext globalContext) { - for (String parameterName : referencedParametersNames) { - if (!isHeatPseudoParameter(parameterName) - && !parametersNamesFromFile.contains(parameterName)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_1,Messages - .REFERENCED_PARAMETER_NOT_FOUND.getErrorMessage(), - parameterName, resourceName)); - } - } - } - - private static boolean isHeatPseudoParameter(String parameterName) { - return HeatPseudoParameters.getPseudoParameterNames().contains(parameterName); - } - - /* validation 18*/ - - private static void validateGetAttr(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map outputMap; - outputMap = heatOrchestrationTemplate.getOutputs(); - - if (MapUtils.isNotEmpty(outputMap)) { - loopOverOutputMapAndValidateGetAttrFromNested(fileName, outputMap, - heatOrchestrationTemplate, globalContext); - } - } - - private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, - Map outputMap, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext - globalContext) { - for (Output output : outputMap.values()) { - Object outputValue = output.getValue(); - if (outputValue instanceof Map) { - Map outputValueMap = (Map) outputValue; - List getAttrValue = - (List) outputValueMap.get( - ResourceReferenceFunctions.GET_ATTR.getFunction()); + .forEach(referencedResource -> + globalContext.addMessage(fileName, + ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_16, Messages + .REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), referencedResource))); + } + + /* validation 16 */ + private static void validateGetParamPointToParameter(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Set parametersNames = heatOrchestrationTemplate.getParameters() == null ? null : heatOrchestrationTemplate.getParameters().keySet(); + Map resourcesMap = heatOrchestrationTemplate.getResources(); + if (CollectionUtils.isNotEmpty(parametersNames) && MapUtils.isNotEmpty(resourcesMap)) { + for (Map.Entry resourceEntry : resourcesMap.entrySet()) { + Resource resource = resourceEntry.getValue(); + Map properties = resource.getProperties(); + validatePropertiesForGetParamPointToParameter(properties, fileName, parametersNames, resourceEntry, globalContext); + } + } + } + + private static void validatePropertiesForGetParamPointToParameter(Map properties, String fileName, Set parametersNames, + Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + if (MapUtils.isNotEmpty(properties)) { + Collection propertiesValues = properties.values(); + if (CollectionUtils.isNotEmpty(propertiesValues)) { + for (Object propertyObject : propertiesValues) { + Set referencedParameterNames = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, "get_param", propertyObject, globalContext); + validateReferenceParams(fileName, resourceEntry.getKey(), parametersNames, referencedParameterNames, globalContext); + } + } + } + } + + private static void validateReferenceParams(String fileName, String resourceName, Set parametersNamesFromFile, + Set referencedParametersNames, GlobalValidationContext globalContext) { + for (String parameterName : referencedParametersNames) { + if (!isHeatPseudoParameter(parameterName) && !parametersNamesFromFile.contains(parameterName)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_1, Messages.REFERENCED_PARAMETER_NOT_FOUND.getErrorMessage(), parameterName, + resourceName)); + } + } + } + + private static boolean isHeatPseudoParameter(String parameterName) { + return HeatPseudoParameters.getPseudoParameterNames().contains(parameterName); + } + /* validation 18*/ + + private static void validateGetAttr(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map outputMap; + outputMap = heatOrchestrationTemplate.getOutputs(); + + if (MapUtils.isNotEmpty(outputMap)) { + loopOverOutputMapAndValidateGetAttrFromNested(fileName, outputMap, + heatOrchestrationTemplate, globalContext); + } + } + + private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, + Map outputMap, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext + globalContext) { + for (Output output : outputMap.values()) { + Object outputValue = output.getValue(); + if (outputValue instanceof Map) { + Map outputValueMap = (Map) outputValue; + List getAttrValue = + (List) outputValueMap.get( + ResourceReferenceFunctions.GET_ATTR.getFunction()); handleGetAttrValueList(getAttrValue, fileName, heatOrchestrationTemplate, - globalContext); + globalContext); } } @@ -303,328 +274,249 @@ public class HeatValidator implements Validator { } String attName = getAttrValue.get(1); String resourceType = - getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); + getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); if (Objects.nonNull(resourceType) - && HeatValidationService.isNestedResource(resourceType)) { + && HeatValidationService.isNestedResource(resourceType)) { handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, - resourceType); + resourceType); } } } - private static void handleGetAttrNestedResource(String fileName, - GlobalValidationContext globalContext, - String resourceName, String attName, - String resourceType) { - Map nestedOutputMap; - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - try { - Optional fileContent = globalContext.getFileContent(resourceType); - if (fileContent.isPresent()) { - nestedHeatOrchestrationTemplate = - new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); - } else { - throw new Exception("The file '" + resourceType + "' has no content"); - } - } catch (Exception exception) { + + private static void handleGetAttrNestedResource(String fileName, + GlobalValidationContext globalContext, + String resourceName, String attName, + String resourceType) { + Map nestedOutputMap; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + try { + Optional fileContent = globalContext.getFileContent(resourceType); + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + throw new Exception("The file '" + resourceType + "' has no content"); + } + } catch (Exception exception) { LOGGER.error("Invalid yaml file", exception); - return; - } - nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); - - if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(attName)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_17,Messages - .GET_ATTR_NOT_FOUND.getErrorMessage(), - attName, resourceName)); - } - } - - private static String getResourceTypeFromResourcesMap(String resourceName, - HeatOrchestrationTemplate - heatOrchestrationTemplate) { - Resource resource = heatOrchestrationTemplate.getResources().get(resourceName); - if (Objects.nonNull(resource)) { - return resource.getType(); - } else { - return null; - } - } - - /* validation 17 + */ - private static void validateEnvFile(String fileName, String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Environment envContent; - - if (!envFileName.contains(".env")) { - globalContext.addMessage(envFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_2,Messages - .WRONG_ENV_FILE_EXTENSION.getErrorMessage(), envFileName)); - } - - envContent = HeatValidationService.validateEnvContent(fileName, envFileName, globalContext); - if (envContent != null) { - validateEnvContentIsSubSetOfHeatParameters(envFileName, envContent, globalContext, - heatOrchestrationTemplate); - validateEnvParametersMatchDefinedHeatParameterTypes(envFileName, envContent, globalContext, - heatOrchestrationTemplate); - } - } - - private static void validateEnvContentIsSubSetOfHeatParameters(String envFile, - Environment envContent, - GlobalValidationContext - globalContext, - HeatOrchestrationTemplate - heatOrchestrationTemplate) { - Set parametersNames = heatOrchestrationTemplate.getParameters() == null ? null - : heatOrchestrationTemplate.getParameters().keySet(); - - if (MapUtils.isNotEmpty(envContent.getParameters())) { - if (CollectionUtils.isNotEmpty(parametersNames)) { - for (Map.Entry envEntry : envContent.getParameters().entrySet()) { + return; + } + nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); + if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(attName)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_17, Messages + .GET_ATTR_NOT_FOUND.getErrorMessage(), + attName, resourceName)); + } + } - validateEnvEntryForvalidateEnvContentIsSubSetOfHeatParameters(envEntry, - parametersNames, envFile, globalContext); + private static String getResourceTypeFromResourcesMap(String resourceName, + HeatOrchestrationTemplate + heatOrchestrationTemplate) { + Resource resource = heatOrchestrationTemplate.getResources().get(resourceName); + if (Objects.nonNull(resource)) { + return resource.getType(); + } else { + return null; } - } else { - for (Map.Entry envEntry : envContent.getParameters().entrySet()) { - globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_3,Messages - .ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), - envFile, envEntry.getKey())); + } + + /* validation 17 + */ + private static void validateEnvFile(String fileName, String envFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Environment envContent; + if (!envFileName.contains(".env")) { + globalContext.addMessage(envFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_2, Messages.WRONG_ENV_FILE_EXTENSION.getErrorMessage(), envFileName)); + } + envContent = HeatValidationService.validateEnvContent(fileName, envFileName, globalContext); + if (envContent != null) { + validateEnvContentIsSubSetOfHeatParameters(envFileName, envContent, globalContext, heatOrchestrationTemplate); + validateEnvParametersMatchDefinedHeatParameterTypes(envFileName, envContent, globalContext, heatOrchestrationTemplate); } - } - } - } - - private static void validateEnvEntryForvalidateEnvContentIsSubSetOfHeatParameters( - Map.Entry envEntry, - Set parametersNames, - String envFile, - GlobalValidationContext globalContext) { - String envParameter = envEntry.getKey(); - if (parametersNames != null && !parametersNames.contains(envParameter)) { - globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HOT_3,Messages - .ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, - envParameter)); } -} - private static void validateParameterDefaultTypeAlignWithType(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext - globalContext) { - Map parametersMap = heatOrchestrationTemplate.getParameters(); - - if (MapUtils.isNotEmpty(parametersMap)) { - for (Map.Entry parameterEntry : parametersMap.entrySet()) { - validateParameterEntryForParameterDefaultTypeAlignWithType(parameterEntry, - fileName, globalContext); - } - } - } - private static void validateParameterEntryForParameterDefaultTypeAlignWithType( - Map.Entry parameterEntry, - String fileName, GlobalValidationContext globalContext){ + + private static void validateEnvContentIsSubSetOfHeatParameters(String envFile, Environment envContent, GlobalValidationContext globalContext, + HeatOrchestrationTemplate heatOrchestrationTemplate) { + Set parametersNames = heatOrchestrationTemplate.getParameters() == null ? null : heatOrchestrationTemplate.getParameters().keySet(); + if (MapUtils.isNotEmpty(envContent.getParameters())) { + if (CollectionUtils.isNotEmpty(parametersNames)) { + for (Map.Entry envEntry : envContent.getParameters().entrySet()) { + validateEnvEntryForvalidateEnvContentIsSubSetOfHeatParameters(envEntry, parametersNames, envFile, globalContext); + } + } else { + for (Map.Entry envEntry : envContent.getParameters().entrySet()) { + globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_3, Messages.ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, + envEntry.getKey())); + } + } + } + } + + private static void validateEnvEntryForvalidateEnvContentIsSubSetOfHeatParameters(Map.Entry envEntry, Set parametersNames, + String envFile, GlobalValidationContext globalContext) { + String envParameter = envEntry.getKey(); + if (parametersNames != null && !parametersNames.contains(envParameter)) { + globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_3, Messages.ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, envParameter)); + } + } + + private static void validateParameterDefaultTypeAlignWithType(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map parametersMap = heatOrchestrationTemplate.getParameters(); + if (MapUtils.isNotEmpty(parametersMap)) { + for (Map.Entry parameterEntry : parametersMap.entrySet()) { + validateParameterEntryForParameterDefaultTypeAlignWithType(parameterEntry, fileName, globalContext); + } + } + } + + private static void validateParameterEntryForParameterDefaultTypeAlignWithType(Map.Entry parameterEntry, String fileName, + GlobalValidationContext globalContext) { Parameter parameter = parameterEntry.getValue(); String parameterType = parameter.getType(); Object parameterDefault = parameter.get_default(); if (parameterDefault != null && parameterType != null) { - boolean isValueMatchDefault = - DefinedHeatParameterTypes.isValueIsFromGivenType(parameterDefault, - parameterType); + boolean isValueMatchDefault = DefinedHeatParameterTypes.isValueIsFromGivenType(parameterDefault, parameterType); if (!isValueMatchDefault) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HOT_4,Messages - .PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), - parameterEntry.getKey(), parameterType)); + .getErrorWithParameters(ERROR_CODE_HOT_4, Messages.PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), + parameterEntry.getKey(), parameterType)); } } } - private static void validateEnvParametersMatchDefinedHeatParameterTypes(String envFile, - Environment envContent, - GlobalValidationContext globalContext, - HeatOrchestrationTemplate heatOrchestrationTemplate) { - Map heatParameters = heatOrchestrationTemplate.getParameters(); + private static void validateEnvParametersMatchDefinedHeatParameterTypes(String envFile, Environment envContent, + GlobalValidationContext globalContext, + HeatOrchestrationTemplate heatOrchestrationTemplate) { + Map heatParameters = heatOrchestrationTemplate.getParameters(); + if (MapUtils.isNotEmpty(heatParameters) && MapUtils.isNotEmpty(envContent.getParameters())) { + validateEnvEntryForEnvParametersMatchDefinedHeatParameterTypes(envContent, heatParameters, envFile, globalContext); + } + } - if (MapUtils.isNotEmpty(heatParameters) && MapUtils.isNotEmpty(envContent.getParameters())) { - validateEnvEntryForEnvParametersMatchDefinedHeatParameterTypes(envContent, - heatParameters, envFile, globalContext); + private static void validateEnvEntryForEnvParametersMatchDefinedHeatParameterTypes(Environment envContent, Map heatParameters, + String envFile, GlobalValidationContext globalContext) { + for (Map.Entry envEntry : envContent.getParameters().entrySet()) { + String parameterName = envEntry.getKey(); + Object parameterEnvValue = envEntry.getValue(); + Parameter parameterFromHeatFile = heatParameters.get(parameterName); + if (parameterFromHeatFile != null) { + String parameterType = parameterFromHeatFile.getType(); + if (!DefinedHeatParameterTypes.isEmptyValueInEnv(parameterEnvValue) && !DefinedHeatParameterTypes + .isValueIsFromGivenType(parameterEnvValue, parameterType)) { + globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_5, Messages.PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), parameterName)); + } + } + } + } + private static Set getGeneratedArtifactNames() { + Set predefinedArtifactNames = new HashSet<>(); + predefinedArtifactNames.add(VF_LICENSE_MODEL_XML); + predefinedArtifactNames.add(VENDOR_LICENSE_MODEL_XML); + predefinedArtifactNames.add(HEAT_META); + return predefinedArtifactNames; + } + @SuppressWarnings("unchecked") + private static void checkResourceDependsOn(String fileName, Resource resource, Set resourcesNames, + GlobalValidationContext globalContext) { + Object dependencies = resource.getDepends_on(); + if (dependencies instanceof Collection) { + ((Collection) dependencies).stream().filter(resourceId -> !resourcesNames.contains(resourceId)).forEach( + resourceId -> globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_7, Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), resourceId))); + } else if (dependencies instanceof String && !resourcesNames.contains(dependencies)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_8, Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), String.valueOf(dependencies))); + } } - } - private static void validateEnvEntryForEnvParametersMatchDefinedHeatParameterTypes( - Environment envContent, - Map heatParameters, - String envFile, - GlobalValidationContext globalContext) { - for (Map.Entry envEntry : envContent.getParameters().entrySet()) { - String parameterName = envEntry.getKey(); - Object parameterEnvValue = envEntry.getValue(); - Parameter parameterFromHeatFile = heatParameters.get(parameterName); - if (parameterFromHeatFile != null) { - String parameterType = parameterFromHeatFile.getType(); - if (!DefinedHeatParameterTypes.isEmptyValueInEnv(parameterEnvValue) - && !DefinedHeatParameterTypes - .isValueIsFromGivenType(parameterEnvValue, parameterType)) { - globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HOT_5,Messages - .PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), - parameterName)); - } - } - } - } - - @Override - public void validate(GlobalValidationContext globalContext) { - ManifestContent manifestContent; - try { - manifestContent = ValidationUtil.validateManifest(globalContext); - } catch (Exception exception) { - LOGGER.error("Failed to validate manifest file", exception); - return; - } - Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - Map fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); - Set artifacts = new HashSet<>(); - - globalContext.getFiles().stream() - .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))).forEach( - fileName -> validate(fileName, fileEnvMap.get(fileName) == null ? null : fileEnvMap.get( - fileName).getFile(), artifacts, - globalContext)); - - Set manifestArtifacts = ManifestUtil.getArtifacts(manifestContent); - - globalContext.getFiles().stream().filter(fileName -> isManifestArtifact(manifestArtifacts, fileName) - && isNotArtifact(artifacts, fileName)).forEach(fileName -> { + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.validateManifest(globalContext); + } catch (Exception exception) { + LOGGER.error("Failed to validate manifest file", exception); + return; + } + Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + Map fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); + Set artifacts = new HashSet<>(); + globalContext.getFiles().stream().filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))).forEach( + fileName -> validate(fileName, fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(), artifacts, globalContext)); + Set manifestArtifacts = ManifestUtil.getArtifacts(manifestContent); + globalContext.getFiles().stream().filter(fileName -> isManifestArtifact(manifestArtifacts, fileName) && isNotArtifact(artifacts, fileName)) + .forEach(fileName -> { + globalContext.addMessage(fileName, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_HOT_11, Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage())); + validateGeneratedArtifact(fileName, globalContext); + }); + } - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_11, - Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage())); + private void validateGeneratedArtifact(String fileName, GlobalValidationContext globalContext) { + if (GENERATED_ARTIFACTS.contains(fileName)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_HOT_18, Messages.GENERATED_ARTIFACT_IN_USE.getErrorMessage(), fileName)); + } + } - validateGeneratedArtifact(fileName, globalContext); + private boolean isManifestArtifact(Set manifestArtifacts, String fileName) { + return manifestArtifacts.contains(fileName); + } - }); + private boolean isNotArtifact(Set artifacts, String fileName) { + return !artifacts.contains(fileName); } - private void validateGeneratedArtifact(String fileName, GlobalValidationContext globalContext) { - if (GENERATED_ARTIFACTS.contains(fileName)) { + private void validate(String fileName, String envFileName, Set artifacts, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_HOT_12); + HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate != null) { + if (!(fileName.contains(".yaml") || fileName.contains(".yml"))) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_6, Messages.WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), fileName)); + } + validateHeatBaseStructure(fileName, heatOrchestrationTemplate, globalContext); + validateParameterDefaultTypeAlignWithType(fileName, heatOrchestrationTemplate, globalContext); + validateAllResourceReferencesExist(fileName, heatOrchestrationTemplate, globalContext); + validateResourceDependsOn(fileName, heatOrchestrationTemplate, globalContext); + validateGetParamPointToParameter(fileName, heatOrchestrationTemplate, globalContext); + validateGetAttr(fileName, heatOrchestrationTemplate, globalContext); + validateAllRequiredArtifactsExist(fileName, heatOrchestrationTemplate, artifacts, globalContext); + if (envFileName != null) { + validateEnvFile(fileName, envFileName, heatOrchestrationTemplate, globalContext); + } + } + } + + private void validateResourceDependsOn(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map resourcesMap = heatOrchestrationTemplate.getResources(); + if (MapUtils.isEmpty(resourcesMap)) { + return; + } + Set resourcesNames = resourcesMap.keySet(); + resourcesMap.entrySet().stream().forEach(entry -> checkResourceDependsOn(fileName, entry.getValue(), resourcesNames, globalContext)); + } + + private void validateHeatBaseStructure(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + if (heatOrchestrationTemplate.getHeat_template_version() == null) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_18, - Messages.GENERATED_ARTIFACT_IN_USE.getErrorMessage(), fileName)); + .getErrorWithParameters(ERROR_CODE_HOT_9, Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), "missing template version")); } - } - - private static Set getGeneratedArtifactNames() { - Set predefinedArtifactNames = new HashSet<>(); - predefinedArtifactNames.add(VF_LICENSE_MODEL_XML); - predefinedArtifactNames.add(VENDOR_LICENSE_MODEL_XML); - predefinedArtifactNames.add(HEAT_META); - return predefinedArtifactNames; - } - - private boolean isManifestArtifact(Set manifestArtifacts, String fileName) { - return manifestArtifacts.contains(fileName); - } - - private boolean isNotArtifact(Set artifacts, String fileName) { - return !artifacts.contains(fileName); - } - - private void validate(String fileName, String envFileName, - Set artifacts, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_HOT_12); - HeatOrchestrationTemplate - heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition( - fileName, globalContext); - - - if (heatOrchestrationTemplate != null) { - if (!(fileName.contains(".yaml") || fileName.contains(".yml"))) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_6,Messages - .WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), fileName)); - } - - validateHeatBaseStructure(fileName, heatOrchestrationTemplate, globalContext); - validateParameterDefaultTypeAlignWithType(fileName, heatOrchestrationTemplate, globalContext); - validateAllResourceReferencesExist(fileName, heatOrchestrationTemplate, globalContext); - validateResourceDependsOn(fileName, heatOrchestrationTemplate, globalContext); - validateGetParamPointToParameter(fileName, heatOrchestrationTemplate, globalContext); - validateGetAttr(fileName, heatOrchestrationTemplate, globalContext); - validateAllRequiredArtifactsExist(fileName, heatOrchestrationTemplate, artifacts, - globalContext); - - if (envFileName != null) { - validateEnvFile(fileName, envFileName, heatOrchestrationTemplate, globalContext); - } - } - } - - private void validateResourceDependsOn(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map resourcesMap = heatOrchestrationTemplate.getResources(); - if(MapUtils.isEmpty(resourcesMap)) { - return; - } - - Set resourcesNames = resourcesMap.keySet(); - - resourcesMap.entrySet().stream() - .forEach(entry -> checkResourceDependsOn(fileName, entry.getValue(), - resourcesNames, globalContext)); - } - - @SuppressWarnings("unchecked") - private static void checkResourceDependsOn(String fileName, Resource resource, - Set resourcesNames, - GlobalValidationContext globalContext) { - Object dependencies = resource.getDepends_on(); - if (dependencies instanceof Collection) { - ((Collection) dependencies) - .stream() - .filter(resourceId -> !resourcesNames.contains(resourceId)) - .forEach(resourceId -> globalContext.addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_7, - Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), resourceId))); - } else if (dependencies instanceof String && !resourcesNames.contains(dependencies)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_8, - Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), String.valueOf(dependencies))); - } - } - - - private void validateHeatBaseStructure(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - if (heatOrchestrationTemplate.getHeat_template_version() == null) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_9, - Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), - "missing template version")); - } - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_10, - Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), - "The heat file does not contain any resources")); - } - } + if (heatOrchestrationTemplate.getResources() == null || heatOrchestrationTemplate.getResources().size() == 0) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_10, Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + "The heat file does not contain any resources")); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java index 675aa8adaf..ca01448a43 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java @@ -12,10 +12,13 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.validation.impl.validators; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -29,161 +32,121 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.Validator; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - public class ManifestValidator implements Validator { - private static final Logger LOGGER = LoggerFactory.getLogger(YamlValidator.class); - private static final ErrorMessageCode ERROR_CODE_MNF_1 = new ErrorMessageCode("MNF1"); - private static final ErrorMessageCode ERROR_CODE_MNF_2 = new ErrorMessageCode("MNF2"); - private static final ErrorMessageCode ERROR_CODE_MNF_3 = new ErrorMessageCode("MNF3"); - private static final ErrorMessageCode ERROR_CODE_MNF_4 = new ErrorMessageCode("MNF4"); - private static final ErrorMessageCode ERROR_CODE_MNF_5 = new ErrorMessageCode("MNF5"); - private static final ErrorMessageCode ERROR_CODE_MNF_6 = new ErrorMessageCode("MNF6"); - private static final ErrorMessageCode ERROR_CODE_MNF_7 = new ErrorMessageCode("MNF7"); - private static final ErrorMessageCode ERROR_CODE_MNF_8 = new ErrorMessageCode("MNF8"); - - @Override - public void validate(GlobalValidationContext globalContext) { - Optional content = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); - ManifestContent manifestContent; - - try { - if (content.isPresent()) { - manifestContent = JsonUtil.json2Object(content.get(), ManifestContent.class); - } else { - throw new Exception("The manifest file '" + SdcCommon.MANIFEST_NAME + "' has no content"); - } - } catch (Exception re) { - LOGGER.error("Invalid manifest file", re); - globalContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_6, - Messages.INVALID_MANIFEST_FILE.getErrorMessage())); - return; - } - List manifestFiles = getManifestFileList(manifestContent, globalContext); - manifestFiles.stream().filter(name -> - !globalContext.getFileContextMap().containsKey(name) - ).forEach(name -> globalContext - .addMessage(name, ErrorLevel.ERROR,ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_4, - Messages.MISSING_FILE_IN_ZIP.getErrorMessage()))); - - globalContext.getFileContextMap().keySet().stream().filter(name -> - isNotManifestFiles(manifestFiles, name) && isNotManifestName(name) - ).forEach(name -> - globalContext.addMessage(name, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_5, - Messages.MISSING_FILE_IN_MANIFEST.getErrorMessage()))); - } - - private boolean isNotManifestFiles(List manifestFiles, String name) { - return !manifestFiles.contains(name); - } - - private boolean isNotManifestName(String name) { - return !SdcCommon.MANIFEST_NAME.equals(name); - } - - - private List getManifestFileList(ManifestContent manifestContent, - GlobalValidationContext context) { - ManifestScanner manifestScanner = new ManifestScanner(); - manifestScanner.scan(null, manifestContent.getData(), context); - return manifestScanner.getFileList(); - } - - - private class ManifestScanner { - private final List fileList = new ArrayList<>(); - - public void scan(FileData fileData, List data, - GlobalValidationContext globalContext) { - if (fileData == null) { - for (FileData childFileData : data) { - validateIfEnvIsAssociatedToHeat(globalContext, childFileData); + private static final Logger LOGGER = LoggerFactory.getLogger(YamlValidator.class); + private static final ErrorMessageCode ERROR_CODE_MNF_1 = new ErrorMessageCode("MNF1"); + private static final ErrorMessageCode ERROR_CODE_MNF_2 = new ErrorMessageCode("MNF2"); + private static final ErrorMessageCode ERROR_CODE_MNF_3 = new ErrorMessageCode("MNF3"); + private static final ErrorMessageCode ERROR_CODE_MNF_4 = new ErrorMessageCode("MNF4"); + private static final ErrorMessageCode ERROR_CODE_MNF_5 = new ErrorMessageCode("MNF5"); + private static final ErrorMessageCode ERROR_CODE_MNF_6 = new ErrorMessageCode("MNF6"); + private static final ErrorMessageCode ERROR_CODE_MNF_7 = new ErrorMessageCode("MNF7"); + private static final ErrorMessageCode ERROR_CODE_MNF_8 = new ErrorMessageCode("MNF8"); + + @Override + public void validate(GlobalValidationContext globalContext) { + Optional content = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); + ManifestContent manifestContent; + try { + if (content.isPresent()) { + manifestContent = JsonUtil.json2Object(content.get(), ManifestContent.class); + } else { + throw new Exception("The manifest file '" + SdcCommon.MANIFEST_NAME + "' has no content"); + } + } catch (Exception re) { + LOGGER.error("Invalid manifest file", re); + globalContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_6, Messages.INVALID_MANIFEST_FILE.getErrorMessage())); + return; } - } - if (fileData != null) { - fileList.add(fileData.getFile()); - validateFileTypeVsFileName(globalContext,fileData); - } - if (data == null) { - return; - } - data.forEach(chileFileData -> scan(chileFileData, chileFileData.getData(), globalContext)); + List manifestFiles = getManifestFileList(manifestContent, globalContext); + manifestFiles.stream().filter(name -> !globalContext.getFileContextMap().containsKey(name)).forEach(name -> globalContext + .addMessage(name, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_4, Messages.MISSING_FILE_IN_ZIP.getErrorMessage()))); + globalContext.getFileContextMap().keySet().stream().filter(name -> isNotManifestFiles(manifestFiles, name) && isNotManifestName(name)) + .forEach(name -> globalContext.addMessage(name, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_5, Messages.MISSING_FILE_IN_MANIFEST.getErrorMessage()))); } - public List getFileList() { - return this.fileList; + private boolean isNotManifestFiles(List manifestFiles, String name) { + return !manifestFiles.contains(name); } - private void validateFileTypeVsFileName(GlobalValidationContext globalValidationContext, - FileData fileData) { - String fileName = fileData.getFile(); - validateIfFileExists(globalValidationContext,fileName); - FileData.Type type = fileData.getType(); - if (type == null) { - globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_8, - Messages.INVALID_FILE_TYPE.getErrorMessage())); - } else if (type.equals(FileData.Type.HEAT_NET) || type.equals(FileData.Type.HEAT_VOL) - || type.equals(FileData.Type.HEAT)) { - validateIfFileHasYamlExtenstion(globalValidationContext,fileName); - } else if (type.equals(FileData.Type.HEAT_ENV)) { - validateIfFileHasEnvExtension(globalValidationContext,fileName); - } + private boolean isNotManifestName(String name) { + return !SdcCommon.MANIFEST_NAME.equals(name); } - private void validateIfEnvIsAssociatedToHeat(GlobalValidationContext globalContext, - FileData childFileData) { - if (childFileData.getType() != null - && childFileData.getType().equals(FileData.Type.HEAT_ENV)) { - globalContext.addMessage(childFileData.getFile(), ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_1, - Messages.ENV_NOT_ASSOCIATED_TO_HEAT.getErrorMessage())); - } + private List getManifestFileList(ManifestContent manifestContent, GlobalValidationContext context) { + ManifestScanner manifestScanner = new ManifestScanner(); + manifestScanner.scan(null, manifestContent.getData(), context); + return manifestScanner.getFileList(); } - private void validateIfFileHasEnvExtension(GlobalValidationContext globalValidationContext, - String fileName) { - if (fileName != null && !fileName.endsWith(".env")) { - globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_3, - Messages.WRONG_ENV_FILE_EXTENSION.getErrorMessage(), - fileName)); - } - } + private class ManifestScanner { + + private final List fileList = new ArrayList<>(); + + public void scan(FileData fileData, List data, GlobalValidationContext globalContext) { + if (fileData == null) { + for (FileData childFileData : data) { + validateIfEnvIsAssociatedToHeat(globalContext, childFileData); + } + } + if (fileData != null) { + fileList.add(fileData.getFile()); + validateFileTypeVsFileName(globalContext, fileData); + } + if (data == null) { + return; + } + data.forEach(chileFileData -> scan(chileFileData, chileFileData.getData(), globalContext)); + } - private void validateIfFileHasYamlExtenstion(GlobalValidationContext globalValidationContext, - String fileName) { - if (fileName != null && !fileName.endsWith(".yml") && !fileName.endsWith(".yaml")) { - globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_2, - Messages.WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), - fileName)); - } - } + public List getFileList() { + return this.fileList; + } - private void validateIfFileExists(GlobalValidationContext globalValidationContext, - String fileName) { - if (fileName == null) { - globalValidationContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_MNF_7, - Messages.MISSING_FILE_NAME_IN_MANIFEST.getErrorMessage())); + private void validateFileTypeVsFileName(GlobalValidationContext globalValidationContext, FileData fileData) { + String fileName = fileData.getFile(); + validateIfFileExists(globalValidationContext, fileName); + FileData.Type type = fileData.getType(); + if (type == null) { + globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_8, Messages.INVALID_FILE_TYPE.getErrorMessage())); + } else if (type.equals(FileData.Type.HEAT_NET) || type.equals(FileData.Type.HEAT_VOL) || type.equals(FileData.Type.HEAT)) { + validateIfFileHasYamlExtenstion(globalValidationContext, fileName); + } else if (type.equals(FileData.Type.HEAT_ENV)) { + validateIfFileHasEnvExtension(globalValidationContext, fileName); + } + } - } - } + private void validateIfEnvIsAssociatedToHeat(GlobalValidationContext globalContext, FileData childFileData) { + if (childFileData.getType() != null && childFileData.getType().equals(FileData.Type.HEAT_ENV)) { + globalContext.addMessage(childFileData.getFile(), ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_1, Messages.ENV_NOT_ASSOCIATED_TO_HEAT.getErrorMessage())); + } + } - } - + private void validateIfFileHasEnvExtension(GlobalValidationContext globalValidationContext, String fileName) { + if (fileName != null && !fileName.endsWith(".env")) { + globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_MNF_3, Messages.WRONG_ENV_FILE_EXTENSION.getErrorMessage(), fileName)); + } + } + + private void validateIfFileHasYamlExtenstion(GlobalValidationContext globalValidationContext, String fileName) { + if (fileName != null && !fileName.endsWith(".yml") && !fileName.endsWith(".yaml")) { + globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_MNF_2, Messages.WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), fileName)); + } + } + + private void validateIfFileExists(GlobalValidationContext globalValidationContext, String fileName) { + if (fileName == null) { + globalValidationContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_MNF_7, Messages.MISSING_FILE_NAME_IN_MANIFEST.getErrorMessage())); + } + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java index 81f7c61eee..b65199758d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java @@ -19,6 +19,7 @@ */ package org.openecomp.sdc.validation.impl.validators; +import java.util.Map; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.validation.ValidationContext; @@ -26,23 +27,19 @@ import org.openecomp.sdc.validation.base.ResourceBaseValidator; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.type.NamingConventionValidationContext; -import java.util.Map; - /** * Created by TALIO on 2/15/2017. */ public class NamingConventionGuideLineValidator extends ResourceBaseValidator { - @Override - public void init(Map properties){ - super.init((Map) properties.get(ConfigConstants.Resource_Base_Validator)); - } + @Override + public void init(Map properties) { + super.init((Map) properties.get(ConfigConstants.Resource_Base_Validator)); + } - @Override - public ValidationContext createValidationContext(String fileName, String envFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext){ - return new NamingConventionValidationContext(heatOrchestrationTemplate, envFileName); - } + @Override + public ValidationContext createValidationContext(String fileName, String envFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + return new NamingConventionValidationContext(heatOrchestrationTemplate, envFileName); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/PmDictionaryValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/PmDictionaryValidator.java index 05021fdf4f..4dad4afc16 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/PmDictionaryValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/PmDictionaryValidator.java @@ -17,11 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.impl.validators; import io.vavr.control.Option; import io.vavr.control.Try; +import java.io.InputStream; +import java.util.List; +import java.util.Set; import org.onap.validation.yaml.YamlContentValidator; import org.onap.validation.yaml.error.YamlDocumentValidationError; import org.openecomp.core.validation.ErrorMessageCode; @@ -30,10 +32,6 @@ import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.validation.Validator; -import java.io.InputStream; -import java.util.List; -import java.util.Set; - public class PmDictionaryValidator implements Validator { private static final ErrorMessageCode PM_DICT_ERROR_CODE = new ErrorMessageCode("PM_DICT"); @@ -44,11 +42,8 @@ public class PmDictionaryValidator implements Validator { validatePmDictionaryFiles(globalContext, pmDictionaryFiles); } - private void validatePmDictionaryFiles(GlobalValidationContext globalContext, Set pmDictionaryFiles) { - pmDictionaryFiles.stream() - .map(fileName -> new ValidationHelper(globalContext, fileName)) - .forEach(ValidationHelper::validate); + pmDictionaryFiles.stream().map(fileName -> new ValidationHelper(globalContext, fileName)).forEach(ValidationHelper::validate); } private static class ValidationHelper { @@ -62,36 +57,27 @@ public class PmDictionaryValidator implements Validator { } public void validate() { - Option.ofOptional(globalContext.getFileContent(fileName)) - .peek(this::validateFileContent) - .onEmpty(() -> addErrorToContext(formatMessage("File is empty"))); + Option.ofOptional(globalContext.getFileContent(fileName)).peek(this::validateFileContent) + .onEmpty(() -> addErrorToContext(formatMessage("File is empty"))); } private void validateFileContent(InputStream inputStream) { - Try.of(inputStream::readAllBytes) - .mapTry(fileContent -> new YamlContentValidator().validate(fileContent)) - .onSuccess(this::reportValidationErrorsIfPresent) - .onFailure(e -> addErrorToContext(formatMessage(e.getMessage()))); + Try.of(inputStream::readAllBytes).mapTry(fileContent -> new YamlContentValidator().validate(fileContent)) + .onSuccess(this::reportValidationErrorsIfPresent).onFailure(e -> addErrorToContext(formatMessage(e.getMessage()))); } private void reportValidationErrorsIfPresent(List validationErrors) { - validationErrors.stream() - .map(this::prepareValidationMessage) - .forEach(this::addErrorToContext); + validationErrors.stream().map(this::prepareValidationMessage).forEach(this::addErrorToContext); } private String prepareValidationMessage(YamlDocumentValidationError error) { - final String errorMessage = String.format("Document Number: %s, Path: %s, Problem: %s", - error.getYamlDocumentNumber(), - error.getPath(), - error.getMessage() - ); + final String errorMessage = String + .format("Document Number: %s, Path: %s, Problem: %s", error.getYamlDocumentNumber(), error.getPath(), error.getMessage()); return formatMessage(errorMessage); } private String formatMessage(String message) { - return ErrorMessagesFormatBuilder - .getErrorWithParameters(PM_DICT_ERROR_CODE, message); + return ErrorMessagesFormatBuilder.getErrorWithParameters(PM_DICT_ERROR_CODE, message); } private void addErrorToContext(String message) { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java index 0c279c23ee..3bac4c786d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.validation.ErrorMessageCode; @@ -36,198 +38,126 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - public class SharedResourceGuideLineValidator implements Validator { - private static final Logger LOGGER = LoggerFactory.getLogger( - SharedResourceGuideLineValidator.class); - private static final ErrorMessageCode ERROR_CODE_SRG_1 = new ErrorMessageCode("SRG1"); - private static final ErrorMessageCode ERROR_CODE_SRG_2 = new ErrorMessageCode("SRG2"); - private static final ErrorMessageCode ERROR_CODE_SRG_3 = new ErrorMessageCode("SRG3"); - private static final ErrorMessageCode ERROR_CODE_SRG_4 = new ErrorMessageCode("SRG4"); - private static final ErrorMessageCode ERROR_CODE_SRG_5 = new ErrorMessageCode("SRG5"); - private static final ErrorMessageCode ERROR_CODE_SRG_6 = new ErrorMessageCode("SRG6"); - - @Override - public void validate(GlobalValidationContext globalContext) { - ManifestContent manifestContent; - try { - manifestContent = ValidationUtil.validateManifest(globalContext); - } catch (Exception exception) { - LOGGER.error("Fialed to check Validation PreCondition ",exception); - return; - } - - Set baseFiles = validateManifest(manifestContent, globalContext); - - Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - globalContext.getFiles().stream() - .filter(fileName -> FileData - .isHeatFile(fileTypeMap.get(fileName))) - .forEach(fileName -> validate(fileName, - fileTypeMap, baseFiles, globalContext)); + private static final Logger LOGGER = LoggerFactory.getLogger(SharedResourceGuideLineValidator.class); + private static final ErrorMessageCode ERROR_CODE_SRG_1 = new ErrorMessageCode("SRG1"); + private static final ErrorMessageCode ERROR_CODE_SRG_2 = new ErrorMessageCode("SRG2"); + private static final ErrorMessageCode ERROR_CODE_SRG_3 = new ErrorMessageCode("SRG3"); + private static final ErrorMessageCode ERROR_CODE_SRG_4 = new ErrorMessageCode("SRG4"); + private static final ErrorMessageCode ERROR_CODE_SRG_5 = new ErrorMessageCode("SRG5"); + private static final ErrorMessageCode ERROR_CODE_SRG_6 = new ErrorMessageCode("SRG6"); - } - - private Set validateManifest(ManifestContent manifestContent, - GlobalValidationContext globalContext) { - Set baseFiles = ManifestUtil.getBaseFiles(manifestContent); - if (baseFiles == null || baseFiles.isEmpty()) { - globalContext.addMessage( - SdcCommon.MANIFEST_NAME, - ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_SRG_3,Messages - .MISSIN_BASE_HEAT_FILE.getErrorMessage())); - } else if (baseFiles.size() > 1) { - String baseFileList = getElementListAsString(baseFiles); - globalContext.addMessage( - SdcCommon.MANIFEST_NAME, - ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_SRG_4,Messages - .MULTI_BASE_HEAT_FILE.getErrorMessage(), - baseFileList)); + private static String getElementListAsString(Set elementCollection) { + return "[" + CommonMethods.collectionToCommaSeparatedString(elementCollection) + "]"; } - return baseFiles; - } - - private static String getElementListAsString(Set elementCollection) { - return "[" - + CommonMethods.collectionToCommaSeparatedString(elementCollection) - + "]"; - } - private void validate(String fileName, Map fileTypeMap, - Set baseFiles, GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_SRG_5); - HeatOrchestrationTemplate - heatOrchestrationTemplate = ValidationUtil - .checkHeatOrchestrationPreCondition(fileName, globalContext); - if (heatOrchestrationTemplate == null) { - return; + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.validateManifest(globalContext); + } catch (Exception exception) { + LOGGER.error("Fialed to check Validation PreCondition ", exception); + return; + } + Set baseFiles = validateManifest(manifestContent, globalContext); + Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + globalContext.getFiles().stream().filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, fileTypeMap, baseFiles, globalContext)); } - validateBaseFile(fileName, baseFiles, heatOrchestrationTemplate, globalContext); - validateHeatVolumeFile(fileName, fileTypeMap, heatOrchestrationTemplate, globalContext); - } - - - private void validateBaseFile(String fileName, Set baseFiles, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - //if not base return - if (baseFiles == null || !baseFiles.contains(fileName)) { - return; - } - - //if no resources exist return - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - return; - } - - Set expectedExposedResources = new HashSet<>(); - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> ValidationUtil.isExpectedToBeExposed(entry.getValue().getType())) - .forEach(entry -> expectedExposedResources.add(entry.getKey())); - Set actualExposedResources = new HashSet<>(); - - if (heatOrchestrationTemplate.getOutputs() != null) { - globalContext.setMessageCode(ERROR_CODE_SRG_6); - heatOrchestrationTemplate.getOutputs().entrySet() - .stream() - .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), - globalContext)) - .forEach(entry -> actualExposedResources.add( - getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), - globalContext))); - } - ValidationUtil.removeExposedResourcesCalledByGetResource(fileName, actualExposedResources, - heatOrchestrationTemplate, globalContext); - - actualExposedResources.forEach(expectedExposedResources::remove); - - if (CollectionUtils.isNotEmpty(expectedExposedResources)) { - expectedExposedResources - .stream() - .forEach(name -> globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_SRG_1, - Messages.RESOURCE_NOT_DEFINED_IN_OUTPUT.getErrorMessage(), - name))); + private Set validateManifest(ManifestContent manifestContent, GlobalValidationContext globalContext) { + Set baseFiles = ManifestUtil.getBaseFiles(manifestContent); + if (baseFiles == null || baseFiles.isEmpty()) { + globalContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_SRG_3, Messages.MISSIN_BASE_HEAT_FILE.getErrorMessage())); + } else if (baseFiles.size() > 1) { + String baseFileList = getElementListAsString(baseFiles); + globalContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_SRG_4, Messages.MULTI_BASE_HEAT_FILE.getErrorMessage(), baseFileList)); + } + return baseFiles; } - } - private void validateHeatVolumeFile(String fileName, Map fileTypeMap, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - //if not heat volume return - if (!fileTypeMap.get(fileName).equals(FileData.Type.HEAT_VOL)) { - return; + private void validate(String fileName, Map fileTypeMap, Set baseFiles, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_SRG_5); + HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; + } + validateBaseFile(fileName, baseFiles, heatOrchestrationTemplate, globalContext); + validateHeatVolumeFile(fileName, fileTypeMap, heatOrchestrationTemplate, globalContext); } - //if no resources exist return - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - return; + private void validateBaseFile(String fileName, Set baseFiles, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + //if not base return + if (baseFiles == null || !baseFiles.contains(fileName)) { + return; + } + //if no resources exist return + if (heatOrchestrationTemplate.getResources() == null || heatOrchestrationTemplate.getResources().size() == 0) { + return; + } + Set expectedExposedResources = new HashSet<>(); + heatOrchestrationTemplate.getResources().entrySet().stream().filter(entry -> ValidationUtil.isExpectedToBeExposed(entry.getValue().getType())) + .forEach(entry -> expectedExposedResources.add(entry.getKey())); + Set actualExposedResources = new HashSet<>(); + if (heatOrchestrationTemplate.getOutputs() != null) { + globalContext.setMessageCode(ERROR_CODE_SRG_6); + heatOrchestrationTemplate.getOutputs().entrySet().stream() + .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), globalContext)) + .forEach(entry -> actualExposedResources.add(getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), globalContext))); + } + ValidationUtil.removeExposedResourcesCalledByGetResource(fileName, actualExposedResources, heatOrchestrationTemplate, globalContext); + actualExposedResources.forEach(expectedExposedResources::remove); + if (CollectionUtils.isNotEmpty(expectedExposedResources)) { + expectedExposedResources.stream().forEach(name -> globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_SRG_1, Messages.RESOURCE_NOT_DEFINED_IN_OUTPUT.getErrorMessage(), name))); + } } - Set expectedExposedResources = new HashSet<>(); - Set actualExposedResources = new HashSet<>(); - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType() - .equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())) - .forEach(entry -> expectedExposedResources.add(entry.getKey())); - - if (heatOrchestrationTemplate.getOutputs() != null) { - globalContext.setMessageCode(ERROR_CODE_SRG_6); - heatOrchestrationTemplate.getOutputs().entrySet() - .stream() - .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), - globalContext)) - .forEach(entry -> actualExposedResources.add( - getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), - globalContext))); + private void validateHeatVolumeFile(String fileName, Map fileTypeMap, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + //if not heat volume return + if (!fileTypeMap.get(fileName).equals(FileData.Type.HEAT_VOL)) { + return; + } + //if no resources exist return + if (heatOrchestrationTemplate.getResources() == null || heatOrchestrationTemplate.getResources().size() == 0) { + return; + } + Set expectedExposedResources = new HashSet<>(); + Set actualExposedResources = new HashSet<>(); + heatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> entry.getValue().getType().equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())) + .forEach(entry -> expectedExposedResources.add(entry.getKey())); + if (heatOrchestrationTemplate.getOutputs() != null) { + globalContext.setMessageCode(ERROR_CODE_SRG_6); + heatOrchestrationTemplate.getOutputs().entrySet().stream() + .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), globalContext)) + .forEach(entry -> actualExposedResources.add(getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), globalContext))); + } + actualExposedResources.forEach(expectedExposedResources::remove); + if (CollectionUtils.isNotEmpty(expectedExposedResources)) { + expectedExposedResources.stream().forEach(name -> globalContext.addMessage(fileName, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_SRG_2, Messages.VOLUME_HEAT_NOT_EXPOSED.getErrorMessage(), name))); + } } - actualExposedResources.forEach(expectedExposedResources::remove); - - if (CollectionUtils.isNotEmpty(expectedExposedResources)) { - expectedExposedResources - .stream() - .forEach(name -> globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_SRG_2, - Messages.VOLUME_HEAT_NOT_EXPOSED.getErrorMessage(), name))); + private boolean isPropertyValueGetResource(String filename, Object value, GlobalValidationContext globalContext) { + Set referenceValues = HeatStructureUtil + .getReferencedValuesByFunctionName(filename, ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); + return referenceValues != null && (CollectionUtils.isNotEmpty(referenceValues)); } - } - - private boolean isPropertyValueGetResource(String filename, Object value, - GlobalValidationContext globalContext) { - Set referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); - return referenceValues != null && (CollectionUtils.isNotEmpty(referenceValues)); - } - - private String getResourceIdFromPropertyValue(String filename, Object value, - GlobalValidationContext globalContext) { - Set referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); - if (referenceValues != null && CollectionUtils.isNotEmpty(referenceValues)) { - return (String) referenceValues.toArray()[0]; + private String getResourceIdFromPropertyValue(String filename, Object value, GlobalValidationContext globalContext) { + Set referenceValues = HeatStructureUtil + .getReferencedValuesByFunctionName(filename, ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); + if (referenceValues != null && CollectionUtils.isNotEmpty(referenceValues)) { + return (String) referenceValues.toArray()[0]; + } + return null; } - return null; - } - } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java index c433c3e7d4..cb9469a146 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java @@ -14,9 +14,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators; +import java.io.InputStream; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import org.onap.sdc.tosca.services.MyPropertyUtils; import org.onap.sdc.tosca.services.StrictMapAppenderConstructor; import org.openecomp.core.validation.ErrorMessageCode; @@ -33,24 +37,16 @@ import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.representer.Representer; -import java.io.InputStream; -import java.util.Collection; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - public class YamlValidator implements Validator { + private static final ErrorMessageCode ERROR_CODE_YML_1 = new ErrorMessageCode("YML1"); private static final ErrorMessageCode ERROR_CODE_YML_2 = new ErrorMessageCode("YML2"); @Override public void validate(GlobalValidationContext globalContext) { Set pmDictionaryFiles = GlobalContextUtil.findPmDictionaryFiles(globalContext); - - Collection files = globalContext.files( - (fileName, globalValidationContext) -> FileExtensionUtils.isYaml(fileName) - && !pmDictionaryFiles.contains(fileName)); - + Collection files = globalContext + .files((fileName, globalValidationContext) -> FileExtensionUtils.isYaml(fileName) && !pmDictionaryFiles.contains(fileName)); files.forEach(fileName -> validate(fileName, globalContext)); } @@ -58,9 +54,8 @@ public class YamlValidator implements Validator { Optional rowContent = globalContext.getFileContent(fileName); if (rowContent.isEmpty()) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_YML_1, Messages - .INVALID_YAML_FORMAT_REASON.getErrorMessage(), - Messages.EMPTY_YAML_FILE.getErrorMessage())); + .getErrorWithParameters(ERROR_CODE_YML_1, Messages.INVALID_YAML_FORMAT_REASON.getErrorMessage(), + Messages.EMPTY_YAML_FILE.getErrorMessage())); return; /* no need to continue validation */ } @@ -80,10 +75,11 @@ public class YamlValidator implements Validator { } } catch (Exception exception) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_YML_2, Messages - .INVALID_YAML_FORMAT_REASON.getErrorMessage(), - YamlValidatorUtil.getParserExceptionReason(exception))); + .getErrorWithParameters(ERROR_CODE_YML_2, Messages + .INVALID_YAML_FORMAT_REASON.getErrorMessage(), + YamlValidatorUtil.getParserExceptionReason(exception))); } } } + diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java index 190ae3d2c0..a7b1f47862 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java @@ -19,6 +19,8 @@ */ package org.openecomp.sdc.validation.impl.validators.heatresource; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -32,70 +34,45 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; import org.openecomp.sdc.validation.type.ValidatorConstants; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 2/28/2017. */ public class ContrailNetworkPolicyResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HNP1 = new ErrorMessageCode("HNP1"); - private static final ErrorMessageCode ERROR_CODE_HNP2 = new ErrorMessageCode("HNP2"); - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - validateNetworkPolicyIsUsed(fileName, resourceEntry, globalContext, - (HeatResourceValidationContext) validationContext); - } + private static final ErrorMessageCode ERROR_CODE_HNP1 = new ErrorMessageCode("HNP1"); + private static final ErrorMessageCode ERROR_CODE_HNP2 = new ErrorMessageCode("HNP2"); - private static void validateNetworkPolicyIsUsed(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - HeatResourceValidationContext validationContext) { - Map>> referencedNetworkAttachPoliciesResources = - validationContext.getFileLevelResourceDependencies() - .get(HeatResourcesTypes.CONTRAIL_NETWORK_RULE_RESOURCE_TYPE.getHeatResource()); - - if (MapUtils.isEmpty(referencedNetworkAttachPoliciesResources)) { - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNP1, - Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), - ValidatorConstants.Network_Policy, resourceEntry.getKey())); - return; + private static void validateNetworkPolicyIsUsed(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + HeatResourceValidationContext validationContext) { + Map>> referencedNetworkAttachPoliciesResources = validationContext.getFileLevelResourceDependencies() + .get(HeatResourcesTypes.CONTRAIL_NETWORK_RULE_RESOURCE_TYPE.getHeatResource()); + if (MapUtils.isEmpty(referencedNetworkAttachPoliciesResources)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNP1, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), ValidatorConstants.Network_Policy, + resourceEntry.getKey())); + return; + } + handleNetworkAttachPolicyReferences(fileName, resourceEntry, referencedNetworkAttachPoliciesResources, globalContext); } - handleNetworkAttachPolicyReferences(fileName, resourceEntry, - referencedNetworkAttachPoliciesResources, globalContext); - } - - private static void handleNetworkAttachPolicyReferences(String fileName, - Map.Entry resourceEntry, - Map>> pointedNetworkAttachPolicies, - GlobalValidationContext globalContext) { - - Map> resourcesPointingToCurrNetworkAttachPolicy = - pointedNetworkAttachPolicies.get(resourceEntry.getKey()); - if (isNetworkAttachPolicyNotInUse(resourcesPointingToCurrNetworkAttachPolicy)) { - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNP2, - Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), - ValidatorConstants.Network_Policy, resourceEntry.getKey())); + private static void handleNetworkAttachPolicyReferences(String fileName, Map.Entry resourceEntry, + Map>> pointedNetworkAttachPolicies, + GlobalValidationContext globalContext) { + Map> resourcesPointingToCurrNetworkAttachPolicy = pointedNetworkAttachPolicies.get(resourceEntry.getKey()); + if (isNetworkAttachPolicyNotInUse(resourcesPointingToCurrNetworkAttachPolicy)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNP2, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), ValidatorConstants.Network_Policy, + resourceEntry.getKey())); + } } - } - private static boolean isNetworkAttachPolicyNotInUse( - Map> resourcesPointingToCurrNetworkAttachPolicy) { - return MapUtils.isEmpty(resourcesPointingToCurrNetworkAttachPolicy); - } + private static boolean isNetworkAttachPolicyNotInUse(Map> resourcesPointingToCurrNetworkAttachPolicy) { + return MapUtils.isEmpty(resourcesPointingToCurrNetworkAttachPolicy); + } + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateNetworkPolicyIsUsed(fileName, resourceEntry, globalContext, (HeatResourceValidationContext) validationContext); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java index 4a5a996777..06d1f8942f 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; import java.util.ArrayList; @@ -22,7 +21,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -38,64 +36,48 @@ import org.openecomp.sdc.validation.impl.util.HeatValidationService; * Created by TALIO on 2/22/2017. */ public class NestedResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HNR1 = new ErrorMessageCode("HNR1"); - private static final ErrorMessageCode ERROR_CODE_HNR2 = new ErrorMessageCode("HNR2"); - private static final ErrorMessageCode ERROR_CODE_HNR3 = new ErrorMessageCode("HNR3"); - private static final ErrorMessageCode ERROR_CODE_HNR4 = new ErrorMessageCode("HNR4"); - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { + private static final ErrorMessageCode ERROR_CODE_HNR1 = new ErrorMessageCode("HNR1"); + private static final ErrorMessageCode ERROR_CODE_HNR2 = new ErrorMessageCode("HNR2"); + private static final ErrorMessageCode ERROR_CODE_HNR3 = new ErrorMessageCode("HNR3"); + private static final ErrorMessageCode ERROR_CODE_HNR4 = new ErrorMessageCode("HNR4"); - handleNestedResourceType(fileName, resourceEntry.getKey(), resourceEntry.getValue(), - Optional.empty(), globalContext); - } + private static void handleNestedResourceType(String fileName, String resourceName, Resource resource, Optional indexVarValue, + GlobalValidationContext globalContext) { + validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, globalContext); + validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); + } - private static void handleNestedResourceType(String fileName, String resourceName, - Resource resource, Optional indexVarValue, - GlobalValidationContext globalContext) { - validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, - globalContext); - validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); - } + public static void validateAllPropertiesMatchNestedParameters(String fileName, String resourceName, Resource resource, + Optional indexVarValue, GlobalValidationContext globalContext) { + String resourceType = resource.getType(); + if (globalContext.getFileContextMap().containsKey(resourceType)) { + Set propertiesNames = resource.getProperties() == null ? null : resource.getProperties().keySet(); + if (CollectionUtils.isNotEmpty(propertiesNames)) { + globalContext.setMessageCode(ERROR_CODE_HNR3); + HeatValidationService + .checkNestedParametersNoMissingParameterInNested(fileName, resourceType, resourceName, propertiesNames, globalContext); + globalContext.setMessageCode(ERROR_CODE_HNR4); + HeatValidationService + .checkNestedInputValuesAlignWithType(fileName, resourceType, resourceName, resource, indexVarValue, globalContext); + } + } else { + globalContext.addMessage(resourceType, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_HNR1, Messages.MISSING_NESTED_FILE.getErrorMessage(), resourceType)); + } + } - public static void validateAllPropertiesMatchNestedParameters(String fileName, - String resourceName, - Resource resource, - Optional indexVarValue, - GlobalValidationContext - globalContext) { - String resourceType = resource.getType(); - if (globalContext.getFileContextMap().containsKey(resourceType)) { - Set propertiesNames = - resource.getProperties() == null ? null : resource.getProperties().keySet(); - if (CollectionUtils.isNotEmpty(propertiesNames)) { - globalContext.setMessageCode(ERROR_CODE_HNR3); - HeatValidationService - .checkNestedParametersNoMissingParameterInNested(fileName, resourceType, resourceName, - propertiesNames, - globalContext); - globalContext.setMessageCode(ERROR_CODE_HNR4); - HeatValidationService - .checkNestedInputValuesAlignWithType(fileName, resourceType, resourceName, resource, - indexVarValue, globalContext); - } - } else { - globalContext.addMessage(resourceType, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNR1, - Messages.MISSING_NESTED_FILE.getErrorMessage(), - resourceType)); + public static void validateLoopsOfNestingFromFile(String fileName, String resourceType, GlobalValidationContext globalContext) { + List filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); + if (HeatValidationService.isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNR2, Messages.NESTED_LOOP.getErrorMessage(), HeatValidationService.drawFilesLoop(filesInLoop))); + } } - } - public static void validateLoopsOfNestingFromFile(String fileName, String resourceType, - GlobalValidationContext globalContext) { - List filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); - if (HeatValidationService - .isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNR2, Messages.NESTED_LOOP.getErrorMessage(), - HeatValidationService.drawFilesLoop(filesInLoop))); + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + handleNestedResourceType(fileName, resourceEntry.getKey(), resourceEntry.getValue(), Optional.empty(), globalContext); } - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java index a21173a6b2..08177a158e 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; import java.util.ArrayList; @@ -33,90 +32,57 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; public class NeutronPortResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_HPRODE_HPR1 = new ErrorMessageCode("HPR1"); - private static final ErrorMessageCode ERROR_HPRODE_HPR2 = new ErrorMessageCode("HPR2"); - private static final ErrorMessageCode ERROR_HPRODE_HPR3 = new ErrorMessageCode("HPR3"); - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - - validateNovaServerPortBinding(fileName, - resourceEntry, (HeatResourceValidationContext) validationContext, globalContext); - } - - @SuppressWarnings("unchecked") - private static void validateNovaServerPortBinding(String fileName, - Map.Entry resourceEntry, - HeatResourceValidationContext heatResourceValidationContext, - GlobalValidationContext globalContext) { - Map>> portIdToPointingResources = - heatResourceValidationContext.getFileLevelResourceDependencies() - .get(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); - - String portResourceId = resourceEntry.getKey(); - if (MapUtils.isEmpty(portIdToPointingResources)) { - globalContext - .addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_HPRODE_HPR1, Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), - portResourceId)); - - return; + private static final ErrorMessageCode ERROR_HPRODE_HPR1 = new ErrorMessageCode("HPR1"); + private static final ErrorMessageCode ERROR_HPRODE_HPR2 = new ErrorMessageCode("HPR2"); + private static final ErrorMessageCode ERROR_HPRODE_HPR3 = new ErrorMessageCode("HPR3"); + + @SuppressWarnings("unchecked") + private static void validateNovaServerPortBinding(String fileName, Map.Entry resourceEntry, + HeatResourceValidationContext heatResourceValidationContext, + GlobalValidationContext globalContext) { + Map>> portIdToPointingResources = heatResourceValidationContext.getFileLevelResourceDependencies() + .get(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); + String portResourceId = resourceEntry.getKey(); + if (MapUtils.isEmpty(portIdToPointingResources)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_HPRODE_HPR1, Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), portResourceId)); + return; + } + Map> pointingResourcesToCurrPort = portIdToPointingResources.get(portResourceId); + checkPortBindingFromMap(fileName, portResourceId, pointingResourcesToCurrPort, globalContext); } - Map> pointingResourcesToCurrPort = - portIdToPointingResources.get(portResourceId); - checkPortBindingFromMap( - fileName, portResourceId, pointingResourcesToCurrPort, globalContext); - } - - private static void checkPortBindingFromMap(String fileName, - String portResourceId, - Map> resourcesPointingToCurrPort, - GlobalValidationContext globalContext) { - List pointingNovaServers = - MapUtils.isEmpty(resourcesPointingToCurrPort) ? new ArrayList<>() - : resourcesPointingToCurrPort.get(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); - - handleErrorEventsForPortBinding( - fileName, portResourceId, globalContext, pointingNovaServers); - - - } + private static void checkPortBindingFromMap(String fileName, String portResourceId, Map> resourcesPointingToCurrPort, + GlobalValidationContext globalContext) { + List pointingNovaServers = MapUtils.isEmpty(resourcesPointingToCurrPort) ? new ArrayList<>() + : resourcesPointingToCurrPort.get(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); + handleErrorEventsForPortBinding(fileName, portResourceId, globalContext, pointingNovaServers); + } - private static void handleErrorEventsForPortBinding(String fileName, - String portResourceId, - GlobalValidationContext globalContext, - List pointingNovaServers) { - if (isThereMoreThanOneBindFromNovaToPort(pointingNovaServers)) { - globalContext - .addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_HPRODE_HPR2, - Messages.MORE_THAN_ONE_BIND_FROM_NOVA_TO_PORT.getErrorMessage(), - portResourceId)); + private static void handleErrorEventsForPortBinding(String fileName, String portResourceId, GlobalValidationContext globalContext, + List pointingNovaServers) { + if (isThereMoreThanOneBindFromNovaToPort(pointingNovaServers)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_HPRODE_HPR2, Messages.MORE_THAN_ONE_BIND_FROM_NOVA_TO_PORT.getErrorMessage(), portResourceId)); + } + if (isNoNovaPointingToPort(pointingNovaServers)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_HPRODE_HPR3, Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), portResourceId)); + } } - if (isNoNovaPointingToPort(pointingNovaServers)) { - globalContext - .addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_HPRODE_HPR3, Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), - portResourceId)); + private static boolean isNoNovaPointingToPort(List pointingNovaServers) { + return CollectionUtils.isEmpty(pointingNovaServers); } - } - private static boolean isNoNovaPointingToPort(List pointingNovaServers) { - return CollectionUtils.isEmpty(pointingNovaServers); - } + private static boolean isThereMoreThanOneBindFromNovaToPort(List pointingNovaServers) { + return CollectionUtils.isNotEmpty(pointingNovaServers) && pointingNovaServers.size() > 1; + } - private static boolean isThereMoreThanOneBindFromNovaToPort(List pointingNovaServers) { - return CollectionUtils.isNotEmpty(pointingNovaServers) - && pointingNovaServers.size() > 1; - } + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateNovaServerPortBinding(fileName, resourceEntry, (HeatResourceValidationContext) validationContext, globalContext); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java index d9ba1aeaed..48a6d01143 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java @@ -19,6 +19,8 @@ */ package org.openecomp.sdc.validation.impl.validators.heatresource; +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -32,56 +34,36 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; import org.openecomp.sdc.validation.type.ValidatorConstants; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 2/27/2017. */ public class NeutronSecurityGroupResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HSG1 = new ErrorMessageCode("HSG1"); - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - HeatResourceValidationContext heatResourceValidationContext = - (HeatResourceValidationContext) validationContext; - validateSecurityGroupIsUsed(fileName, resourceEntry, heatResourceValidationContext, - globalContext); - } + private static final ErrorMessageCode ERROR_CODE_HSG1 = new ErrorMessageCode("HSG1"); - private void validateSecurityGroupIsUsed(String fileName, - Map.Entry resourceEntry, - HeatResourceValidationContext - heatResourceValidationContext, - GlobalValidationContext globalContext) { - - Map>> securityGroupsPointedByOtherResources = - heatResourceValidationContext.getFileLevelResourceDependencies() - .get(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); - - if (MapUtils.isEmpty(securityGroupsPointedByOtherResources)) { - return; + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + HeatResourceValidationContext heatResourceValidationContext = (HeatResourceValidationContext) validationContext; + validateSecurityGroupIsUsed(fileName, resourceEntry, heatResourceValidationContext, globalContext); } - Map> resourcesPointingCurrSecurityGroup = - securityGroupsPointedByOtherResources.get(resourceEntry.getKey()); - - if (isSecurityGroupNotInUse(resourcesPointingCurrSecurityGroup)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HSG1, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), - ValidatorConstants.Security_Group, resourceEntry.getKey())); + private void validateSecurityGroupIsUsed(String fileName, Map.Entry resourceEntry, + HeatResourceValidationContext heatResourceValidationContext, GlobalValidationContext globalContext) { + Map>> securityGroupsPointedByOtherResources = heatResourceValidationContext + .getFileLevelResourceDependencies().get(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + if (MapUtils.isEmpty(securityGroupsPointedByOtherResources)) { + return; + } + Map> resourcesPointingCurrSecurityGroup = securityGroupsPointedByOtherResources.get(resourceEntry.getKey()); + if (isSecurityGroupNotInUse(resourcesPointingCurrSecurityGroup)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HSG1, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), ValidatorConstants.Security_Group, + resourceEntry.getKey())); + } } - } - - private boolean isSecurityGroupNotInUse(Map> - referencingResourcesToCurrSecurityGroup) { - return MapUtils.isEmpty(referencingResourcesToCurrSecurityGroup); - } + private boolean isSecurityGroupNotInUse(Map> referencingResourcesToCurrSecurityGroup) { + return MapUtils.isEmpty(referencingResourcesToCurrSecurityGroup); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java index 72226d96f4..6083670481 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; +import java.util.List; +import java.util.Map; +import java.util.Objects; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -30,100 +32,69 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; import org.openecomp.sdc.validation.type.ValidatorConstants; -import java.util.List; -import java.util.Map; -import java.util.Objects; - public class NovaServerGroupResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HNG1 = new ErrorMessageCode("HNG1"); - private static final ErrorMessageCode ERROR_CODE_HNG2 = new ErrorMessageCode("HNG2"); - private static final ErrorMessageCode ERROR_CODE_HNG3 = new ErrorMessageCode("HNG3"); - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - validateNovaServerGroupPolicy(fileName, resourceEntry, globalContext); - validateServerGroupIsUsed(fileName, resourceEntry, globalContext, - (HeatResourceValidationContext) validationContext); - } + private static final ErrorMessageCode ERROR_CODE_HNG1 = new ErrorMessageCode("HNG1"); + private static final ErrorMessageCode ERROR_CODE_HNG2 = new ErrorMessageCode("HNG2"); + private static final ErrorMessageCode ERROR_CODE_HNG3 = new ErrorMessageCode("HNG3"); - @SuppressWarnings("unchecked") - private static void validateNovaServerGroupPolicy(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - Resource resource = resourceEntry.getValue(); - Object policies = - resource.getProperties() == null ? null : resource.getProperties().get("policies"); - - if (Objects.nonNull(policies) && policies instanceof List) { - List policiesList = (List) policies; - if (policiesList.size() == 1) { - Object policy = policiesList.get(0); - if (!isGivenPolicyValid(policy)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HNG1, Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), - resourceEntry.getKey())); + @SuppressWarnings("unchecked") + private static void validateNovaServerGroupPolicy(String fileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + Resource resource = resourceEntry.getValue(); + Object policies = resource.getProperties() == null ? null : resource.getProperties().get("policies"); + if (Objects.nonNull(policies) && policies instanceof List) { + List policiesList = (List) policies; + if (policiesList.size() == 1) { + Object policy = policiesList.get(0); + if (!isGivenPolicyValid(policy)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNG1, Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), resourceEntry.getKey())); + } + } else { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNG1, Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), resourceEntry.getKey())); + } } - } else { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNG1, - Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), - resourceEntry.getKey())); - } } - } - private static boolean isGivenPolicyValid(Object policy) { - if (policy instanceof Map) { - return true; - } - if (policy instanceof String) { - return PolicyTypes.isGivenPolicyValid((String) policy); + private static boolean isGivenPolicyValid(Object policy) { + if (policy instanceof Map) { + return true; + } + if (policy instanceof String) { + return PolicyTypes.isGivenPolicyValid((String) policy); + } + return false; } - return false; - } - - public void validateServerGroupIsUsed(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - HeatResourceValidationContext validationContext) { - Map>> pointedServerGroups = - validationContext.getFileLevelResourceDependencies().get(HeatResourcesTypes - .NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); - - if (MapUtils.isEmpty(pointedServerGroups)) { - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HNG2, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), - ValidatorConstants.Server_Group, resourceEntry.getKey())); - return; + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateNovaServerGroupPolicy(fileName, resourceEntry, globalContext); + validateServerGroupIsUsed(fileName, resourceEntry, globalContext, (HeatResourceValidationContext) validationContext); } - handleServerGroupReferences(fileName, resourceEntry, pointedServerGroups, globalContext); - } - - private void handleServerGroupReferences(String fileName, Map.Entry - resourceEntry, Map>> pointedServerGroups, - GlobalValidationContext globalContext) { - Map> resourcesPointingToCurrServerGroup = - pointedServerGroups.get(resourceEntry.getKey()); - - if (MapUtils.isEmpty(resourcesPointingToCurrServerGroup)) { - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HNG3, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), - ValidatorConstants.Server_Group, resourceEntry.getKey())); + public void validateServerGroupIsUsed(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + HeatResourceValidationContext validationContext) { + Map>> pointedServerGroups = validationContext.getFileLevelResourceDependencies() + .get(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + if (MapUtils.isEmpty(pointedServerGroups)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNG2, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), ValidatorConstants.Server_Group, + resourceEntry.getKey())); + return; + } + handleServerGroupReferences(fileName, resourceEntry, pointedServerGroups, globalContext); } - } + private void handleServerGroupReferences(String fileName, Map.Entry resourceEntry, + Map>> pointedServerGroups, GlobalValidationContext globalContext) { + Map> resourcesPointingToCurrServerGroup = pointedServerGroups.get(resourceEntry.getKey()); + if (MapUtils.isEmpty(resourcesPointingToCurrServerGroup)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNG3, Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), ValidatorConstants.Server_Group, + resourceEntry.getKey())); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java index d261c8e9eb..bf5f1256d5 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java @@ -13,102 +13,86 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.heat.datatypes.model.*; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.PropertiesMapKeyTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; -import java.util.Map; - public class NovaServerResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HNS1 = new ErrorMessageCode("HNS1"); - private static final ErrorMessageCode ERROR_CODE_HNS2 = new ErrorMessageCode("HNS2"); - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { + private static final ErrorMessageCode ERROR_CODE_HNS1 = new ErrorMessageCode("HNS1"); + private static final ErrorMessageCode ERROR_CODE_HNS2 = new ErrorMessageCode("HNS2"); - HeatResourceValidationContext heatResourceValidationContext = (HeatResourceValidationContext) - validationContext; - validateNovaServerResourceType (fileName, - resourceEntry, heatResourceValidationContext, globalContext ); - } - - private static void validateNovaServerResourceType(String fileName, - Map.Entry resourceEntry, - HeatResourceValidationContext heatResourceValidationContext, - GlobalValidationContext globalContext) { - validateAssignedValueForImageOrFlavorFromNova(fileName, resourceEntry, globalContext); - validateAllServerGroupsPointedByServerExistAndDefined (fileName, - resourceEntry, heatResourceValidationContext.getHeatOrchestrationTemplate(), globalContext ); - } - - private static void validateAssignedValueForImageOrFlavorFromNova(String fileName, - Map.Entry - resourceEntry, - GlobalValidationContext - globalContext) { - Resource resource = resourceEntry.getValue(); - Map propertiesMap = resource.getProperties(); - if (propertiesMap.get(PropertiesMapKeyTypes.IMAGE.getKeyMap()) == null - && propertiesMap.get(PropertiesMapKeyTypes.FLAVOR.getKeyMap()) == null) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNS1, Messages.MISSING_IMAGE_AND_FLAVOR.getErrorMessage(), - resourceEntry.getKey())); + private static void validateNovaServerResourceType(String fileName, Map.Entry resourceEntry, + HeatResourceValidationContext heatResourceValidationContext, + GlobalValidationContext globalContext) { + validateAssignedValueForImageOrFlavorFromNova(fileName, resourceEntry, globalContext); + validateAllServerGroupsPointedByServerExistAndDefined(fileName, resourceEntry, heatResourceValidationContext.getHeatOrchestrationTemplate(), + globalContext); } - } - @SuppressWarnings("unchecked") - private static void validateAllServerGroupsPointedByServerExistAndDefined(String fileName, - Map.Entry resourceEntry, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map resourcesMap = heatOrchestrationTemplate.getResources(); - Map resourceProperties = resourceEntry.getValue().getProperties(); - Map schedulerHintsMap = - resourceProperties == null ? null : (Map) resourceProperties.get( - ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); - - if (MapUtils.isEmpty(schedulerHintsMap)) { - return; + private static void validateAssignedValueForImageOrFlavorFromNova(String fileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + Resource resource = resourceEntry.getValue(); + Map propertiesMap = resource.getProperties(); + if (propertiesMap.get(PropertiesMapKeyTypes.IMAGE.getKeyMap()) == null + && propertiesMap.get(PropertiesMapKeyTypes.FLAVOR.getKeyMap()) == null) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNS1, Messages.MISSING_IMAGE_AND_FLAVOR.getErrorMessage(), resourceEntry.getKey())); + } } - validateServerGroupValue(fileName, resourceEntry, globalContext, resourcesMap, schedulerHintsMap); - } - - private static void validateServerGroupValue(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, - Map resourcesMap, Map schedulerHintsMap) { - if (schedulerHintsMap != null) { - for (Object serverGroupValue : schedulerHintsMap.values()) { - if (!(serverGroupValue instanceof Map)) { - continue; + @SuppressWarnings("unchecked") + private static void validateAllServerGroupsPointedByServerExistAndDefined(String fileName, Map.Entry resourceEntry, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map resourcesMap = heatOrchestrationTemplate.getResources(); + Map resourceProperties = resourceEntry.getValue().getProperties(); + Map schedulerHintsMap = resourceProperties == null ? null + : (Map) resourceProperties.get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); + if (MapUtils.isEmpty(schedulerHintsMap)) { + return; } - Map currentServerMap = (Map) serverGroupValue; - String serverResourceName = (String) currentServerMap - .get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); - Resource serverResource = - serverResourceName == null || resourcesMap == null ? null - : resourcesMap.get(serverResourceName); + validateServerGroupValue(fileName, resourceEntry, globalContext, resourcesMap, schedulerHintsMap); + } - if (serverResource != null && !serverResource.getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource())) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HNS2, - Messages.SERVER_NOT_DEFINED_FROM_NOVA.getErrorMessage(), - serverResourceName, resourceEntry.getKey())); + private static void validateServerGroupValue(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + Map resourcesMap, Map schedulerHintsMap) { + if (schedulerHintsMap != null) { + for (Object serverGroupValue : schedulerHintsMap.values()) { + if (!(serverGroupValue instanceof Map)) { + continue; + } + Map currentServerMap = (Map) serverGroupValue; + String serverResourceName = (String) currentServerMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); + Resource serverResource = serverResourceName == null || resourcesMap == null ? null : resourcesMap.get(serverResourceName); + if (serverResource != null && !serverResource.getType() + .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource())) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HNS2, Messages.SERVER_NOT_DEFINED_FROM_NOVA.getErrorMessage(), serverResourceName, + resourceEntry.getKey())); + } + } } - } } - } + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + HeatResourceValidationContext heatResourceValidationContext = (HeatResourceValidationContext) validationContext; + validateNovaServerResourceType(fileName, resourceEntry, heatResourceValidationContext, globalContext); + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java index be0d1e2f88..98776c65fc 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; import java.util.ArrayList; @@ -23,7 +22,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -41,114 +39,81 @@ import org.openecomp.sdc.validation.impl.util.HeatValidationService; * Created by TALIO on 2/22/2017. */ public class ResourceGroupResourceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_HRR1 = new ErrorMessageCode("HRR1"); - private static final ErrorMessageCode ERROR_CODE_HRR2 = new ErrorMessageCode("HRR2"); - private static final ErrorMessageCode ERROR_CODE_HRR3 = new ErrorMessageCode("HRR3"); - private static final ErrorMessageCode ERROR_CODE_HRR4 = new ErrorMessageCode("HRR4"); - private static final ErrorMessageCode ERROR_CODE_HRR5 = new ErrorMessageCode("HRR5"); - private static final ErrorMessageCode ERROR_CODE_HRR6 = new ErrorMessageCode("HRR6"); - private static final ErrorMessageCode ERROR_CODE_HRR7 = new ErrorMessageCode("HRR7"); - private static final ErrorMessageCode ERROR_CODE_HRR8 = new ErrorMessageCode("HRR8"); - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - validateResourceGroupType(fileName, resourceEntry, globalContext); - } - private static void validateResourceGroupType(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_HRR6); - HeatTreeManagerUtil - .checkResourceTypeValid(fileName, resourceEntry.getKey(), resourceEntry.getValue(), - globalContext); - globalContext.setMessageCode(ERROR_CODE_HRR7); - HeatTreeManagerUtil - .checkResourceGroupTypeValid(fileName, resourceEntry.getKey(), resourceEntry.getValue(), - globalContext); - globalContext.setMessageCode(ERROR_CODE_HRR8); - HeatTreeManagerUtil.checkIfResourceGroupTypeIsNested(fileName, resourceEntry.getKey(), - resourceEntry.getValue(), globalContext); - Resource resourceDef = HeatTreeManagerUtil - .getResourceDef( resourceEntry.getValue()); - - if (resourceDef != null && Objects.nonNull(resourceDef.getType()) - && HeatValidationService.isNestedResource(resourceDef.getType())) { - Optional indexVarValue = - getResourceGroupIndexVarValue(resourceEntry, fileName, globalContext); - handleNestedResourceType(fileName, resourceEntry.getKey(), resourceDef, indexVarValue, - globalContext); + private static final ErrorMessageCode ERROR_CODE_HRR1 = new ErrorMessageCode("HRR1"); + private static final ErrorMessageCode ERROR_CODE_HRR2 = new ErrorMessageCode("HRR2"); + private static final ErrorMessageCode ERROR_CODE_HRR3 = new ErrorMessageCode("HRR3"); + private static final ErrorMessageCode ERROR_CODE_HRR4 = new ErrorMessageCode("HRR4"); + private static final ErrorMessageCode ERROR_CODE_HRR5 = new ErrorMessageCode("HRR5"); + private static final ErrorMessageCode ERROR_CODE_HRR6 = new ErrorMessageCode("HRR6"); + private static final ErrorMessageCode ERROR_CODE_HRR7 = new ErrorMessageCode("HRR7"); + private static final ErrorMessageCode ERROR_CODE_HRR8 = new ErrorMessageCode("HRR8"); + private static void validateResourceGroupType(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_HRR6); + HeatTreeManagerUtil.checkResourceTypeValid(fileName, resourceEntry.getKey(), resourceEntry.getValue(), globalContext); + globalContext.setMessageCode(ERROR_CODE_HRR7); + HeatTreeManagerUtil.checkResourceGroupTypeValid(fileName, resourceEntry.getKey(), resourceEntry.getValue(), globalContext); + globalContext.setMessageCode(ERROR_CODE_HRR8); + HeatTreeManagerUtil.checkIfResourceGroupTypeIsNested(fileName, resourceEntry.getKey(), resourceEntry.getValue(), globalContext); + Resource resourceDef = HeatTreeManagerUtil.getResourceDef(resourceEntry.getValue()); + if (resourceDef != null && Objects.nonNull(resourceDef.getType()) && HeatValidationService.isNestedResource(resourceDef.getType())) { + Optional indexVarValue = getResourceGroupIndexVarValue(resourceEntry, fileName, globalContext); + handleNestedResourceType(fileName, resourceEntry.getKey(), resourceDef, indexVarValue, globalContext); + } } - } - private static Optional getResourceGroupIndexVarValue( - Map.Entry resourceEntry, String fileName, - GlobalValidationContext globalContext) { - Object indexVar = - resourceEntry.getValue().getProperties().get(HeatConstants.INDEX_PROPERTY_NAME); - if (indexVar == null) { - return Optional.of(HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE); + private static Optional getResourceGroupIndexVarValue(Map.Entry resourceEntry, String fileName, + GlobalValidationContext globalContext) { + Object indexVar = resourceEntry.getValue().getProperties().get(HeatConstants.INDEX_PROPERTY_NAME); + if (indexVar == null) { + return Optional.of(HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE); + } + if (indexVar instanceof String) { + return Optional.of((String) indexVar); + } else { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HRR1, Messages.RESOURCE_GROUP_INVALID_INDEX_VAR.getErrorMessage(), resourceEntry.getKey())); + return Optional.empty(); + } } - if (indexVar instanceof String) { - return Optional.of((String) indexVar); - } else { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HRR1, Messages.RESOURCE_GROUP_INVALID_INDEX_VAR.getErrorMessage(), - resourceEntry.getKey())); - return Optional.empty(); + private static void handleNestedResourceType(String fileName, String resourceName, Resource resource, Optional indexVarValue, + GlobalValidationContext globalContext) { + validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, globalContext); + validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); } - } - private static void handleNestedResourceType(String fileName, String resourceName, - Resource resource, Optional indexVarValue, - GlobalValidationContext globalContext) { - validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, - globalContext); - validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); - } + private static void validateAllPropertiesMatchNestedParameters(String fileName, String resourceName, Resource resource, + Optional indexVarValue, GlobalValidationContext globalContext) { + String resourceType = resource.getType(); + if (globalContext.getFileContextMap().containsKey(resourceType)) { + Set propertiesNames = resource.getProperties() == null ? null : resource.getProperties().keySet(); + if (CollectionUtils.isNotEmpty(propertiesNames)) { + globalContext.setMessageCode(ERROR_CODE_HRR4); + HeatValidationService + .checkNestedParametersNoMissingParameterInNested(fileName, resourceType, resourceName, propertiesNames, globalContext); + globalContext.setMessageCode(ERROR_CODE_HRR5); + HeatValidationService + .checkNestedInputValuesAlignWithType(fileName, resourceType, resourceName, resource, indexVarValue, globalContext); + } + } else { + globalContext.addMessage(resourceType, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_HRR2, Messages.MISSING_NESTED_FILE.getErrorMessage(), resourceType)); + } + } - private static void validateAllPropertiesMatchNestedParameters(String fileName, - String resourceName, - Resource resource, - Optional indexVarValue, - GlobalValidationContext - globalContext) { - String resourceType = resource.getType(); - if (globalContext.getFileContextMap().containsKey(resourceType)) { - Set propertiesNames = - resource.getProperties() == null ? null : resource.getProperties().keySet(); - if (CollectionUtils.isNotEmpty(propertiesNames)) { - globalContext.setMessageCode(ERROR_CODE_HRR4); - HeatValidationService - .checkNestedParametersNoMissingParameterInNested(fileName, resourceType, resourceName, - propertiesNames, - globalContext); - globalContext.setMessageCode(ERROR_CODE_HRR5); - HeatValidationService - .checkNestedInputValuesAlignWithType(fileName, resourceType, resourceName, resource, - indexVarValue, globalContext); - } - } else { - globalContext.addMessage(resourceType, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HRR2, Messages.MISSING_NESTED_FILE.getErrorMessage(), - resourceType)); + private static void validateLoopsOfNestingFromFile(String fileName, String resourceType, GlobalValidationContext globalContext) { + List filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); + if (HeatValidationService.isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HRR3, Messages.NESTED_LOOP.getErrorMessage(), HeatValidationService.drawFilesLoop(filesInLoop))); + } } - } - private static void validateLoopsOfNestingFromFile(String fileName, String resourceType, - GlobalValidationContext globalContext) { - List filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); - if (HeatValidationService - .isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_HRR3, Messages.NESTED_LOOP.getErrorMessage(), - HeatValidationService.drawFilesLoop(filesInLoop))); + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateResourceGroupType(fileName, resourceEntry, globalContext); } - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/VirtualMachineInterfaceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/VirtualMachineInterfaceValidator.java index 016b911c81..d1b3d9bad3 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/VirtualMachineInterfaceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/VirtualMachineInterfaceValidator.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.heatresource; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; @@ -27,138 +29,97 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.impl.util.HeatValidationService; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class VirtualMachineInterfaceValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_VLAN1 = new ErrorMessageCode("VLAN1"); - private static final ErrorMessageCode ERROR_CODE_VLAN2 = new ErrorMessageCode("VLAN2"); - - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - HeatResourceValidationContext heatResourceValidationContext = - (HeatResourceValidationContext) validationContext; - final ValidityStatus status = calculateValidityStatus(resourceEntry.getValue()); - switch (status) { - case BOTH_PROPERTIES_PRESENT: - validateHasSingleParentPort(fileName, resourceEntry, globalContext, - heatResourceValidationContext); - break; - case REFS_PROPERTY_MISSING: - globalContext - .addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_VLAN2, - Messages.VLAN_SUBINTERFACE_MISSING_REFS_PROPERTY.getErrorMessage(), - resourceEntry.getKey())); - break; - case VLAN_TAG_PROPERTY_MISSING: - globalContext - .addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_VLAN2, - Messages.VLAN_SUBINTERFACE_MISSING_TAG_PROPERTY.getErrorMessage(), - resourceEntry.getKey())); - validateHasSingleParentPort(fileName, resourceEntry, globalContext, - heatResourceValidationContext); - break; - case BOTH_PROPERTIES_MISSING: - // this is a port and not a VLAN, no further validation required - break; - default : - throw new IllegalArgumentException("Received a value for which no handling is " + - "available " + status); - } - } - - private ValidityStatus calculateValidityStatus(Resource resource) { - Optional refsPropertyValue = getRefsPropertyValue(resource); - Optional tagPropertyValue = getVlanTagPropertyValue(resource); - - if (refsPropertyValue.isPresent() && tagPropertyValue.isPresent()) { - return ValidityStatus.BOTH_PROPERTIES_PRESENT; - } - if (!refsPropertyValue.isPresent() && !tagPropertyValue.isPresent()) { - return ValidityStatus.BOTH_PROPERTIES_MISSING; + private static final ErrorMessageCode ERROR_CODE_VLAN1 = new ErrorMessageCode("VLAN1"); + private static final ErrorMessageCode ERROR_CODE_VLAN2 = new ErrorMessageCode("VLAN2"); + + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + HeatResourceValidationContext heatResourceValidationContext = (HeatResourceValidationContext) validationContext; + final ValidityStatus status = calculateValidityStatus(resourceEntry.getValue()); + switch (status) { + case BOTH_PROPERTIES_PRESENT: + validateHasSingleParentPort(fileName, resourceEntry, globalContext, heatResourceValidationContext); + break; + case REFS_PROPERTY_MISSING: + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_VLAN2, Messages.VLAN_SUBINTERFACE_MISSING_REFS_PROPERTY.getErrorMessage(), + resourceEntry.getKey())); + break; + case VLAN_TAG_PROPERTY_MISSING: + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_VLAN2, Messages.VLAN_SUBINTERFACE_MISSING_TAG_PROPERTY.getErrorMessage(), + resourceEntry.getKey())); + validateHasSingleParentPort(fileName, resourceEntry, globalContext, heatResourceValidationContext); + break; + case BOTH_PROPERTIES_MISSING: + // this is a port and not a VLAN, no further validation required + break; + default: + throw new IllegalArgumentException("Received a value for which no handling is " + "available " + status); + } } - return refsPropertyValue.map(o -> ValidityStatus.VLAN_TAG_PROPERTY_MISSING) - .orElse(ValidityStatus.REFS_PROPERTY_MISSING); - } - - private void validateHasSingleParentPort(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - HeatResourceValidationContext heatResourceValidationContext) { - Object refsPropertyValue = resourceEntry.getValue().getProperties() - .get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(refsPropertyValue)) { - return; - } - boolean hasSingleParentPort = HeatValidationService.hasSingleParentPort(fileName, globalContext, - heatResourceValidationContext, - refsPropertyValue); - if (!hasSingleParentPort) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_VLAN1, - Messages.VLAN_SUBINTERFACE_MORE_THAN_ONE_PORT.getErrorMessage(), - resourceEntry.getKey())); + private ValidityStatus calculateValidityStatus(Resource resource) { + Optional refsPropertyValue = getRefsPropertyValue(resource); + Optional tagPropertyValue = getVlanTagPropertyValue(resource); + if (refsPropertyValue.isPresent() && tagPropertyValue.isPresent()) { + return ValidityStatus.BOTH_PROPERTIES_PRESENT; + } + if (!refsPropertyValue.isPresent() && !tagPropertyValue.isPresent()) { + return ValidityStatus.BOTH_PROPERTIES_MISSING; + } + return refsPropertyValue.map(o -> ValidityStatus.VLAN_TAG_PROPERTY_MISSING).orElse(ValidityStatus.REFS_PROPERTY_MISSING); } - - } - - - private Optional getVlanTagPropertyValue(Resource resource) { - Object vmiProperties = resource.getProperties() - .get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); - if (Objects.nonNull(vmiProperties) && vmiProperties instanceof Map) { - return Optional.ofNullable(((Map) vmiProperties) - .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + private void validateHasSingleParentPort(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + HeatResourceValidationContext heatResourceValidationContext) { + Object refsPropertyValue = resourceEntry.getValue().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); + if (Objects.isNull(refsPropertyValue)) { + return; + } + boolean hasSingleParentPort = HeatValidationService + .hasSingleParentPort(fileName, globalContext, heatResourceValidationContext, refsPropertyValue); + if (!hasSingleParentPort) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_VLAN1, Messages.VLAN_SUBINTERFACE_MORE_THAN_ONE_PORT.getErrorMessage(), resourceEntry.getKey())); + } } - return Optional.empty(); - } - - private Optional getRefsPropertyValue(Resource resource) { - Object refsProperty = resource.getProperties() - .get(HeatConstants.VMI_REFS_PROPERTY_NAME); - return Optional.ofNullable(refsProperty); - - } + private Optional getVlanTagPropertyValue(Resource resource) { + Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); + if (Objects.nonNull(vmiProperties) && vmiProperties instanceof Map) { + return Optional.ofNullable(((Map) vmiProperties).get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + } + return Optional.empty(); + } - private enum ValidityStatus { - BOTH_PROPERTIES_MISSING, - BOTH_PROPERTIES_PRESENT, - REFS_PROPERTY_MISSING, - VLAN_TAG_PROPERTY_MISSING + private Optional getRefsPropertyValue(Resource resource) { + Object refsProperty = resource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); + return Optional.ofNullable(refsProperty); + } - } + private enum ValidityStatus {BOTH_PROPERTIES_MISSING, BOTH_PROPERTIES_PRESENT, REFS_PROPERTY_MISSING, VLAN_TAG_PROPERTY_MISSING} - private enum Messages { - VLAN_SUBINTERFACE_MORE_THAN_ONE_PORT( - "More than one parent port found, there should be only one parent port for a VLAN sub-interface ID [%s]"), - VLAN_SUBINTERFACE_MISSING_TAG_PROPERTY("VLAN Tag property " + - "virtual_machine_interface_properties_sub_interface_vlan_tag is missing in VLAN Resource ID [%s]"), - VLAN_SUBINTERFACE_MISSING_REFS_PROPERTY("Parent port property virtual_machine_interface_refs " + - "is missing in VLAN Resource ID [%s]"); + private enum Messages { + // @formatter:off + VLAN_SUBINTERFACE_MORE_THAN_ONE_PORT("More than one parent port found, there should be only one parent port for " + + "a VLAN sub-interface ID [%s]"), + VLAN_SUBINTERFACE_MISSING_TAG_PROPERTY("VLAN Tag property virtual_machine_interface_properties_sub_interface_vlan_tag is missing " + + "in VLAN Resource ID [%s]"), + VLAN_SUBINTERFACE_MISSING_REFS_PROPERTY("Parent port property virtual_machine_interface_refs is missing in VLAN Resource ID [%s]"); + // @formatter:on - String getErrorMessage() { - return errorMessage; - } + private final String errorMessage; - private final String errorMessage; + Messages(String errorMessage) { + this.errorMessage = errorMessage; + } - Messages(String errorMessage) { - this.errorMessage = errorMessage; + String getErrorMessage() { + return errorMessage; + } } - - } - } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java index bd430bf2eb..a3325fae78 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.namingconvention; +import static java.util.Objects.nonNull; + +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -27,57 +29,40 @@ import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.Map; - -import static java.util.Objects.nonNull; - - public class ContrailServiceInstanceNamingConventionValidator implements ResourceValidator { - private static final String AVAILABILITY_ZONE = "availability_zone"; - private static final ErrorMessageCode ERROR_CODE_NSI1 = new ErrorMessageCode("NSI1"); - private static final ErrorMessageCode ERROR_CODE_NSI2 = new ErrorMessageCode("NSI2"); - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - validateAvailabilityZoneName(fileName, resourceEntry, globalContext); - } + private static final String AVAILABILITY_ZONE = "availability_zone"; + private static final ErrorMessageCode ERROR_CODE_NSI1 = new ErrorMessageCode("NSI1"); + private static final ErrorMessageCode ERROR_CODE_NSI2 = new ErrorMessageCode("NSI2"); - private void validateAvailabilityZoneName(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - String[] regexList = new String[]{"availability_zone_(\\d+)"}; - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateAvailabilityZoneName(fileName, resourceEntry, globalContext); } - Object availabilityZoneMap = - resourceEntry.getValue().getProperties().containsKey(AVAILABILITY_ZONE) ? resourceEntry - .getValue().getProperties().get(AVAILABILITY_ZONE) : null; - - if (nonNull(availabilityZoneMap)) { - if (availabilityZoneMap instanceof Map) { - String availabilityZoneName = ValidationUtil - .getWantedNameFromPropertyValueGetParam (availabilityZoneMap); - - if (availabilityZoneName != null && !ValidationUtil - .evalPattern(availabilityZoneName, regexList)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters(ERROR_CODE_NSI1, - Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), - "Availability Zone", - availabilityZoneName, resourceEntry.getKey())); - } - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_NSI2, Messages.MISSING_GET_PARAM.getErrorMessage(), - AVAILABILITY_ZONE, resourceEntry.getKey())); - } + private void validateAvailabilityZoneName(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext) { + String[] regexList = new String[]{"availability_zone_(\\d+)"}; + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return; + } + Object availabilityZoneMap = + resourceEntry.getValue().getProperties().containsKey(AVAILABILITY_ZONE) ? resourceEntry.getValue().getProperties().get(AVAILABILITY_ZONE) + : null; + if (nonNull(availabilityZoneMap)) { + if (availabilityZoneMap instanceof Map) { + String availabilityZoneName = ValidationUtil.getWantedNameFromPropertyValueGetParam(availabilityZoneMap); + if (availabilityZoneName != null && !ValidationUtil.evalPattern(availabilityZoneName, regexList)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NSI1, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), "Availability Zone", availabilityZoneName, + resourceEntry.getKey())); + } + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NSI2, Messages.MISSING_GET_PARAM.getErrorMessage(), AVAILABILITY_ZONE, + resourceEntry.getKey())); + } + } } - } - } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java index 547e38f62b..7895c12ae2 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.namingconvention; import static java.util.Objects.nonNull; @@ -24,7 +23,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -39,168 +37,124 @@ import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.util.ValidationUtil; - public class ContrailServiceTemplateNamingConventionValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_NST1 = new ErrorMessageCode("NST1"); - private static final ErrorMessageCode ERROR_CODE_NST2 = new ErrorMessageCode("NST2"); - private static final ErrorMessageCode ERROR_CODE_NST3 = new ErrorMessageCode("NST3"); - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext); - } + private static final ErrorMessageCode ERROR_CODE_NST1 = new ErrorMessageCode("NST1"); + private static final ErrorMessageCode ERROR_CODE_NST2 = new ErrorMessageCode("NST2"); + private static final ErrorMessageCode ERROR_CODE_NST3 = new ErrorMessageCode("NST3"); - private void validateServiceTemplateImageAndFlavor(String fileName, - Map.Entry entry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(entry.getValue().getProperties())) { - return; + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext); } - Pair imagePair = new ImmutablePair<>("image_name", ".*_image_name"); - Pair flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); - List> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); - - Map propertiesMap = entry.getValue().getProperties(); - - boolean errorExistValidatingImageOrFlavor = false; - for (Pair imageOrFlavor : imageFlavorPairs) { - boolean errorExistWhenValidatingImageOrFlavorNames = - isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry, - propertiesMap, globalContext); - errorExistValidatingImageOrFlavor = - errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames; - } - - if (!errorExistValidatingImageOrFlavor) { - validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext, - propertiesMap); + private void validateServiceTemplateImageAndFlavor(String fileName, Map.Entry entry, GlobalValidationContext globalContext) { + if (MapUtils.isEmpty(entry.getValue().getProperties())) { + return; + } + Pair imagePair = new ImmutablePair<>("image_name", ".*_image_name"); + Pair flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); + List> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); + Map propertiesMap = entry.getValue().getProperties(); + boolean errorExistValidatingImageOrFlavor = false; + for (Pair imageOrFlavor : imageFlavorPairs) { + boolean errorExistWhenValidatingImageOrFlavorNames = isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry, + propertiesMap, globalContext); + errorExistValidatingImageOrFlavor = errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames; + } + if (!errorExistValidatingImageOrFlavor) { + validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext, propertiesMap); + } } - } - - private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName, - Map.Entry entry, - GlobalValidationContext globalContext, - Map propertiesMap) { - Pair vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name"); - Pair vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name"); - validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair), - fileName, entry, propertiesMap, globalContext); - } - private void validatePropertiesValuesVmtypesAreIdentical(List propertiesToMatch, - String fileName, - Map.Entry resourceEntry, - Map propertiesMap, - GlobalValidationContext globalContext) { - if (CollectionUtils.isEmpty(propertiesToMatch)) { - return; + private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName, Map.Entry entry, + GlobalValidationContext globalContext, + Map propertiesMap) { + Pair vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name"); + Pair vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name"); + validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair), fileName, entry, propertiesMap, globalContext); } - String previousPropertyValueValue = null; - for (Pair propertyToMatch : propertiesToMatch) { - Optional propertyVmType = - extractVmTypeFromProperty(fileName, resourceEntry, propertiesMap, globalContext, - propertyToMatch); - if (propertyVmType.isPresent()) { - String currentPropVmType = propertyVmType.get(); - previousPropertyValueValue = - handleFirstIteration(previousPropertyValueValue, currentPropVmType); - if (addWarningIfCurrentVmTypeIsDifferentFromPrevious(fileName, resourceEntry, globalContext, - previousPropertyValueValue, currentPropVmType)) { - return; + private void validatePropertiesValuesVmtypesAreIdentical(List propertiesToMatch, String fileName, Map.Entry resourceEntry, + Map propertiesMap, GlobalValidationContext globalContext) { + if (CollectionUtils.isEmpty(propertiesToMatch)) { + return; + } + String previousPropertyValueValue = null; + for (Pair propertyToMatch : propertiesToMatch) { + Optional propertyVmType = extractVmTypeFromProperty(fileName, resourceEntry, propertiesMap, globalContext, propertyToMatch); + if (propertyVmType.isPresent()) { + String currentPropVmType = propertyVmType.get(); + previousPropertyValueValue = handleFirstIteration(previousPropertyValueValue, currentPropVmType); + if (addWarningIfCurrentVmTypeIsDifferentFromPrevious(fileName, resourceEntry, globalContext, previousPropertyValueValue, + currentPropVmType)) { + return; + } + } } - } } - } - private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - String previousPropertyValueValue, - String currentPropVmType) { - if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NST1, Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION - .getErrorMessage(), - resourceEntry.getKey())); - return true; + private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext, String previousPropertyValueValue, + String currentPropVmType) { + if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NST1, Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION.getErrorMessage(), + resourceEntry.getKey())); + return true; + } + return false; } - return false; - } - - private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, - Pair propertyNameAndRegex, - Map.Entry resourceEntry, - Map propertiesMap, - GlobalValidationContext globalContext) { - String propertyName = propertyNameAndRegex.getKey(); - Object nameValue = propertiesMap.get(propertyName); - String[] regexList = new String[]{propertyNameAndRegex.getValue()}; - if (nonNull(nameValue)) { - if (nameValue instanceof Map) { - globalContext.setMessageCode(ERROR_CODE_NST3); - if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, - propertyName, - nameValue, regexList)) { - return true; + private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, Pair propertyNameAndRegex, + Map.Entry resourceEntry, Map propertiesMap, + GlobalValidationContext globalContext) { + String propertyName = propertyNameAndRegex.getKey(); + Object nameValue = propertiesMap.get(propertyName); + String[] regexList = new String[]{propertyNameAndRegex.getValue()}; + if (nonNull(nameValue)) { + if (nameValue instanceof Map) { + globalContext.setMessageCode(ERROR_CODE_NST3); + if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, propertyName, nameValue, regexList)) { + return true; + } + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, resourceEntry.getKey())); + return true; + } + return false; } - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(), - propertyName, - resourceEntry.getKey())); - return true; - } - - return false; + return false; } - return false; - } - - private Optional extractVmTypeFromProperty(String fileName, - Map.Entry resourceEntry, - Map propertiesMap, - GlobalValidationContext globalContext, - Pair propertyKeyRegex) { - String propertyName = (String) propertyKeyRegex.getKey(); - Object propertyVal = propertiesMap.get(propertyName); - if (nonNull(propertyVal)) { - if (propertyVal instanceof Map) { - String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam - (propertyVal); - if (nonNull(propertyValFromGetParam)) { - Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue()); - return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]); + private Optional extractVmTypeFromProperty(String fileName, Map.Entry resourceEntry, Map propertiesMap, + GlobalValidationContext globalContext, Pair propertyKeyRegex) { + String propertyName = (String) propertyKeyRegex.getKey(); + Object propertyVal = propertiesMap.get(propertyName); + if (nonNull(propertyVal)) { + if (propertyVal instanceof Map) { + String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam(propertyVal); + if (nonNull(propertyValFromGetParam)) { + Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue()); + return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]); + } + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, resourceEntry.getKey())); + return Optional.empty(); + } } - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(), - propertyName, - resourceEntry.getKey())); return Optional.empty(); - } } - return Optional.empty(); - } - private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) { - String previousPropertyValue; - if (Objects.isNull(previousPropertyValueValue)) { - previousPropertyValue = currentPropVmType; - return previousPropertyValue; + private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) { + String previousPropertyValue; + if (Objects.isNull(previousPropertyValueValue)) { + previousPropertyValue = currentPropVmType; + return previousPropertyValue; + } + return previousPropertyValueValue; } - - return previousPropertyValueValue; - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java index 760c73a52b..4a886fb1eb 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.namingconvention; +import static java.util.Objects.nonNull; + +import java.util.List; +import java.util.Map; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -30,75 +33,51 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.NamingConventionValidationContext; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import static java.util.Objects.nonNull; - public class NeutronPortNamingConventionValidator implements ResourceValidator { + private static final ErrorMessageCode ERROR_CODE_NNP1 = new ErrorMessageCode("NNP1"); private static final ErrorMessageCode ERROR_CODE_NNP2 = new ErrorMessageCode("NNP2"); private static final ErrorMessageCode ERROR_CODE_NNP3 = new ErrorMessageCode("NNP3"); @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { NamingConventionValidationContext namingConventionValidationContext = (NamingConventionValidationContext) validationContext; validatePortNetworkNamingConvention(fileName, namingConventionValidationContext.getHeatOrchestrationTemplate(), globalContext); validateFixedIpsNamingConvention(fileName, namingConventionValidationContext.getHeatOrchestrationTemplate(), globalContext); } - private void validatePortNetworkNamingConvention(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void validatePortNetworkNamingConvention(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { return; } String[] regexList = {".*_net_id", ".*_net_name", ".*_net_fqdn"}; - - heatOrchestrationTemplate - .getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType().equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) - .forEach(entry -> entry.getValue() - .getProperties() - .entrySet() - .stream() - .filter(propertyEntry -> ("network").equalsIgnoreCase(propertyEntry.getKey()) || ("network_id").equals(propertyEntry.getKey())) - .forEach(propertyEntry -> validateParamNamingConvention(fileName, entry.getKey(), - propertyEntry.getValue(), regexList, - Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES, globalContext))); + heatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> entry.getValue().getType().equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())).forEach( + entry -> entry.getValue().getProperties().entrySet().stream() + .filter(propertyEntry -> ("network").equalsIgnoreCase(propertyEntry.getKey()) || ("network_id").equals(propertyEntry.getKey())) + .forEach(propertyEntry -> validateParamNamingConvention(fileName, entry.getKey(), propertyEntry.getValue(), regexList, + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES, globalContext))); } - private void validateFixedIpsNamingConvention(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, + private void validateFixedIpsNamingConvention(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { return; } - - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) != null) - .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) - .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE)) - .forEach(entry -> checkNeutronPortFixedIpsName(fileName, entry, globalContext)); + heatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) != null) + .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()).equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE)) + .forEach(entry -> checkNeutronPortFixedIpsName(fileName, entry, globalContext)); } - private void checkNeutronPortFixedIpsName(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - String[] regexList = {"[^_]+_[^_]+_ips", "[^_]+_[^_]+_v6_ips", "[^_]+_[^_]+_ip_(\\d+)", - "[^_]+_[^_]+_v6_ip_(\\d+)", "[^_]+_[^_]+_[^_]+_ips", "[^_]+_[^_]+_[^_]+_v6_ips", - "[^_]+_[^_]+_[^_]+_ip_(\\d+)", "[^_]+_[^_]+_[^_]+_v6_ip_(\\d+)"}; - + private void checkNeutronPortFixedIpsName(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext) { + String[] regexList = {"[^_]+_[^_]+_ips", "[^_]+_[^_]+_v6_ips", "[^_]+_[^_]+_ip_(\\d+)", "[^_]+_[^_]+_v6_ip_(\\d+)", "[^_]+_[^_]+_[^_]+_ips", + "[^_]+_[^_]+_[^_]+_v6_ips", "[^_]+_[^_]+_[^_]+_ip_(\\d+)", "[^_]+_[^_]+_[^_]+_v6_ip_(\\d+)"}; if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { return; } - Map propertiesMap = resourceEntry.getValue().getProperties(); Object fixedIps = propertiesMap.get("fixed_ips"); if (nonNull(fixedIps) && fixedIps instanceof List) { @@ -117,27 +96,27 @@ public class NeutronPortNamingConventionValidator implements ResourceValidator { String fixedIpsName = ValidationUtil.getWantedNameFromPropertyValueGetParam(fixedIpsEntry.getValue()); if (nonNull(fixedIpsName) && !ValidationUtil.evalPattern(fixedIpsName, regexList)) { globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_NNP1, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - "Port", "Fixed_IPS", fixedIpsName, resourceEntry.getKey())); + .getErrorWithParameters(ERROR_CODE_NNP1, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), "Port", + "Fixed_IPS", fixedIpsName, resourceEntry.getKey())); } } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder. - getErrorWithParameters(ERROR_CODE_NNP2, Messages.MISSING_GET_PARAM.getErrorMessage(), "fixed_ips", resourceEntry.getKey())); + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNP2, Messages.MISSING_GET_PARAM.getErrorMessage(), "fixed_ips", resourceEntry.getKey())); } } } - private void validateParamNamingConvention(String fileName, String resourceId, Object propertyValue, String[] regexList, - Messages message, GlobalValidationContext globalContext) { + private void validateParamNamingConvention(String fileName, String resourceId, Object propertyValue, String[] regexList, Messages message, + GlobalValidationContext globalContext) { if (propertyValue instanceof Map) { Object paramName = ((Map) propertyValue).get("get_param"); if (paramName instanceof String && !ValidationUtil.evalPattern(paramName, regexList)) { globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_NNP3, message.getErrorMessage(), "Port", "Network", (String) paramName, resourceId)); + .getErrorWithParameters(ERROR_CODE_NNP3, message.getErrorMessage(), "Port", "Network", (String) paramName, resourceId)); } } else { globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_NNP2, Messages.MISSING_GET_PARAM.getErrorMessage(), "network or network_id", resourceId)); + .getErrorWithParameters(ERROR_CODE_NNP2, Messages.MISSING_GET_PARAM.getErrorMessage(), "network or network_id", resourceId)); } } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java index e9f6257a88..e2ce555caa 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation.impl.validators.namingconvention; import static java.util.Objects.nonNull; @@ -28,7 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -50,508 +48,371 @@ import org.openecomp.sdc.validation.type.NamingConventionValidationContext; import org.openecomp.sdc.validation.util.ValidationUtil; public class NovaServerNamingConventionGuideLineValidator implements ResourceValidator { - private static final String AVAILABILITY_ZONE = "availability_zone"; - private static final String SERVER = "Server"; - private static final ErrorMessageCode ERROR_CODE_NNS1 = new ErrorMessageCode("NNS1"); - private static final ErrorMessageCode ERROR_CODE_NNS2 = new ErrorMessageCode("NNS2"); - private static final ErrorMessageCode ERROR_CODE_NNS3 = new ErrorMessageCode("NNS3"); - private static final ErrorMessageCode ERROR_CODE_NNS4 = new ErrorMessageCode("NNS4"); - private static final ErrorMessageCode ERROR_CODE_NNS5 = new ErrorMessageCode("NNS5"); - private static final ErrorMessageCode ERROR_CODE_NNS6 = new ErrorMessageCode("NNS6"); - private static final ErrorMessageCode ERROR_CODE_NNS7 = new ErrorMessageCode("NNS7"); - private static final ErrorMessageCode ERROR_CODE_NNS8 = new ErrorMessageCode("NNS8"); - private static final ErrorMessageCode ERROR_CODE_NNS9 = new ErrorMessageCode("NNS9"); - private static final ErrorMessageCode ERROR_CODE_NNS10 = new ErrorMessageCode("NNS10"); - private static final ErrorMessageCode ERROR_CODE_NNS11 = new ErrorMessageCode("NNS11"); - private static final ErrorMessageCode ERROR_CODE_NNS12 = new ErrorMessageCode("NNS12"); - private static final ErrorMessageCode ERROR_CODE_NNS13 = new ErrorMessageCode("NNS13"); - private static final ErrorMessageCode ERROR_CODE_NNS14 = new ErrorMessageCode("NNS14"); - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - NamingConventionValidationContext namingConventionValidationContext = - (NamingConventionValidationContext)validationContext; - validateHeatNovaResource(fileName, namingConventionValidationContext.getEnvFileName(), - namingConventionValidationContext.getHeatOrchestrationTemplate(), - globalContext); - } - - private void validateHeatNovaResource(String fileName, String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - //if no resources exist return - if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { - return; + private static final String AVAILABILITY_ZONE = "availability_zone"; + private static final String SERVER = "Server"; + private static final ErrorMessageCode ERROR_CODE_NNS1 = new ErrorMessageCode("NNS1"); + private static final ErrorMessageCode ERROR_CODE_NNS2 = new ErrorMessageCode("NNS2"); + private static final ErrorMessageCode ERROR_CODE_NNS3 = new ErrorMessageCode("NNS3"); + private static final ErrorMessageCode ERROR_CODE_NNS4 = new ErrorMessageCode("NNS4"); + private static final ErrorMessageCode ERROR_CODE_NNS5 = new ErrorMessageCode("NNS5"); + private static final ErrorMessageCode ERROR_CODE_NNS6 = new ErrorMessageCode("NNS6"); + private static final ErrorMessageCode ERROR_CODE_NNS7 = new ErrorMessageCode("NNS7"); + private static final ErrorMessageCode ERROR_CODE_NNS8 = new ErrorMessageCode("NNS8"); + private static final ErrorMessageCode ERROR_CODE_NNS9 = new ErrorMessageCode("NNS9"); + private static final ErrorMessageCode ERROR_CODE_NNS10 = new ErrorMessageCode("NNS10"); + private static final ErrorMessageCode ERROR_CODE_NNS11 = new ErrorMessageCode("NNS11"); + private static final ErrorMessageCode ERROR_CODE_NNS12 = new ErrorMessageCode("NNS12"); + private static final ErrorMessageCode ERROR_CODE_NNS13 = new ErrorMessageCode("NNS13"); + private static final ErrorMessageCode ERROR_CODE_NNS14 = new ErrorMessageCode("NNS14"); + + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + NamingConventionValidationContext namingConventionValidationContext = (NamingConventionValidationContext) validationContext; + validateHeatNovaResource(fileName, namingConventionValidationContext.getEnvFileName(), + namingConventionValidationContext.getHeatOrchestrationTemplate(), globalContext); } - heatOrchestrationTemplate - .getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType() - .equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource())) - .forEach( entry -> validateNovaServerResourceType(entry.getKey(), fileName, envFileName, - entry, new HashMap(), heatOrchestrationTemplate, globalContext)); - } - - private void validateNovaServerResourceType(String resourceId, String fileName, - String envFileName, - Map.Entry resourceEntry, - Map uniqueResourcePortNetworkRole, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - validateNovaServerResourceMetaData(fileName, resourceId, - heatOrchestrationTemplate.getResources().get(resourceId), globalContext); - validateNovaServerResourceNetworkUniqueRole(fileName, resourceId, uniqueResourcePortNetworkRole, - heatOrchestrationTemplate, globalContext); - validateAvailabilityZoneName(fileName, resourceEntry, globalContext); - validateNovaServerNameImageAndFlavor(fileName, envFileName, resourceEntry, globalContext); - } - - @SuppressWarnings("unchecked") - private void validateNovaServerResourceMetaData(String fileName, String resourceId, - Resource resource, - GlobalValidationContext globalValidationContext) { - Map novaServerProp = resource.getProperties(); - Object novaServerPropMetadata; - if (MapUtils.isNotEmpty(novaServerProp)) { - novaServerPropMetadata = novaServerProp.get("metadata"); - if (novaServerPropMetadata == null) { - globalValidationContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS1, Messages.MISSING_NOVA_SERVER_METADATA.getErrorMessage(), - resourceId)); - } else if (novaServerPropMetadata instanceof Map) { - TreeMap propertyMap = new TreeMap((Comparator) String::compareToIgnoreCase); - propertyMap.putAll((Map) novaServerPropMetadata); - if (!propertyMap.containsKey("vf_module_id")) { - globalValidationContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS2, Messages.MISSING_NOVA_SERVER_VF_MODULE_ID.getErrorMessage(), - resourceId)); - } - if (!propertyMap.containsKey("vnf_id")) { - globalValidationContext.addMessage( - fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS3, Messages.MISSING_NOVA_SERVER_VNF_ID.getErrorMessage(), - resourceId)); + private void validateHeatNovaResource(String fileName, String envFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + //if no resources exist return + if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + return; } - } + heatOrchestrationTemplate.getResources().entrySet().stream() + .filter(entry -> entry.getValue().getType().equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource())).forEach( + entry -> validateNovaServerResourceType(entry.getKey(), fileName, envFileName, entry, new HashMap(), + heatOrchestrationTemplate, globalContext)); } - } - private void validateNovaServerResourceNetworkUniqueRole(String fileName, String resourceId, - Map uniqueResourcePortNetworkRole, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalValidationContext) { - if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources().get(resourceId).getProperties())) { - return; - } - Object propertyNetworkValue = - heatOrchestrationTemplate.getResources().get(resourceId).getProperties().get("networks"); - if (propertyNetworkValue != null && propertyNetworkValue instanceof List) { - List portResourceIdList = - getNovaNetworkPortResourceList(fileName, (List) propertyNetworkValue, - globalValidationContext); - for (String portResourceId : portResourceIdList) { - Resource portResource = heatOrchestrationTemplate.getResources().get(portResourceId); + private void validateNovaServerResourceType(String resourceId, String fileName, String envFileName, Map.Entry resourceEntry, + Map uniqueResourcePortNetworkRole, + HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { + validateNovaServerResourceMetaData(fileName, resourceId, heatOrchestrationTemplate.getResources().get(resourceId), globalContext); + validateNovaServerResourceNetworkUniqueRole(fileName, resourceId, uniqueResourcePortNetworkRole, heatOrchestrationTemplate, globalContext); + validateAvailabilityZoneName(fileName, resourceEntry, globalContext); + validateNovaServerNameImageAndFlavor(fileName, envFileName, resourceEntry, globalContext); + } - if (portResource != null && portResource.getType() - .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { - validateUniqueResourcePortNetworkRole(fileName, resourceId, - uniqueResourcePortNetworkRole, globalValidationContext, - portResourceId, portResource); + @SuppressWarnings("unchecked") + private void validateNovaServerResourceMetaData(String fileName, String resourceId, Resource resource, + GlobalValidationContext globalValidationContext) { + Map novaServerProp = resource.getProperties(); + Object novaServerPropMetadata; + if (MapUtils.isNotEmpty(novaServerProp)) { + novaServerPropMetadata = novaServerProp.get("metadata"); + if (novaServerPropMetadata == null) { + globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS1, Messages.MISSING_NOVA_SERVER_METADATA.getErrorMessage(), resourceId)); + } else if (novaServerPropMetadata instanceof Map) { + TreeMap propertyMap = new TreeMap((Comparator) String::compareToIgnoreCase); + propertyMap.putAll((Map) novaServerPropMetadata); + if (!propertyMap.containsKey("vf_module_id")) { + globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS2, Messages.MISSING_NOVA_SERVER_VF_MODULE_ID.getErrorMessage(), resourceId)); + } + if (!propertyMap.containsKey("vnf_id")) { + globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS3, Messages.MISSING_NOVA_SERVER_VNF_ID.getErrorMessage(), resourceId)); + } + } } - } } - } - private void validateUniqueResourcePortNetworkRole(String fileName, String resourceId, - Map uniqueResourcePortNetworkRole, - GlobalValidationContext globalValidationContext, - String portResourceId, Resource portResource) { - String role = null; - Object network; - Map portNetwork = - getPortNetwork(fileName, resourceId, portResource, globalValidationContext); - if (Objects.nonNull(portNetwork)) { - network = portNetwork.get("get_param"); - if (Objects.nonNull(network)) { - if (network instanceof String ){ - role = getNetworkRole((String)network); - }else if (network instanceof List){ - role = getNetworkRole((String)((List) network).get(0)); + private void validateNovaServerResourceNetworkUniqueRole(String fileName, String resourceId, Map uniqueResourcePortNetworkRole, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalValidationContext) { + if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources().get(resourceId).getProperties())) { + return; } - if (role != null && uniqueResourcePortNetworkRole.containsKey(role)) { - globalValidationContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS12, Messages.RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE - .getErrorMessage(), role, resourceId)); - } else { - uniqueResourcePortNetworkRole.put(role, resourceId); + Object propertyNetworkValue = heatOrchestrationTemplate.getResources().get(resourceId).getProperties().get("networks"); + if (propertyNetworkValue != null && propertyNetworkValue instanceof List) { + List portResourceIdList = getNovaNetworkPortResourceList(fileName, (List) propertyNetworkValue, globalValidationContext); + for (String portResourceId : portResourceIdList) { + Resource portResource = heatOrchestrationTemplate.getResources().get(portResourceId); + if (portResource != null && portResource.getType().equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { + validateUniqueResourcePortNetworkRole(fileName, resourceId, uniqueResourcePortNetworkRole, globalValidationContext, + portResourceId, portResource); + } + } } - } } - } - private List getNovaNetworkPortResourceList(String filename, List propertyNetworkValue, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_NNS14); - List portResourceIdList = new ArrayList<>(); - for (Object propValue : propertyNetworkValue) { - Object portPropValue = ((Map) propValue).get("port"); - Collection portResourceIds = HeatStructureUtil - .getReferencedValuesByFunctionName(filename, "get_resource", portPropValue, - globalContext); - if (portResourceIds != null) { - portResourceIdList.addAll(portResourceIds); - } - } - - return portResourceIdList; - } - - private String getNetworkRole(String network) { - if (network == null) { - return null; - } - if (network.contains("_net_id")) { - return network.substring(0, network.indexOf("_net_id")); - } else if (network.contains("_net_name")) { - return network.substring(0, network.indexOf("_net_name")); - } else if (network.contains("_net_fqdn")) { - return network.substring(0, network.indexOf("_net_fqdn")); - } - return null; - } - - private Map getPortNetwork(String fileName, String resourceId, Resource portResource, - GlobalValidationContext globalValidationContext) { - Object portNetwork = portResource.getProperties().get("network_id"); - if (portNetwork == null) { - portNetwork = portResource.getProperties().get("network"); - } - if (!(portNetwork instanceof Map)) { - globalValidationContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS4, Messages.MISSING_GET_PARAM.getErrorMessage(), - "network or network_id", resourceId)); - return null; + private void validateUniqueResourcePortNetworkRole(String fileName, String resourceId, Map uniqueResourcePortNetworkRole, + GlobalValidationContext globalValidationContext, String portResourceId, + Resource portResource) { + String role = null; + Object network; + Map portNetwork = getPortNetwork(fileName, resourceId, portResource, globalValidationContext); + if (Objects.nonNull(portNetwork)) { + network = portNetwork.get("get_param"); + if (Objects.nonNull(network)) { + if (network instanceof String) { + role = getNetworkRole((String) network); + } else if (network instanceof List) { + role = getNetworkRole((String) ((List) network).get(0)); + } + if (role != null && uniqueResourcePortNetworkRole.containsKey(role)) { + globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS12, + Messages.RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE.getErrorMessage(), role, resourceId)); + } else { + uniqueResourcePortNetworkRole.put(role, resourceId); + } + } + } } - return (Map) portNetwork; - } - private void validateAvailabilityZoneName(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - String[] regexList = new String[]{"availability_zone_(\\d+)"}; - - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; + private List getNovaNetworkPortResourceList(String filename, List propertyNetworkValue, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_NNS14); + List portResourceIdList = new ArrayList<>(); + for (Object propValue : propertyNetworkValue) { + Object portPropValue = ((Map) propValue).get("port"); + Collection portResourceIds = HeatStructureUtil + .getReferencedValuesByFunctionName(filename, "get_resource", portPropValue, globalContext); + if (portResourceIds != null) { + portResourceIdList.addAll(portResourceIds); + } + } + return portResourceIdList; } - Object availabilityZoneMap = resourceEntry.getValue().getProperties() - .get(AVAILABILITY_ZONE); - - if (nonNull(availabilityZoneMap)) { - if (availabilityZoneMap instanceof Map) { - String availabilityZoneName = ValidationUtil.getWantedNameFromPropertyValueGetParam - (availabilityZoneMap); - - if (availabilityZoneName != null && !ValidationUtil - .evalPattern(availabilityZoneName, regexList)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS5, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), - "Availability Zone", availabilityZoneName, resourceEntry.getKey())); - } - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS6, Messages.MISSING_GET_PARAM.getErrorMessage(), - AVAILABILITY_ZONE, resourceEntry.getKey())); - } + private String getNetworkRole(String network) { + if (network == null) { + return null; + } + if (network.contains("_net_id")) { + return network.substring(0, network.indexOf("_net_id")); + } else if (network.contains("_net_name")) { + return network.substring(0, network.indexOf("_net_name")); + } else if (network.contains("_net_fqdn")) { + return network.substring(0, network.indexOf("_net_fqdn")); + } + return null; } - } - - private void validateNovaServerNameImageAndFlavor(String fileName, String envFileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - String novaName = - validateNovaServerNamingConvention(fileName, envFileName, resourceEntry, globalContext); - Map legalNovaNamingConventionMap = - validateImageAndFlavorFromNovaServer(fileName, resourceEntry, globalContext); - if (Objects.nonNull(novaName)) { - legalNovaNamingConventionMap.put("name", novaName); + private Map getPortNetwork(String fileName, String resourceId, Resource portResource, GlobalValidationContext globalValidationContext) { + Object portNetwork = portResource.getProperties().get("network_id"); + if (portNetwork == null) { + portNetwork = portResource.getProperties().get("network"); + } + if (!(portNetwork instanceof Map)) { + globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS4, Messages.MISSING_GET_PARAM.getErrorMessage(), "network or network_id", resourceId)); + return null; + } + return (Map) portNetwork; } - if (legalNovaNamingConventionMap.keySet().size() > 1) { - validateNovaServerNameImageAndFlavorSync(fileName, resourceEntry, - legalNovaNamingConventionMap, globalContext); + private void validateAvailabilityZoneName(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext) { + String[] regexList = new String[]{"availability_zone_(\\d+)"}; + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return; + } + Object availabilityZoneMap = resourceEntry.getValue().getProperties().get(AVAILABILITY_ZONE); + if (nonNull(availabilityZoneMap)) { + if (availabilityZoneMap instanceof Map) { + String availabilityZoneName = ValidationUtil.getWantedNameFromPropertyValueGetParam(availabilityZoneMap); + if (availabilityZoneName != null && !ValidationUtil.evalPattern(availabilityZoneName, regexList)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS5, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), "Availability Zone", availabilityZoneName, + resourceEntry.getKey())); + } + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS6, Messages.MISSING_GET_PARAM.getErrorMessage(), AVAILABILITY_ZONE, + resourceEntry.getKey())); + } + } } - } - private String validateNovaServerNamingConvention(String fileName, String envFileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return null; + private void validateNovaServerNameImageAndFlavor(String fileName, String envFileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + String novaName = validateNovaServerNamingConvention(fileName, envFileName, resourceEntry, globalContext); + Map legalNovaNamingConventionMap = validateImageAndFlavorFromNovaServer(fileName, resourceEntry, globalContext); + if (Objects.nonNull(novaName)) { + legalNovaNamingConventionMap.put("name", novaName); + } + if (legalNovaNamingConventionMap.keySet().size() > 1) { + validateNovaServerNameImageAndFlavorSync(fileName, resourceEntry, legalNovaNamingConventionMap, globalContext); + } } - return checkIfNovaNameByGuidelines(fileName, envFileName, resourceEntry, globalContext); - } - private Map validateImageAndFlavorFromNovaServer(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - Map imageAndFlavorLegalNames = new HashMap<>(); - - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return imageAndFlavorLegalNames; + private String validateNovaServerNamingConvention(String fileName, String envFileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return null; + } + return checkIfNovaNameByGuidelines(fileName, envFileName, resourceEntry, globalContext); } - Pair imagePair = new ImmutablePair<>("image", ".*_image_name"); - Pair flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); - List> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); - Map propertiesMap = resourceEntry.getValue().getProperties(); - - for (Pair imageOrFlavor : imageFlavorPairs) { - boolean isErrorInImageOrFlavor = - isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, resourceEntry, - propertiesMap, globalContext); - if (!isErrorInImageOrFlavor) { - Object nameValue = propertiesMap.get(imageOrFlavor.getKey()); - String imageOrFlavorName = ValidationUtil.getWantedNameFromPropertyValueGetParam - (nameValue); - imageAndFlavorLegalNames.put(imageOrFlavor.getKey(), imageOrFlavorName); - } + private Map validateImageAndFlavorFromNovaServer(String fileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + Map imageAndFlavorLegalNames = new HashMap<>(); + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return imageAndFlavorLegalNames; + } + Pair imagePair = new ImmutablePair<>("image", ".*_image_name"); + Pair flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); + List> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); + Map propertiesMap = resourceEntry.getValue().getProperties(); + for (Pair imageOrFlavor : imageFlavorPairs) { + boolean isErrorInImageOrFlavor = isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, resourceEntry, propertiesMap, + globalContext); + if (!isErrorInImageOrFlavor) { + Object nameValue = propertiesMap.get(imageOrFlavor.getKey()); + String imageOrFlavorName = ValidationUtil.getWantedNameFromPropertyValueGetParam(nameValue); + imageAndFlavorLegalNames.put(imageOrFlavor.getKey(), imageOrFlavorName); + } + } + return imageAndFlavorLegalNames; } - return imageAndFlavorLegalNames; - } - private String checkIfNovaNameByGuidelines(String fileName, String envFileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return null; - } - Object novaNameGetParam = getNovaServerName(resourceEntry); - String novaName = null; - if (nonNull(novaNameGetParam)) { - novaName = - checkNovaNameGetParamValueMap(fileName, novaNameGetParam, resourceEntry, globalContext); - checkIfNovaNameParameterInEnvIsStringOrList(fileName, envFileName, novaName, resourceEntry, - globalContext); - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS7, Messages.MISSING_GET_PARAM.getErrorMessage(), - "nova server name", resourceEntry.getKey())); + private String checkIfNovaNameByGuidelines(String fileName, String envFileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return null; + } + Object novaNameGetParam = getNovaServerName(resourceEntry); + String novaName = null; + if (nonNull(novaNameGetParam)) { + novaName = checkNovaNameGetParamValueMap(fileName, novaNameGetParam, resourceEntry, globalContext); + checkIfNovaNameParameterInEnvIsStringOrList(fileName, envFileName, novaName, resourceEntry, globalContext); + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS7, Messages.MISSING_GET_PARAM.getErrorMessage(), "nova server name", resourceEntry.getKey())); + } + return novaName; } - return novaName; - } - - private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, - Pair propertyNameAndRegex, - Map.Entry resourceEntry, - Map propertiesMap, - GlobalValidationContext globalContext) { - String propertyName = propertyNameAndRegex.getKey(); - Object nameValue = propertiesMap.get(propertyName); - String[] regexList = new String[]{propertyNameAndRegex.getValue()}; - - - if (nonNull(nameValue)) { - if (nameValue instanceof Map) { - globalContext.setMessageCode(ERROR_CODE_NNS13); - if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, - propertyName, - nameValue, regexList)) { - return true; + private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, Pair propertyNameAndRegex, + Map.Entry resourceEntry, Map propertiesMap, + GlobalValidationContext globalContext) { + String propertyName = propertyNameAndRegex.getKey(); + Object nameValue = propertiesMap.get(propertyName); + String[] regexList = new String[]{propertyNameAndRegex.getValue()}; + if (nonNull(nameValue)) { + if (nameValue instanceof Map) { + globalContext.setMessageCode(ERROR_CODE_NNS13); + if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, propertyName, nameValue, regexList)) { + return true; + } + } else { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS8, Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, resourceEntry.getKey())); + return true; + } + return false; } - } else { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - ERROR_CODE_NNS8, Messages.MISSING_GET_PARAM.getErrorMessage(), - propertyName, resourceEntry.getKey())); - return true; - } - - return false; + return false; } - return false; - } - - private Object getNovaServerName(Map.Entry resourceEntry) { - Object novaServerName = resourceEntry.getValue().getProperties().get("name"); - Map novaNameMap; - if (nonNull(novaServerName) && novaServerName instanceof Map) { - novaNameMap = (Map) novaServerName; - return novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()); - } - return null; - } - - @SuppressWarnings("unchecked") - private String checkNovaNameGetParamValueMap(String fileName, Object getParamValue, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (getParamValue instanceof List) { - List getParamNameList = (List) getParamValue; - String[] regexName = new String[]{".*_names"}; - return isNovaNameAsListLegal(fileName, regexName, getParamNameList, resourceEntry, - globalContext); - } else if (getParamValue instanceof String) { - String[] regexName = new String[]{".*_name_(\\d+)"}; - return isNovaNameAsStringLegal(fileName, (String) getParamValue, regexName, resourceEntry, - globalContext); + private Object getNovaServerName(Map.Entry resourceEntry) { + Object novaServerName = resourceEntry.getValue().getProperties().get("name"); + Map novaNameMap; + if (nonNull(novaServerName) && novaServerName instanceof Map) { + novaNameMap = (Map) novaServerName; + return novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()); + } + return null; } - return null; - } - - private void checkIfNovaNameParameterInEnvIsStringOrList(String fileName, - String envFileName, - String novaServerName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (nonNull(envFileName)) { - Environment environment = ValidationUtil.validateEnvContent(envFileName, globalContext); - - if (environment != null && MapUtils.isNotEmpty(environment.getParameters())) { - Object novaServerNameEnvValue = environment.getParameters() - .get(novaServerName); - if (Objects.nonNull(novaServerNameEnvValue) && !DefinedHeatParameterTypes - .isNovaServerEnvValueIsFromRightType(novaServerNameEnvValue)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS9, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - SERVER, "Name", - novaServerNameEnvValue.toString(), resourceEntry.getKey())); - } - } + @SuppressWarnings("unchecked") + private String checkNovaNameGetParamValueMap(String fileName, Object getParamValue, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + if (getParamValue instanceof List) { + List getParamNameList = (List) getParamValue; + String[] regexName = new String[]{".*_names"}; + return isNovaNameAsListLegal(fileName, regexName, getParamNameList, resourceEntry, globalContext); + } else if (getParamValue instanceof String) { + String[] regexName = new String[]{".*_name_(\\d+)"}; + return isNovaNameAsStringLegal(fileName, (String) getParamValue, regexName, resourceEntry, globalContext); + } + return null; } - } - - private String isNovaNameAsListLegal(String fileName, - String[] regexName, - List getParamNameList, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (getParamNameList.size() != 2 || !ValidationUtil.evalPattern(getParamNameList.get(0), - regexName)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS10, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - SERVER, - "name", getParamNameList.toString(), resourceEntry.getKey())); - return null; + private void checkIfNovaNameParameterInEnvIsStringOrList(String fileName, String envFileName, String novaServerName, + Map.Entry resourceEntry, GlobalValidationContext globalContext) { + if (nonNull(envFileName)) { + Environment environment = ValidationUtil.validateEnvContent(envFileName, globalContext); + if (environment != null && MapUtils.isNotEmpty(environment.getParameters())) { + Object novaServerNameEnvValue = environment.getParameters().get(novaServerName); + if (Objects.nonNull(novaServerNameEnvValue) && !DefinedHeatParameterTypes + .isNovaServerEnvValueIsFromRightType(novaServerNameEnvValue)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS9, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), SERVER, + "Name", novaServerNameEnvValue.toString(), resourceEntry.getKey())); + } + } + } } - return (String) getParamNameList.get(0); - } - - private String isNovaNameAsStringLegal(String fileName, - String novaName, - String[] regexName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - if (!ValidationUtil.evalPattern(novaName, regexName)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS10, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - SERVER, - "name", novaName, resourceEntry.getKey())); - return null; + private String isNovaNameAsListLegal(String fileName, String[] regexName, List getParamNameList, + Map.Entry resourceEntry, GlobalValidationContext globalContext) { + if (getParamNameList.size() != 2 || !ValidationUtil.evalPattern(getParamNameList.get(0), regexName)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS10, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), SERVER, "name", + getParamNameList.toString(), resourceEntry.getKey())); + return null; + } + return (String) getParamNameList.get(0); } - return novaName; - } - - private void validateNovaServerNameImageAndFlavorSync(String fileName, - Map.Entry resourceEntry, - Map legalNovaNamingConventionNames, - GlobalValidationContext globalContext) { - List vmNames = new LinkedList<>(); - for (Map.Entry nameEntry : legalNovaNamingConventionNames.entrySet()) { - vmNames.add(getVmName(nameEntry.getValue(), nameEntry.getKey())); + private String isNovaNameAsStringLegal(String fileName, String novaName, String[] regexName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + if (!ValidationUtil.evalPattern(novaName, regexName)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS10, Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), SERVER, "name", + novaName, resourceEntry.getKey())); + return null; + } + return novaName; } - vmNames.removeIf(Objects::isNull); - - if (!isVmNameSync(vmNames)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - ERROR_CODE_NNS11, Messages.NOVA_NAME_IMAGE_FLAVOR_NOT_CONSISTENT.getErrorMessage(), - resourceEntry.getKey())); + private void validateNovaServerNameImageAndFlavorSync(String fileName, Map.Entry resourceEntry, + Map legalNovaNamingConventionNames, GlobalValidationContext globalContext) { + List vmNames = new LinkedList<>(); + for (Map.Entry nameEntry : legalNovaNamingConventionNames.entrySet()) { + vmNames.add(getVmName(nameEntry.getValue(), nameEntry.getKey())); + } + vmNames.removeIf(Objects::isNull); + if (!isVmNameSync(vmNames)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_NNS11, Messages.NOVA_NAME_IMAGE_FLAVOR_NOT_CONSISTENT.getErrorMessage(), resourceEntry.getKey())); + } } - } - private String getVmName(String nameToGetVmNameFrom, String stringToGetIndexOf) { - int vmIndex = - nameToGetVmNameFrom == null ? -1 : nameToGetVmNameFrom.indexOf(stringToGetIndexOf); - String vmName = null; - if (nameToGetVmNameFrom != null) { - vmName = vmIndex < 0 ? null - : trimNonAlphaNumericCharactersFromEndOfString(nameToGetVmNameFrom.substring(0, vmIndex)); + private String getVmName(String nameToGetVmNameFrom, String stringToGetIndexOf) { + int vmIndex = nameToGetVmNameFrom == null ? -1 : nameToGetVmNameFrom.indexOf(stringToGetIndexOf); + String vmName = null; + if (nameToGetVmNameFrom != null) { + vmName = vmIndex < 0 ? null : trimNonAlphaNumericCharactersFromEndOfString(nameToGetVmNameFrom.substring(0, vmIndex)); + } + return vmName; } - return vmName; - } - private boolean isVmNameSync(List namesToCompare) { - int size = namesToCompare.size(); - for (int i = 0; i < size - 1; i++) { - if (!namesToCompare.get(i).equals(namesToCompare.get(i + 1))) { - return false; - } + private boolean isVmNameSync(List namesToCompare) { + int size = namesToCompare.size(); + for (int i = 0; i < size - 1; i++) { + if (!namesToCompare.get(i).equals(namesToCompare.get(i + 1))) { + return false; + } + } + return true; } - return true; - } - - private String trimNonAlphaNumericCharactersFromEndOfString(String toTrim) { - int stringSize = toTrim.length(); - int stringLength = stringSize - 1; - String[] regexList = new String[]{"[^a-zA-Z0-9]"}; - while (stringLength >= 0) { - if (!ValidationUtil.evalPattern(String.valueOf(toTrim.charAt(stringLength)), regexList)) { - break; - } - stringLength--; + private String trimNonAlphaNumericCharactersFromEndOfString(String toTrim) { + int stringSize = toTrim.length(); + int stringLength = stringSize - 1; + String[] regexList = new String[]{"[^a-zA-Z0-9]"}; + while (stringLength >= 0) { + if (!ValidationUtil.evalPattern(String.valueOf(toTrim.charAt(stringLength)), regexList)) { + break; + } + stringLength--; + } + return toTrim.substring(0, stringLength + 1); } - - return toTrim.substring(0, stringLength + 1); - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/VirtualMachineInterfaceGuidelineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/VirtualMachineInterfaceGuidelineValidator.java index 3662acfde3..ef87d9e66e 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/VirtualMachineInterfaceGuidelineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/VirtualMachineInterfaceGuidelineValidator.java @@ -30,7 +30,6 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; - import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; @@ -45,191 +44,142 @@ import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.NamingConventionValidationContext; public class VirtualMachineInterfaceGuidelineValidator implements ResourceValidator { - private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE1 = new ErrorMessageCode - ("VlANG1"); - private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE2 = new ErrorMessageCode - ("VlANG2"); - private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE3 = new ErrorMessageCode - ("VlANG3"); - - - @Override - public void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext) { - NamingConventionValidationContext namingConventionValidationContext = - (NamingConventionValidationContext) validationContext; - Optional tagPropertyValue = getVlanTagPropertyValue(resourceEntry.getValue()); - - if (tagPropertyValue.isPresent()) { - validateModeledByResourceGroup(fileName, resourceEntry, globalContext, - namingConventionValidationContext); - validateSingleVirtualMachineInterfaceInFile(fileName, globalContext, - namingConventionValidationContext); - validateSubInterfaceNamingConvention(fileName, resourceEntry, globalContext); - } - } - - private void validateModeledByResourceGroup(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - NamingConventionValidationContext namingConventionValidationContext) { - - Object refsPropertyValue = resourceEntry.getValue().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); - if (Objects.isNull(refsPropertyValue)) { - addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1, - Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey()); - return; - } - final boolean modeledThroughResourceGroup = isModeledThroughResourceGroup(fileName, globalContext, - namingConventionValidationContext, refsPropertyValue); - if (!modeledThroughResourceGroup) { - addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1, - Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey()); - } - - } - - private void validateSubInterfaceNamingConvention(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext) { - final String resourceId = resourceEntry.getKey(); - final Optional networkRole = HeatResourceUtil.extractNetworkRoleFromSubInterfaceId(resourceId, resourceEntry - .getValue().getType()); - if (!networkRole.isPresent()) { - addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE3, - Messages.VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION, resourceId); - } - } - - private void validateSingleVirtualMachineInterfaceInFile(String fileName, - GlobalValidationContext globalContext, - NamingConventionValidationContext - namingConventionValidationContext) { - Set forbiddenTypes = Stream.of(NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), - NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()).collect(Collectors.toSet()); - - final Map resources = - namingConventionValidationContext.getHeatOrchestrationTemplate().getResources(); - - if ((countVlanResources(resources) > 1) || fileContainsNonVlanResources(resources, - forbiddenTypes)) { - addViolationToContext(fileName, globalContext, ErrorLevel.ERROR, ERROR_CODE_VLAN_GUIDELINE2, - Messages.VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN, fileName); + private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE1 = new ErrorMessageCode("VlANG1"); + private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE2 = new ErrorMessageCode("VlANG2"); + private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE3 = new ErrorMessageCode("VlANG3"); + + /** + * This method verifies whether the propertyValue is a list containing a single get_param whose value is string + * + * @param fileName on which the validation is currently run + * @param globalContext global validation context + * @param namingConventionValidationContext heat resource validation context + * @param propertyValue the value which is examined + * @return whether the propertyValue is a list containing a single get_param whose value is string + */ + private static boolean isModeledThroughResourceGroup(String fileName, GlobalValidationContext globalContext, + NamingConventionValidationContext namingConventionValidationContext, Object propertyValue) { + final boolean isList = propertyValue instanceof List; + if (!isList || ((List) propertyValue).size() != 1) { + return false; + } + final Object listValue = ((List) propertyValue).get(0); + final Set getParamValues = HeatStructureUtil.getReferencedValuesByFunctionName(fileName, "get_param", listValue, globalContext); + if (getParamValues.isEmpty()) { + return false; //this is not a get_param + } + //validating get_param value + return (getParamValues.size() == 1) && validateGetParamValueOfType(getParamValues, namingConventionValidationContext, + DefinedHeatParameterTypes.STRING.getType()); } - - } - - private boolean fileContainsNonVlanResources(Map resources, - Set forbiddenTypes) { - for (Map.Entry resourceEntry : resources.entrySet()) { - if (forbiddenTypes.contains(resourceEntry.getValue().getType())) { - return true; - } - } - return false; - } - - private int countVlanResources(Map resources) { - int numVlanResources = 0; - for (Map.Entry resourceEntry : resources.entrySet()) { - final String resourceType = resourceEntry.getValue().getType(); - if (resourceType.equals - (CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) { - numVlanResources++; - } + private static boolean validateGetParamValueOfType(Set values, NamingConventionValidationContext namingConventionValidationContext, + String type) { + return values.stream() + .anyMatch(e -> Objects.equals(namingConventionValidationContext.getHeatOrchestrationTemplate().getParameters().get(e).getType(), type)); } - return numVlanResources; - } - - - private void addViolationToContext(String fileName, GlobalValidationContext globalContext, - ErrorLevel error, ErrorMessageCode errorCodeVlanGuideline1, - Messages vlanGuidelineValidationNotModeledThroughResourceGroup, - String key) { - globalContext.addMessage(fileName, error, ErrorMessagesFormatBuilder - .getErrorWithParameters(errorCodeVlanGuideline1, - vlanGuidelineValidationNotModeledThroughResourceGroup.getErrorMessage(), - key)); - } - - - private Optional getVlanTagPropertyValue(Resource resource) { - Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); - if (Objects.nonNull(vmiProperties) && vmiProperties instanceof Map) { - return Optional.ofNullable(((Map) vmiProperties) - .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); - } - return Optional.empty(); - } - - - /** - * This method verifies whether the propertyValue is a list containing a single get_param - * whose value is string - * - * @param fileName on which the validation is currently run - * @param globalContext global validation context - * @param namingConventionValidationContext heat resource validation context - * @param propertyValue the value which is examined - * @return whether the propertyValue is a list containing a single get_param - * whose value is string - */ - private static boolean isModeledThroughResourceGroup(String fileName, GlobalValidationContext - globalContext, NamingConventionValidationContext namingConventionValidationContext, - Object propertyValue) { - final boolean isList = propertyValue instanceof List; - if (!isList || ((List) propertyValue).size() != 1) { - return false; + @Override + public void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext) { + NamingConventionValidationContext namingConventionValidationContext = (NamingConventionValidationContext) validationContext; + Optional tagPropertyValue = getVlanTagPropertyValue(resourceEntry.getValue()); + if (tagPropertyValue.isPresent()) { + validateModeledByResourceGroup(fileName, resourceEntry, globalContext, namingConventionValidationContext); + validateSingleVirtualMachineInterfaceInFile(fileName, globalContext, namingConventionValidationContext); + validateSubInterfaceNamingConvention(fileName, resourceEntry, globalContext); + } } - final Object listValue = ((List) propertyValue).get(0); - - final Set getParamValues = - HeatStructureUtil.getReferencedValuesByFunctionName(fileName, "get_param", - listValue, globalContext); - if (getParamValues.isEmpty()) { - return false; //this is not a get_param + private void validateModeledByResourceGroup(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + NamingConventionValidationContext namingConventionValidationContext) { + Object refsPropertyValue = resourceEntry.getValue().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); + if (Objects.isNull(refsPropertyValue)) { + addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1, + Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey()); + return; + } + final boolean modeledThroughResourceGroup = isModeledThroughResourceGroup(fileName, globalContext, namingConventionValidationContext, + refsPropertyValue); + if (!modeledThroughResourceGroup) { + addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1, + Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey()); + } } - //validating get_param value - return (getParamValues.size() == 1) && - validateGetParamValueOfType(getParamValues, namingConventionValidationContext, - DefinedHeatParameterTypes.STRING.getType()); + private void validateSubInterfaceNamingConvention(String fileName, Map.Entry resourceEntry, + GlobalValidationContext globalContext) { + final String resourceId = resourceEntry.getKey(); + final Optional networkRole = HeatResourceUtil.extractNetworkRoleFromSubInterfaceId(resourceId, resourceEntry.getValue().getType()); + if (!networkRole.isPresent()) { + addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE3, + Messages.VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION, resourceId); + } + } - } + private void validateSingleVirtualMachineInterfaceInFile(String fileName, GlobalValidationContext globalContext, + NamingConventionValidationContext namingConventionValidationContext) { + Set forbiddenTypes = Stream.of(NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()) + .collect(Collectors.toSet()); + final Map resources = namingConventionValidationContext.getHeatOrchestrationTemplate().getResources(); + if ((countVlanResources(resources) > 1) || fileContainsNonVlanResources(resources, forbiddenTypes)) { + addViolationToContext(fileName, globalContext, ErrorLevel.ERROR, ERROR_CODE_VLAN_GUIDELINE2, + Messages.VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN, fileName); + } + } - private static boolean validateGetParamValueOfType(Set values, - NamingConventionValidationContext - namingConventionValidationContext, - String type) { + private boolean fileContainsNonVlanResources(Map resources, Set forbiddenTypes) { + for (Map.Entry resourceEntry : resources.entrySet()) { + if (forbiddenTypes.contains(resourceEntry.getValue().getType())) { + return true; + } + } + return false; + } - return values.stream().anyMatch(e -> Objects.equals( - namingConventionValidationContext.getHeatOrchestrationTemplate().getParameters().get(e) - .getType(), type)); - } + private int countVlanResources(Map resources) { + int numVlanResources = 0; + for (Map.Entry resourceEntry : resources.entrySet()) { + final String resourceType = resourceEntry.getValue().getType(); + if (resourceType.equals(CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) { + numVlanResources++; + } + } + return numVlanResources; + } + private void addViolationToContext(String fileName, GlobalValidationContext globalContext, ErrorLevel error, + ErrorMessageCode errorCodeVlanGuideline1, Messages vlanGuidelineValidationNotModeledThroughResourceGroup, + String key) { + globalContext.addMessage(fileName, error, ErrorMessagesFormatBuilder + .getErrorWithParameters(errorCodeVlanGuideline1, vlanGuidelineValidationNotModeledThroughResourceGroup.getErrorMessage(), key)); + } + private Optional getVlanTagPropertyValue(Resource resource) { + Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); + if (Objects.nonNull(vmiProperties) && vmiProperties instanceof Map) { + return Optional.ofNullable(((Map) vmiProperties).get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + } + return Optional.empty(); + } - private enum Messages { - VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP("VLAN Resource will not be " + - "translated as the VLAN Sub-interface [%s] is not modeled as resource group"), - VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN("There should not be any Compute Server Node, Port, " + - "Parent Port in nested file [%s]"), - VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION( - "Network role associated with VLAN Sub-interface id[%s] is not following the naming convention"); + private enum Messages { + // @formatter:off + VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP("VLAN Resource will not be translated as the VLAN Sub-interface [%s] is not " + + "modeled as resource group"), + VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN("There should not be any Compute Server Node, Port, Parent Port in nested file [%s]"), + VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION("Network role associated with VLAN Sub-interface id[%s] is not following the naming convention"); + // @formatter:on - private final String errorMessage; + private final String errorMessage; - Messages(String errorMessage) { - this.errorMessage = errorMessage; - } + Messages(String errorMessage) { + this.errorMessage = errorMessage; + } - String getErrorMessage() { - return errorMessage; + String getErrorMessage() { + return errorMessage; + } } - } - - -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java index f351af0992..3b7d37105d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,102 +17,100 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.validation.tos; -import org.apache.commons.collections4.MapUtils; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - +import org.apache.commons.collections4.MapUtils; public class ContrailResourcesMappingTo { - private Map> contrailV1Resources; - private Map> contrailV2Resources; - /** - * Add ContrailV1Resource. - * - * @param fileName the file name - * @param resourceName the resource name - */ - public void addContrailV1Resource(String fileName, String resourceName) { - if (MapUtils.isEmpty(contrailV1Resources)) { - contrailV1Resources = new HashMap<>(); + private Map> contrailV1Resources; + private Map> contrailV2Resources; + + /** + * Add ContrailV1Resource. + * + * @param fileName the file name + * @param resourceName the resource name + */ + public void addContrailV1Resource(String fileName, String resourceName) { + if (MapUtils.isEmpty(contrailV1Resources)) { + contrailV1Resources = new HashMap<>(); + } + contrailV1Resources.putIfAbsent(fileName, new ArrayList<>()); + contrailV1Resources.get(fileName).add(resourceName); } - contrailV1Resources.putIfAbsent(fileName, new ArrayList<>()); - contrailV1Resources.get(fileName).add(resourceName); - } - /** - * Add ContrailV1Resource. - * - * @param fileName the file name - * @param resourceName the resource name - */ - public void addContrailV2Resource(String fileName, String resourceName) { - if (MapUtils.isEmpty(contrailV2Resources)) { - contrailV2Resources = new HashMap<>(); + /** + * Add ContrailV1Resource. + * + * @param fileName the file name + * @param resourceName the resource name + */ + public void addContrailV2Resource(String fileName, String resourceName) { + if (MapUtils.isEmpty(contrailV2Resources)) { + contrailV2Resources = new HashMap<>(); + } + contrailV2Resources.putIfAbsent(fileName, new ArrayList<>()); + contrailV2Resources.get(fileName).add(resourceName); } - contrailV2Resources.putIfAbsent(fileName, new ArrayList<>()); - contrailV2Resources.get(fileName).add(resourceName); - } - public void addAll(ContrailResourcesMappingTo contrailResourcesMappingTo) { - addContrailV1Resources(contrailResourcesMappingTo.getContrailV1Resources()); - addContrailV2Resources(contrailResourcesMappingTo.getContrailV2Resources()); - } + public void addAll(ContrailResourcesMappingTo contrailResourcesMappingTo) { + addContrailV1Resources(contrailResourcesMappingTo.getContrailV1Resources()); + addContrailV2Resources(contrailResourcesMappingTo.getContrailV2Resources()); + } - public String fetchContrailV1Resources() { - return fetchContrailResources(contrailV1Resources); - } + public String fetchContrailV1Resources() { + return fetchContrailResources(contrailV1Resources); + } - public String fetchContrailV2Resources() { - return fetchContrailResources(contrailV2Resources); - } + public String fetchContrailV2Resources() { + return fetchContrailResources(contrailV2Resources); + } - private void addContrailV1Resources(Map> contrailV1Resources) { - if (!MapUtils.isEmpty(contrailV1Resources)) { - for (Map.Entry> fileResourcesEntry : contrailV1Resources.entrySet()) { - for (String resourceName : fileResourcesEntry.getValue()) { - this.addContrailV1Resource(fileResourcesEntry.getKey(), resourceName); + private void addContrailV1Resources(Map> contrailV1Resources) { + if (!MapUtils.isEmpty(contrailV1Resources)) { + for (Map.Entry> fileResourcesEntry : contrailV1Resources.entrySet()) { + for (String resourceName : fileResourcesEntry.getValue()) { + this.addContrailV1Resource(fileResourcesEntry.getKey(), resourceName); + } + } } - } } - } - private void addContrailV2Resources(Map> contrailV2Resources) { - if (!MapUtils.isEmpty(contrailV2Resources)) { - for (Map.Entry> fileResourcesEntry : contrailV2Resources.entrySet()) { - for (String resourceName : fileResourcesEntry.getValue()) { - this.addContrailV2Resource(fileResourcesEntry.getKey(), resourceName); + private void addContrailV2Resources(Map> contrailV2Resources) { + if (!MapUtils.isEmpty(contrailV2Resources)) { + for (Map.Entry> fileResourcesEntry : contrailV2Resources.entrySet()) { + for (String resourceName : fileResourcesEntry.getValue()) { + this.addContrailV2Resource(fileResourcesEntry.getKey(), resourceName); + } + } } - } } - } - private String fetchContrailResources(Map> contrailResources) { - StringBuilder buffer = new StringBuilder(); - if (MapUtils.isEmpty(contrailResources)) { - return ""; - } - for (Map.Entry> fileResourcesEntry : contrailResources.entrySet()) { - buffer.append(" file '").append(fileResourcesEntry.getKey()).append("' , resources :"); - for (String resourceName : fileResourcesEntry.getValue()) { - buffer.append("'").append(resourceName).append("', "); - } + private String fetchContrailResources(Map> contrailResources) { + StringBuilder buffer = new StringBuilder(); + if (MapUtils.isEmpty(contrailResources)) { + return ""; + } + for (Map.Entry> fileResourcesEntry : contrailResources.entrySet()) { + buffer.append(" file '").append(fileResourcesEntry.getKey()).append("' , resources :"); + for (String resourceName : fileResourcesEntry.getValue()) { + buffer.append("'").append(resourceName).append("', "); + } + } + buffer.deleteCharAt(buffer.lastIndexOf(",")); + return buffer.toString(); } - buffer.deleteCharAt(buffer.lastIndexOf(",")); - return buffer.toString(); - } - public Map> getContrailV1Resources() { - return contrailV1Resources; - } + public Map> getContrailV1Resources() { + return contrailV1Resources; + } - public Map> getContrailV2Resources() { - return contrailV2Resources; - } + public Map> getContrailV2Resources() { + return contrailV2Resources; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java index 7912dbd393..6197bda119 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java @@ -23,7 +23,8 @@ package org.openecomp.sdc.validation.type; * Created by TALIO on 2/22/2017. */ public class ValidatorConstants { - public static final String Security_Group = "SecurityGroup"; - public static final String Server_Group = "ServerGroup"; - public static final String Network_Policy = "NetworkPolicy"; + + public static final String Security_Group = "SecurityGroup"; + public static final String Server_Group = "ServerGroup"; + public static final String Network_Policy = "NetworkPolicy"; } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/ResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/ResourceValidator.java index ff0e65c9e3..f5c33c48ec 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/ResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/ResourceValidator.java @@ -19,16 +19,15 @@ */ package org.openecomp.sdc.validation; +import java.util.Map; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.model.Resource; -import java.util.Map; - /** * Created by TALIO on 2/23/2017. */ public interface ResourceValidator { - void validate(String fileName, Map.Entry resourceEntry, - GlobalValidationContext globalContext, ValidationContext validationContext); + void validate(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + ValidationContext validationContext); } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/Validator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/Validator.java index 3ed7e74749..5ab83c5854 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/Validator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/Validator.java @@ -13,16 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.validation; -import org.openecomp.core.validation.types.GlobalValidationContext; - import java.util.Map; - +import org.openecomp.core.validation.types.GlobalValidationContext; public interface Validator { - void validate(GlobalValidationContext globalContext); - default void init(Map properties){ } + void validate(GlobalValidationContext globalContext); + + default void init(Map properties) { + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java index a15c7678f7..50d8a86954 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java @@ -12,10 +12,12 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.validation.base; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.validation.ErrorMessageCode; @@ -38,145 +40,108 @@ import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.util.ValidationUtil; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; - /** * Created by TALIO on 2/16/2017. */ public class ResourceBaseValidator implements Validator { - protected final Map resourceTypeToImpl = new HashMap<>(); - private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); - private static final ErrorMessageCode ERROR_CODE_RBV_1 = new ErrorMessageCode("RBV1"); - private static final ErrorMessageCode ERROR_CODE_RBV_2 = new ErrorMessageCode("RBV2"); - - Map getResourceTypeToImpl() { - return MapUtils.unmodifiableMap(this.resourceTypeToImpl); - } + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); + private static final ErrorMessageCode ERROR_CODE_RBV_1 = new ErrorMessageCode("RBV1"); + private static final ErrorMessageCode ERROR_CODE_RBV_2 = new ErrorMessageCode("RBV2"); + protected final Map resourceTypeToImpl = new HashMap<>(); - @Override - public void init(Map properties) { - if (MapUtils.isEmpty(properties)) { - return; + private static boolean isSupportedResourceType(String resourceType, Map resourceTypeToImpl) { + return resourceTypeToImpl.containsKey(resourceType) && resourceTypeToImpl.get(resourceType).isEnable(); } - properties.entrySet().stream() - .filter(entry -> getImplementationConfigurationFromProperties(entry.getValue()) != null) - .forEach(entry -> resourceTypeToImpl - .put(entry.getKey(), getImplementationConfigurationFromProperties(entry.getValue()))); - } - - @Override - public void validate(GlobalValidationContext globalContext) { - ManifestContent manifestContent; - try { - manifestContent = ValidationUtil.validateManifest(globalContext); - } catch (Exception exception) { - LOGGER.error("Failed to validate manifest file", exception); - return; + private static ResourceValidator getResourceValidatorInstance(String resourceType, Map resourceTypeToImpl) { + ResourceValidator resourceBaseValidator = null; + if (isSupportedResourceType(resourceType, resourceTypeToImpl)) { + return getValidatorImpl(resourceType, resourceTypeToImpl); + } + if (HeatStructureUtil.isNestedResource(resourceType)) { + return getValidatorImpl("nestedResource", resourceTypeToImpl); + } + return resourceBaseValidator; } - Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - Map fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); - globalContext.getFiles().stream() - .filter(fileName -> FileData - .isHeatFile(fileTypeMap.get(fileName))) - .forEach(fileName -> validate(fileName, - fileEnvMap.get(fileName) != null ? fileEnvMap.get(fileName).getFile() : null, - globalContext)); - } - - private void validate(String fileName, String envFileName, - GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_RBV_2); - HeatOrchestrationTemplate heatOrchestrationTemplate = - ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); - if (heatOrchestrationTemplate == null) { - return; + private static ResourceValidator getValidatorImpl(String resourceType, Map resourceTypeToImpl) { + String implementationClass = + resourceTypeToImpl.get(resourceType) != null ? resourceTypeToImpl.get(resourceType).getImplementationClass() : null; + return implementationClass == null ? null : CommonMethods.newInstance(implementationClass, ResourceValidator.class); } - ValidationContext validationContext = - createValidationContext(fileName, envFileName, heatOrchestrationTemplate, globalContext); - - Map resourcesMap = heatOrchestrationTemplate.getResources(); - if (MapUtils.isEmpty(resourcesMap)) { - return; + Map getResourceTypeToImpl() { + return MapUtils.unmodifiableMap(this.resourceTypeToImpl); } - for (Map.Entry resourceEntry : resourcesMap.entrySet()) { - String resourceType = resourceEntry.getValue().getType(); - - if (Objects.isNull(resourceType)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_RBV_1, - Messages.INVALID_RESOURCE_TYPE.getErrorMessage(),"null", - resourceEntry.getKey())); - } else { - ResourceValidator - resourceValidatorImpl = getResourceValidatorInstance(resourceType, resourceTypeToImpl); - if (Objects.nonNull(resourceValidatorImpl)) { - resourceValidatorImpl.validate(fileName, resourceEntry, globalContext, - validationContext); + @Override + public void init(Map properties) { + if (MapUtils.isEmpty(properties)) { + return; } - } + properties.entrySet().stream().filter(entry -> getImplementationConfigurationFromProperties(entry.getValue()) != null) + .forEach(entry -> resourceTypeToImpl.put(entry.getKey(), getImplementationConfigurationFromProperties(entry.getValue()))); } - } - - public ValidationContext createValidationContext(String fileName, - String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - return null; - } - - private static boolean isSupportedResourceType(String resourceType, - Map resourceTypeToImpl) { - return resourceTypeToImpl.containsKey(resourceType) && resourceTypeToImpl.get(resourceType) - .isEnable(); - - } - private static ResourceValidator getResourceValidatorInstance(String resourceType, - Map resourceTypeToImpl) { - ResourceValidator resourceBaseValidator = null; - if (isSupportedResourceType(resourceType, resourceTypeToImpl)) { - return getValidatorImpl(resourceType, resourceTypeToImpl); - } - if (HeatStructureUtil.isNestedResource(resourceType)) { - return getValidatorImpl("nestedResource", resourceTypeToImpl); + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.validateManifest(globalContext); + } catch (Exception exception) { + LOGGER.error("Failed to validate manifest file", exception); + return; + } + Map fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + Map fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); + globalContext.getFiles().stream().filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, fileEnvMap.get(fileName) != null ? fileEnvMap.get(fileName).getFile() : null, globalContext)); } - return resourceBaseValidator; - } - - private static ResourceValidator getValidatorImpl(String resourceType, - Map resourceTypeToImpl) { - String implementationClass = resourceTypeToImpl.get(resourceType) != null ? - resourceTypeToImpl.get(resourceType).getImplementationClass() : null; - return implementationClass == null ? null : CommonMethods - .newInstance(implementationClass, ResourceValidator.class); - } - - private ImplementationConfiguration getImplementationConfigurationFromProperties(Object value) { - ImplementationConfiguration implementationConfiguration = new ImplementationConfiguration(); - if (!(value instanceof Map)) { - return null; + private void validate(String fileName, String envFileName, GlobalValidationContext globalContext) { + globalContext.setMessageCode(ERROR_CODE_RBV_2); + HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; + } + ValidationContext validationContext = createValidationContext(fileName, envFileName, heatOrchestrationTemplate, globalContext); + Map resourcesMap = heatOrchestrationTemplate.getResources(); + if (MapUtils.isEmpty(resourcesMap)) { + return; + } + for (Map.Entry resourceEntry : resourcesMap.entrySet()) { + String resourceType = resourceEntry.getValue().getType(); + if (Objects.isNull(resourceType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_RBV_1, Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", resourceEntry.getKey())); + } else { + ResourceValidator resourceValidatorImpl = getResourceValidatorInstance(resourceType, resourceTypeToImpl); + if (Objects.nonNull(resourceValidatorImpl)) { + resourceValidatorImpl.validate(fileName, resourceEntry, globalContext, validationContext); + } + } + } } - Map valueAsMap = (Map) value; - if (!(valueAsMap.containsKey(ConfigConstants.Impl_Class))) { - return null; + public ValidationContext createValidationContext(String fileName, String envFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + return null; } - implementationConfiguration.setImplementationClass( - valueAsMap.get(ConfigConstants.Impl_Class).toString()); - if (valueAsMap.containsKey(ConfigConstants.Enable)) { - implementationConfiguration.setEnable(Boolean. - valueOf(valueAsMap.get(ConfigConstants.Enable).toString())); + private ImplementationConfiguration getImplementationConfigurationFromProperties(Object value) { + ImplementationConfiguration implementationConfiguration = new ImplementationConfiguration(); + if (!(value instanceof Map)) { + return null; + } + Map valueAsMap = (Map) value; + if (!(valueAsMap.containsKey(ConfigConstants.Impl_Class))) { + return null; + } + implementationConfiguration.setImplementationClass(valueAsMap.get(ConfigConstants.Impl_Class).toString()); + if (valueAsMap.containsKey(ConfigConstants.Enable)) { + implementationConfiguration.setEnable(Boolean.valueOf(valueAsMap.get(ConfigConstants.Enable).toString())); + } + return implementationConfiguration; } - - return implementationConfiguration; - } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/ConfigConstants.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/ConfigConstants.java index aacaa10c11..45ac08edeb 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/ConfigConstants.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/ConfigConstants.java @@ -23,14 +23,15 @@ package org.openecomp.sdc.validation.type; * Created by TALIO on 1/30/2017. */ public class ConfigConstants { - public static final String Enable = "enable"; - public static final String Impl_Class = "implementationClass"; - public static final String Resource_Base_Validator = "resourceBaseValidator"; - public static final String Namespace = "validation"; - public static final String Mandatory_Namespace = "mandatoryValidation"; - public static final String Validator_Impl_Key = "validatorImplementations"; - public static final String Nested_Resource_Key = "nestedResource"; + public static final String Enable = "enable"; + public static final String Impl_Class = "implementationClass"; + public static final String Resource_Base_Validator = "resourceBaseValidator"; + public static final String Namespace = "validation"; + public static final String Mandatory_Namespace = "mandatoryValidation"; + public static final String Validator_Impl_Key = "validatorImplementations"; + public static final String Nested_Resource_Key = "nestedResource"; - private ConfigConstants(){} + private ConfigConstants() { + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/HeatResourceValidationContext.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/HeatResourceValidationContext.java index 97703b1de0..5921b51c77 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/HeatResourceValidationContext.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/HeatResourceValidationContext.java @@ -15,13 +15,12 @@ */ package org.openecomp.sdc.validation.type; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.validation.ValidationContext; - import java.util.List; import java.util.Map; -import lombok.Getter; import lombok.EqualsAndHashCode; +import lombok.Getter; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.validation.ValidationContext; /** * Created by TALIO on 2/23/2017. @@ -30,21 +29,19 @@ import lombok.EqualsAndHashCode; @EqualsAndHashCode public class HeatResourceValidationContext implements ValidationContext { - private HeatOrchestrationTemplate heatOrchestrationTemplate; - // key - resource type, value - map with key = resource id and - // value = map with key = pointing / pointed resource type and - // value = pointing / pointed resource id - private Map>>> fileLevelResourceDependencies; - private String envFileName; + private HeatOrchestrationTemplate heatOrchestrationTemplate; + // key - resource type, value - map with key = resource id and + // value = map with key = pointing / pointed resource type and - public HeatResourceValidationContext( - HeatOrchestrationTemplate heatOrchestrationTemplate, - Map>>> fileLevelResourceDependencies, - String envFileName) { + // value = pointing / pointed resource id + private Map>>> fileLevelResourceDependencies; + private String envFileName; - this.heatOrchestrationTemplate = heatOrchestrationTemplate; - this.fileLevelResourceDependencies = fileLevelResourceDependencies; - this.envFileName = envFileName; - } + public HeatResourceValidationContext(HeatOrchestrationTemplate heatOrchestrationTemplate, + Map>>> fileLevelResourceDependencies, String envFileName) { + this.heatOrchestrationTemplate = heatOrchestrationTemplate; + this.fileLevelResourceDependencies = fileLevelResourceDependencies; + this.envFileName = envFileName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/NamingConventionValidationContext.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/NamingConventionValidationContext.java index 7bad45f5fd..3058d36ed3 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/NamingConventionValidationContext.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/type/NamingConventionValidationContext.java @@ -16,12 +16,11 @@ package org.openecomp.sdc.validation.type; import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.validation.ValidationContext; -import lombok.Getter; -import lombok.EqualsAndHashCode; - /** * Created by TALIO on 2/23/2017. */ @@ -30,6 +29,6 @@ import lombok.EqualsAndHashCode; @AllArgsConstructor public class NamingConventionValidationContext implements ValidationContext { - private HeatOrchestrationTemplate heatOrchestrationTemplate; - private String envFileName; + private HeatOrchestrationTemplate heatOrchestrationTemplate; + private String envFileName; } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java index a741df1b79..28613c96df 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java @@ -12,10 +12,17 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.validation.util; +import static java.util.Objects.nonNull; + +import java.io.InputStream; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; import org.apache.commons.collections4.CollectionUtils; import org.onap.sdc.tosca.services.YamlUtil; import org.openecomp.core.utilities.json.JsonUtil; @@ -26,190 +33,159 @@ import org.openecomp.sdc.common.errors.SdcRuntimeException; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; -import org.openecomp.sdc.heat.datatypes.model.*; +import org.openecomp.sdc.heat.datatypes.model.Environment; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.io.InputStream; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Pattern; - -import static java.util.Objects.nonNull; - public class ValidationUtil { - private static final Logger LOG = LoggerFactory.getLogger(ValidationUtil.class.getName()); - - private ValidationUtil(){} - - public static void removeExposedResourcesCalledByGetResource(String fileName, - Set actualExposedResources, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map resourcesMap = heatOrchestrationTemplate.getResources(); - for (Map.Entry resourceEntry : resourcesMap.entrySet()) { - Set referencedResources = - HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions - .GET_RESOURCE - .getFunction(), resourceEntry.getValue().getProperties(), globalContext); + private static final Logger LOG = LoggerFactory.getLogger(ValidationUtil.class.getName()); - removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources, - resourcesMap); + private ValidationUtil() { } - } - - private static void removeExposedResourcesCalledByGetResource(Set referencedResources, - Set - actualExposedResources, - Map resourcesMap) { - for (String referencedResourceName : referencedResources) { - Resource currResource = resourcesMap.get(referencedResourceName); - if (Objects.nonNull(currResource) && isExpectedToBeExposed(currResource.getType())) { - actualExposedResources.add(referencedResourceName); - } - } - } - - public static boolean isExpectedToBeExposed(String type) { - return HeatResourcesTypes.isResourceExpectedToBeExposed(type); - } - - public static String getWantedNameFromPropertyValueGetParam(Object value) { - Set paramName = HeatStructureUtil - .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(), - value, null); - if (paramName != null && CollectionUtils.isNotEmpty(paramName)) { - return (String) paramName.toArray()[0]; - } - return null; - } - public static boolean evalPattern(Object paramVal, String[] regexList) { - String value = ""; - if (paramVal instanceof String) { - value = (String) paramVal; + public static void removeExposedResourcesCalledByGetResource(String fileName, Set actualExposedResources, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Map resourcesMap = heatOrchestrationTemplate.getResources(); + for (Map.Entry resourceEntry : resourcesMap.entrySet()) { + Set referencedResources = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions.GET_RESOURCE.getFunction(), + resourceEntry.getValue().getProperties(), globalContext); + removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources, resourcesMap); + } } - if (paramVal instanceof Integer) { - value = paramVal.toString(); - } - return evalPattern(value, regexList); - } - - private static boolean evalPattern(String paramVal, String[] regexList) { - for (String regex : regexList) { - if (Pattern.matches(regex, paramVal)) { - return true; - } + private static void removeExposedResourcesCalledByGetResource(Set referencedResources, Set actualExposedResources, + Map resourcesMap) { + for (String referencedResourceName : referencedResources) { + Resource currResource = resourcesMap.get(referencedResourceName); + if (Objects.nonNull(currResource) && isExpectedToBeExposed(currResource.getType())) { + actualExposedResources.add(referencedResourceName); + } + } } - return false; - } - - public static String getMessagePartAccordingToResourceType(Map.Entry - resourceEntry) { - HeatResourcesTypes resourcesType = - HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType()); - if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) { - return "Server"; - } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) { - return "Service Template"; - } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) { - return "Service Instance"; - } else { - return ""; + public static boolean isExpectedToBeExposed(String type) { + return HeatResourcesTypes.isResourceExpectedToBeExposed(type); } - } - - public static Environment validateEnvContent(String envFileName, - GlobalValidationContext globalContext) { - Environment envContent; - try { - Optional fileContent = globalContext.getFileContent(envFileName); - if (fileContent.isPresent()) { - envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class); - } else { - throw new Exception("The file '" + envFileName + "' has no content"); - } - } catch (Exception exception) { - LOG.error("Invalid envFile name : " + envFileName, exception); - return null; + + public static String getWantedNameFromPropertyValueGetParam(Object value) { + Set paramName = HeatStructureUtil + .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(), value, null); + if (paramName != null && CollectionUtils.isNotEmpty(paramName)) { + return (String) paramName.toArray()[0]; + } + return null; } - return envContent; - } - - public static boolean validateMapPropertyValue(String fileName, - Map.Entry resourceEntry, - GlobalValidationContext globalContext, - String propertyName, Object nameValue, - String[] regexList) { - String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue); - if (nonNull(propertyValue) && !evalPattern(propertyValue, regexList)) { - globalContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters(globalContext.getMessageCode(), - Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), - getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue, - resourceEntry.getKey())); - return true; - } - return false; - } - - public static ManifestContent validateManifest(GlobalValidationContext globalContext) { - Optional manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); - if (!manifest.isPresent()) { - throw new RuntimeException("Can't load manifest file for Heat Validator"); + + public static boolean evalPattern(Object paramVal, String[] regexList) { + String value = ""; + if (paramVal instanceof String) { + value = (String) paramVal; + } + if (paramVal instanceof Integer) { + value = paramVal.toString(); + } + return evalPattern(value, regexList); } - ManifestContent manifestContent; - try { - manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class); - } catch (Exception exception) { - throw new SdcRuntimeException("Can't load manifest file for Heat Validator", exception); + + private static boolean evalPattern(String paramVal, String[] regexList) { + for (String regex : regexList) { + if (Pattern.matches(regex, paramVal)) { + return true; + } + } + return false; } - return manifestContent; - } + public static String getMessagePartAccordingToResourceType(Map.Entry resourceEntry) { + HeatResourcesTypes resourcesType = HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType()); + if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) { + return "Server"; + } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) { + return "Service Template"; + } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) { + return "Service Instance"; + } else { + return ""; + } + } - public static String getParserExceptionReason(Exception exception) { - String reason; + public static Environment validateEnvContent(String envFileName, GlobalValidationContext globalContext) { + Environment envContent; + try { + Optional fileContent = globalContext.getFileContent(envFileName); + if (fileContent.isPresent()) { + envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class); + } else { + throw new Exception("The file '" + envFileName + "' has no content"); + } + } catch (Exception exception) { + LOG.error("Invalid envFile name : " + envFileName, exception); + return null; + } + return envContent; + } - if (exception.getCause() != null && exception.getCause().getCause() != null) { - reason = exception.getCause().getCause().getMessage(); - } else if (exception.getCause() != null) { - reason = exception.getCause().getMessage(); - } else { - reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage(); + public static boolean validateMapPropertyValue(String fileName, Map.Entry resourceEntry, GlobalValidationContext globalContext, + String propertyName, Object nameValue, String[] regexList) { + String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue); + if (nonNull(propertyValue) && !evalPattern(propertyValue, regexList)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(globalContext.getMessageCode(), Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue, resourceEntry.getKey())); + return true; + } + return false; } - return reason; - } - - public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName, - GlobalValidationContext globalContext) { - HeatOrchestrationTemplate heatOrchestrationTemplate; - try { - Optional fileContent = globalContext.getFileContent(fileName); - if (fileContent.isPresent()) { - heatOrchestrationTemplate = - new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); - } else { - heatOrchestrationTemplate = null; - } - } catch (Exception exception) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(globalContext.getMessageCode(), - Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage() - , getParserExceptionReason(exception))); - return null; + + public static ManifestContent validateManifest(GlobalValidationContext globalContext) { + Optional manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); + if (!manifest.isPresent()) { + throw new RuntimeException("Can't load manifest file for Heat Validator"); + } + ManifestContent manifestContent; + try { + manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class); + } catch (Exception exception) { + throw new SdcRuntimeException("Can't load manifest file for Heat Validator", exception); + } + return manifestContent; } - return heatOrchestrationTemplate; - } + public static String getParserExceptionReason(Exception exception) { + String reason; + if (exception.getCause() != null && exception.getCause().getCause() != null) { + reason = exception.getCause().getCause().getMessage(); + } else if (exception.getCause() != null) { + reason = exception.getCause().getMessage(); + } else { + reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage(); + } + return reason; + } + public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName, GlobalValidationContext globalContext) { + HeatOrchestrationTemplate heatOrchestrationTemplate; + try { + Optional fileContent = globalContext.getFileContent(fileName); + if (fileContent.isPresent()) { + heatOrchestrationTemplate = new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + heatOrchestrationTemplate = null; + } + } catch (Exception exception) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(globalContext.getMessageCode(), Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + getParserExceptionReason(exception))); + return null; + } + return heatOrchestrationTemplate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/HealingServiceFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/HealingServiceFactory.java index 19d664247b..9b76fe96db 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/HealingServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/HealingServiceFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -26,7 +25,7 @@ import org.openecomp.sdc.vendorlicense.healing.HealingService; public abstract class HealingServiceFactory extends AbstractComponentFactory { - public static HealingServiceFactory getInstance() { - return AbstractFactory.getInstance(HealingServiceFactory.class); - } + public static HealingServiceFactory getInstance() { + return AbstractFactory.getInstance(HealingServiceFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactory.java index 0ce7484aa7..a79c01ae51 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService; -public abstract class VendorLicenseArtifactServiceFactory - extends AbstractComponentFactory { +public abstract class VendorLicenseArtifactServiceFactory extends AbstractComponentFactory { - public static VendorLicenseArtifactServiceFactory getInstance() { - return AbstractFactory.getInstance(VendorLicenseArtifactServiceFactory.class); - } + public static VendorLicenseArtifactServiceFactory getInstance() { + return AbstractFactory.getInstance(VendorLicenseArtifactServiceFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseConstants.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseConstants.java index 82fdf045db..d43797e498 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseConstants.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseConstants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,30 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense; import java.io.File; public final class VendorLicenseConstants { - public static final String VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE = "VendorLicenseModel"; - public static final String EXTERNAL_ARTIFACTS_DIR = "Artifacts"; - //todo change when separating external from internal artifacts - public static final String VNF_ARTIFACT_NAME_WITH_PATH = - EXTERNAL_ARTIFACTS_DIR + File.separator + "vf-license-model.xml"; - public static final String VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH = - EXTERNAL_ARTIFACTS_DIR + File.separator + "vendor-license-model.xml"; - public static final String VENDOR_LICENSE_MODEL_ARTIFACT_REGEX_REMOVE = " xmlns=\"\""; - public static final String UNSUPPORTED_OPERATION_ERROR = - "An error has occurred: Unsupported operation for 1707 release."; + public static final String VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE = "VendorLicenseModel"; + public static final String EXTERNAL_ARTIFACTS_DIR = "Artifacts"; + //todo change when separating external from internal artifacts + public static final String VNF_ARTIFACT_NAME_WITH_PATH = EXTERNAL_ARTIFACTS_DIR + File.separator + "vf-license-model.xml"; + public static final String VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH = EXTERNAL_ARTIFACTS_DIR + File.separator + "vendor-license-model.xml"; + public static final String VENDOR_LICENSE_MODEL_ARTIFACT_REGEX_REMOVE = " xmlns=\"\""; + public static final String UNSUPPORTED_OPERATION_ERROR = "An error has occurred: Unsupported operation for 1707 release."; - public final class UniqueValues { - public static final String VENDOR_NAME = "Vendor name"; - public static final String LICENSE_AGREEMENT_NAME = "License Agreement name"; - public static final String FEATURE_GROUP_NAME = "Feature Group name"; - public static final String ENTITLEMENT_POOL_NAME = "Entitlement Pool name"; - public static final String LICENSE_KEY_GROUP_NAME = "License Key Group name"; + public final class UniqueValues { - } + public static final String VENDOR_NAME = "Vendor name"; + public static final String LICENSE_AGREEMENT_NAME = "License Agreement name"; + public static final String FEATURE_GROUP_NAME = "Feature Group name"; + public static final String ENTITLEMENT_POOL_NAME = "Entitlement Pool name"; + public static final String LICENSE_KEY_GROUP_NAME = "License Key Group name"; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java index 7d9aa27c46..3d30f5a8dc 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java @@ -19,19 +19,18 @@ */ package org.openecomp.sdc.vendorlicense; - import java.text.ParseException; import java.text.SimpleDateFormat; public class VendorLicenseUtil { - public static String getIsoFormatDate(String inputDate) { - SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss'Z'"); - try { - return isoDateFormat.format(inputDateFormat.parse(inputDate)); - } catch (ParseException e) { - return null; + public static String getIsoFormatDate(String inputDate) { + SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss'Z'"); + try { + return isoDateFormat.format(inputDateFormat.parse(inputDate)); + } catch (ParseException e) { + return null; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDao.java index b42f64de7c..15089bc655 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; - +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -import java.util.Collection; - public interface EntitlementPoolDao extends VersionableDao, BaseDao { void create(EntitlementPoolEntity entitlementPool); @@ -39,13 +36,11 @@ public interface EntitlementPoolDao extends VersionableDao, BaseDao list(EntitlementPoolEntity entitlementPool); - long count(EntitlementPoolEntity entitlementPool); + long count(EntitlementPoolEntity entitlementPool); - void deleteAll(EntitlementPoolEntity entitlementPool); + void deleteAll(EntitlementPoolEntity entitlementPool); - void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, - String referencingFeatureGroupId); + void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId); - void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, - String referencingFeatureGroupId); + void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDaoFactory.java index e5bfcfa1cb..02d7b8e1d3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/EntitlementPoolDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class EntitlementPoolDaoFactory - extends AbstractComponentFactory { - public static EntitlementPoolDaoFactory getInstance() { - return AbstractFactory.getInstance(EntitlementPoolDaoFactory.class); - } +public abstract class EntitlementPoolDaoFactory extends AbstractComponentFactory { + + public static EntitlementPoolDaoFactory getInstance() { + return AbstractFactory.getInstance(EntitlementPoolDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDao.java index 3a7ce9ac04..7609c7e003 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; +import java.util.Collection; +import java.util.Set; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -import java.util.Collection; -import java.util.Set; - - public interface FeatureGroupDao extends VersionableDao, BaseDao { void delete(FeatureGroupEntity featureGroup); @@ -38,20 +35,18 @@ public interface FeatureGroupDao extends VersionableDao, BaseDao list(FeatureGroupEntity entity); - long count(FeatureGroupEntity featureGroup); + long count(FeatureGroupEntity featureGroup); - void deleteAll(FeatureGroupEntity featureGroup); + void deleteAll(FeatureGroupEntity featureGroup); - void updateFeatureGroup(FeatureGroupEntity entity, Set addedEntitlementPools, - Set removedEntitlementPools, Set addedLicenseKeyGroups, - Set removedLicenseKeyGroups); + void updateFeatureGroup(FeatureGroupEntity entity, Set addedEntitlementPools, Set removedEntitlementPools, + Set addedLicenseKeyGroups, Set removedLicenseKeyGroups); - void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId); + void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId); - void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, - String licenseAgreementId); + void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId); - void removeEntitlementPool(FeatureGroupEntity featureGroup, String entitlementPoolId); + void removeEntitlementPool(FeatureGroupEntity featureGroup, String entitlementPoolId); - void removeLicenseKeyGroup(FeatureGroupEntity featureGroup, String licenseKeyGroupId); + void removeLicenseKeyGroup(FeatureGroupEntity featureGroup, String licenseKeyGroupId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDaoFactory.java index 5a32ee420a..e06d3dffb6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/FeatureGroupDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; - - public abstract class FeatureGroupDaoFactory extends AbstractComponentFactory { - public static FeatureGroupDaoFactory getInstance() { - return AbstractFactory.getInstance(FeatureGroupDaoFactory.class); - } + + public static FeatureGroupDaoFactory getInstance() { + return AbstractFactory.getInstance(FeatureGroupDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDao.java index c49af9c714..2242722ca5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDao.java @@ -1,45 +1,43 @@ /*- -* Copyright (C) 2016-2017 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright (C) 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.sdc.vendorlicense.dao; +import java.util.Collection; +import java.util.Set; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -import java.util.Collection; -import java.util.Set; +public interface LicenseAgreementDao extends VersionableDao { -public interface LicenseAgreementDao extends VersionableDao{ + long count(LicenseAgreementEntity entity); - long count(LicenseAgreementEntity entity); + void deleteAll(LicenseAgreementEntity entity); - void deleteAll(LicenseAgreementEntity entity); + void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId); - void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId); + void updateColumnsAndDeltaFeatureGroupIds(LicenseAgreementEntity licenseAgreement, Set addedFeatureGroupIds, + Set removedFeatureGroupIds); - void updateColumnsAndDeltaFeatureGroupIds(LicenseAgreementEntity licenseAgreement, - Set addedFeatureGroupIds, - Set removedFeatureGroupIds); - Collection list(LicenseAgreementEntity entity); + Collection list(LicenseAgreementEntity entity); - void create(LicenseAgreementEntity entity); + void create(LicenseAgreementEntity entity); - void update(LicenseAgreementEntity entity); + void update(LicenseAgreementEntity entity); - LicenseAgreementEntity get(LicenseAgreementEntity entity); + LicenseAgreementEntity get(LicenseAgreementEntity entity); - void delete(LicenseAgreementEntity entity); + void delete(LicenseAgreementEntity entity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDaoFactory.java index 54c7b7bfea..324d83094c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseAgreementDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class LicenseAgreementDaoFactory - extends AbstractComponentFactory { - public static LicenseAgreementDaoFactory getInstance() { - return AbstractFactory.getInstance(LicenseAgreementDaoFactory.class); - } +public abstract class LicenseAgreementDaoFactory extends AbstractComponentFactory { + + public static LicenseAgreementDaoFactory getInstance() { + return AbstractFactory.getInstance(LicenseAgreementDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDao.java index 4e0ce93ed4..899d1c9a06 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,28 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; - +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -import java.util.Collection; - - public interface LicenseKeyGroupDao extends VersionableDao, BaseDao { - void create(LicenseKeyGroupEntity licenseKeyGroup); + void create(LicenseKeyGroupEntity licenseKeyGroup); - void delete(LicenseKeyGroupEntity licenseKeyGroup); + void delete(LicenseKeyGroupEntity licenseKeyGroup); - LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup); + LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup); - Collection list(LicenseKeyGroupEntity licenseKeyGroup); + Collection list(LicenseKeyGroupEntity licenseKeyGroup); - long count(LicenseKeyGroupEntity licenseKeyGroup); + long count(LicenseKeyGroupEntity licenseKeyGroup); - void deleteAll(LicenseKeyGroupEntity licenseKeyGroup); + void deleteAll(LicenseKeyGroupEntity licenseKeyGroup); - void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId); + void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId); - void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId); + void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDaoFactory.java index 8c76c46301..f5fece1e42 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LicenseKeyGroupDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; +public abstract class LicenseKeyGroupDaoFactory extends AbstractComponentFactory { -public abstract class LicenseKeyGroupDaoFactory - extends AbstractComponentFactory { - - public static LicenseKeyGroupDaoFactory getInstance() { - return AbstractFactory.getInstance(LicenseKeyGroupDaoFactory.class); - } + public static LicenseKeyGroupDaoFactory getInstance() { + return AbstractFactory.getInstance(LicenseKeyGroupDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDao.java index ab302b5982..b01649ecb6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDao.java @@ -25,5 +25,5 @@ import org.openecomp.sdc.versioning.dao.VersionableDao; public interface LimitDao extends VersionableDao, BaseDao { - boolean isLimitPresent(LimitEntity limitEntity); + boolean isLimitPresent(LimitEntity limitEntity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDaoFactory.java index 2971d72507..3c3657e246 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/LimitDaoFactory.java @@ -23,7 +23,8 @@ import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class LimitDaoFactory extends AbstractComponentFactory { - public static LimitDaoFactory getInstance() { - return AbstractFactory.getInstance(LimitDaoFactory.class); - } + + public static LimitDaoFactory getInstance() { + return AbstractFactory.getInstance(LimitDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDao.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDao.java index 0bb2e62b41..eedca41cdc 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.dao.BaseDao; @@ -25,4 +24,5 @@ import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; public interface VendorLicenseModelDao extends VersionableDao, BaseDao { + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDaoFactory.java index b6d13a9027..cbfbb9ffa1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/VendorLicenseModelDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class VendorLicenseModelDaoFactory - extends AbstractComponentFactory { +public abstract class VendorLicenseModelDaoFactory extends AbstractComponentFactory { - public static VendorLicenseModelDaoFactory getInstance() { - return AbstractFactory.getInstance(VendorLicenseModelDaoFactory.class); - } + public static VendorLicenseModelDaoFactory getInstance() { + return AbstractFactory.getInstance(VendorLicenseModelDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/AggregationFunction.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/AggregationFunction.java index 5b5a97f92b..be27bc0fe0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/AggregationFunction.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/AggregationFunction.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; -public enum AggregationFunction { - Peak, - Average, - Other; -} +public enum AggregationFunction {Peak, Average, Other;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ChoiceOrOther.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ChoiceOrOther.java index 01699355f5..e4d58fad29 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ChoiceOrOther.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ChoiceOrOther.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.Transient; @@ -24,126 +23,116 @@ import org.openecomp.sdc.common.errors.ErrorCode; @UDT(keyspace = "dox", name = "choice_or_other") public class ChoiceOrOther> { - private static final String CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID = - "MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID"; - private static final String CHOICE_OR_OTHER_INVALID_ENUM_MSG = - "Enum used as part of ChoiceOrOther type must contain the value 'Other'"; - public static final String OTHER_ENUM_VALUE = "Other"; - - @Transient - private E choice; - - @Transient - private String other; - - private String result; - - public ChoiceOrOther() { - // the default constructor is used to instantiate by reflection - } - - /** - * Instantiates a new Choice or other. - * - * @param choice the choice - * @param other the other - */ - public ChoiceOrOther(E choice, String other) { - this.choice = choice; - this.other = other; - result = resolveResult(); - } - - public E getChoice() { - return choice; - } - - public void setChoice(E choice) { - - this.choice = choice; - } - - public String getOther() { - return other; - } - - public void setOther(String other) { - this.other = other; - } - - public String getResult() { - return result; - } + public static final String OTHER_ENUM_VALUE = "Other"; + private static final String CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID = "MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID"; + private static final String CHOICE_OR_OTHER_INVALID_ENUM_MSG = "Enum used as part of ChoiceOrOther type must contain the value 'Other'"; + @Transient + private E choice; + @Transient + private String other; + private String result; + + public ChoiceOrOther() { + // the default constructor is used to instantiate by reflection + } - /** - * Sets result. - * - * @param result the result - */ - public void setResult(String result) { - if (choice != null) { - if (result == null) { - this.result = resolveResult(); - } - } else { - this.result = result; + /** + * Instantiates a new Choice or other. + * + * @param choice the choice + * @param other the other + */ + public ChoiceOrOther(E choice, String other) { + this.choice = choice; + this.other = other; + result = resolveResult(); } - } - private String resolveResult() { - return OTHER_ENUM_VALUE.equals(choice.name()) ? other : choice.name(); - } + public E getChoice() { + return choice; + } - /** - * Resolve enum. - * - * @param enumClass the enum class - */ - public void resolveEnum(Class enumClass) { - if (choice != null || result == null) { - return; + public void setChoice(E choice) { + this.choice = choice; } - try { - choice = E.valueOf(enumClass, result); - } catch (IllegalArgumentException exception) { - try { - choice = E.valueOf(enumClass, OTHER_ENUM_VALUE); - } catch (IllegalArgumentException ex) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withId(CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID) - .withMessage(CHOICE_OR_OTHER_INVALID_ENUM_MSG).build()); - } - other = result; + public String getOther() { + return other; } - } - @Override - public int hashCode() { - int result1 = choice != null ? choice.hashCode() : 0; - result1 = 31 * result1 + (other != null ? other.hashCode() : 0); - result1 = 31 * result1 + (result != null ? result.hashCode() : 0); - return result1; - } + public void setOther(String other) { + this.other = other; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + public String getResult() { + return result; } - if (obj == null || getClass() != obj.getClass()) { - return false; + + /** + * Sets result. + * + * @param result the result + */ + public void setResult(String result) { + if (choice != null) { + if (result == null) { + this.result = resolveResult(); + } + } else { + this.result = result; + } } - ChoiceOrOther that = (ChoiceOrOther) obj; + private String resolveResult() { + return OTHER_ENUM_VALUE.equals(choice.name()) ? other : choice.name(); + } - if (choice != null ? !choice.equals(that.choice) : that.choice != null) { - return false; + /** + * Resolve enum. + * + * @param enumClass the enum class + */ + public void resolveEnum(Class enumClass) { + if (choice != null || result == null) { + return; + } + try { + choice = E.valueOf(enumClass, result); + } catch (IllegalArgumentException exception) { + try { + choice = E.valueOf(enumClass, OTHER_ENUM_VALUE); + } catch (IllegalArgumentException ex) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withId(CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID).withMessage(CHOICE_OR_OTHER_INVALID_ENUM_MSG) + .build()); + } + other = result; + } } - if (other != null ? !other.equals(that.other) : that.other != null) { - return false; + + @Override + public int hashCode() { + int result1 = choice != null ? choice.hashCode() : 0; + result1 = 31 * result1 + (other != null ? other.hashCode() : 0); + result1 = 31 * result1 + (result != null ? result.hashCode() : 0); + return result1; } - return result != null ? result.equals(that.result) : that.result == null; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + ChoiceOrOther that = (ChoiceOrOther) obj; + if (choice != null ? !choice.equals(that.choice) : that.choice != null) { + return false; + } + if (other != null ? !other.equals(that.other) : that.other != null) { + return false; + } + return result != null ? result.equals(that.result) : that.result == null; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementMetric.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementMetric.java index 23423dc241..331f8f7111 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementMetric.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementMetric.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; public enum EntitlementMetric { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java index 4d3c1d63a7..74df63fba7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -25,7 +24,10 @@ import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - +import java.util.Collection; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; @@ -35,377 +37,335 @@ import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.util.Collection; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - @Table(keyspace = "dox", name = "entitlement_pool") public class EntitlementPoolEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Entitlement Pool"; - - @PartitionKey - @Column(name = "vlm_id") - private String vendorLicenseModelId; - - @PartitionKey(value = 1) - @Frozen - private Version version; - - @ClusteringColumn - @Column(name = "ep_id") - private String id; - private String name; - private String description; - private EntitlementPoolType type; - - @Column(name = "threshold") - private Integer thresholdValue; - - @Column(name = "threshold_unit") - private ThresholdUnit thresholdUnit; - - private String increments; - - @Column(name = "operational_scope") - @Frozen - private MultiChoiceOrOther operationalScope; - - @Column(name = "ref_fg_ids") - private Set referencingFeatureGroups = new HashSet<>(); - - @Column(name = "version_uuid") - private String versionUuId; - - - private String startDate; - private String expiryDate; - - private Collection limits; - - //Defined and used only for License Artifcat XMLs - private String manufacturerReferenceNumber; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public EntitlementPoolEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new Entitlement pool entity. - * - * @param vlmId the vlm id - * @param version the version - * @param id the id - */ - public EntitlementPoolEntity(String vlmId, Version version, String id) { - this.vendorLicenseModelId = vlmId; - this.version = version; - this.id = id; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVendorLicenseModelId(); - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - @Override - public String getVersionUuId() { - return versionUuId; - } - - @Override - public void setVersionUuId(String uuId) { - versionUuId = uuId; - } - - public String getVendorLicenseModelId() { - return vendorLicenseModelId; - } - - public void setVendorLicenseModelId(String vendorLicenseModelId) { - this.vendorLicenseModelId = vendorLicenseModelId; - } - - public Set getReferencingFeatureGroups() { - return referencingFeatureGroups; - } - - public void setReferencingFeatureGroups(Set referencingFeatureGroups) { - this.referencingFeatureGroups = referencingFeatureGroups; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public EntitlementPoolType getType() { - return type; - } - - public void setType(EntitlementPoolType type) { - this.type = type; - } - - public Integer getThresholdValue() { - return thresholdValue; - } - - public void setThresholdValue(Integer thresholdValue) { - this.thresholdValue = thresholdValue; - } - - public ThresholdUnit getThresholdUnit() { - return thresholdUnit; - } - - public void setThresholdUnit(ThresholdUnit thresholdUnits) { - this.thresholdUnit = thresholdUnits; - } - - public String getIncrements() { - return increments; - } - - public void setIncrements(String increments) { - this.increments = increments; - } - - public MultiChoiceOrOther getOperationalScope() { - return operationalScope; - } - - public void setOperationalScope(MultiChoiceOrOther operationalScope) { - if (operationalScope != null) { - operationalScope.resolveEnum(OperationalScope.class); - } - this.operationalScope = operationalScope; - } - - /** - * Gets threshold for artifact. - * - * @return the threshold for artifact - */ - public ThresholdForXml getThresholdForArtifact() { - ThresholdForXml threshold = new ThresholdForXml(); - threshold.setUnit(getThresholdUnit() == null ? null : getThresholdUnit().name()); - threshold.setValue(getThresholdValue()); - return threshold; - } - - /** - * Gets version for artifact. - * - * @return version in format suitable for artifact - */ - public String getVersionForArtifact() { - return version.toString(); - } - - public String getStartDate() { - return startDate; - } - - public void setStartDate(String startDate) { - this.startDate = startDate; - } - - public String getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(String expiryDate) { - this.expiryDate = expiryDate; - } - - public Collection getLimits() { - return limits; - } - - public void setLimits(Collection limits) { - this.limits = limits; - } - - public LimitForXml getSPLimits() { - if (limits != null) { - Set hs = new HashSet<>(); - for (LimitEntity obj : limits) { - if (obj.getType().equals(LimitType.ServiceProvider)) { - LimitXml xmlObj = new LimitXml(); - xmlObj.setDescription(obj.getDescription()); - xmlObj.setMetric(obj.getMetric()); - xmlObj.setValues(obj.getValue()); - xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction( - obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); - xmlObj.setTime(obj.getTime()); - hs.add(xmlObj); + + private static final String ENTITY_TYPE = "Entitlement Pool"; + @PartitionKey + @Column(name = "vlm_id") + private String vendorLicenseModelId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "ep_id") + private String id; + private String name; + private String description; + private EntitlementPoolType type; + @Column(name = "threshold") + private Integer thresholdValue; + @Column(name = "threshold_unit") + private ThresholdUnit thresholdUnit; + private String increments; + @Column(name = "operational_scope") + @Frozen + private MultiChoiceOrOther operationalScope; + @Column(name = "ref_fg_ids") + private Set referencingFeatureGroups = new HashSet<>(); + @Column(name = "version_uuid") + private String versionUuId; + private String startDate; + private String expiryDate; + private Collection limits; + //Defined and used only for License Artifcat XMLs + private String manufacturerReferenceNumber; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public EntitlementPoolEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new Entitlement pool entity. + * + * @param vlmId the vlm id + * @param version the version + * @param id the id + */ + public EntitlementPoolEntity(String vlmId, Version version, String id) { + this.vendorLicenseModelId = vlmId; + this.version = version; + this.id = id; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVendorLicenseModelId(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + @Override + public String getVersionUuId() { + return versionUuId; + } + + @Override + public void setVersionUuId(String uuId) { + versionUuId = uuId; + } + + public String getVendorLicenseModelId() { + return vendorLicenseModelId; + } + + public void setVendorLicenseModelId(String vendorLicenseModelId) { + this.vendorLicenseModelId = vendorLicenseModelId; + } + + public Set getReferencingFeatureGroups() { + return referencingFeatureGroups; + } + + public void setReferencingFeatureGroups(Set referencingFeatureGroups) { + this.referencingFeatureGroups = referencingFeatureGroups; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public EntitlementPoolType getType() { + return type; + } + + public void setType(EntitlementPoolType type) { + this.type = type; + } + + public Integer getThresholdValue() { + return thresholdValue; + } + + public void setThresholdValue(Integer thresholdValue) { + this.thresholdValue = thresholdValue; + } + + public ThresholdUnit getThresholdUnit() { + return thresholdUnit; + } + + public void setThresholdUnit(ThresholdUnit thresholdUnits) { + this.thresholdUnit = thresholdUnits; + } + + public String getIncrements() { + return increments; + } + + public void setIncrements(String increments) { + this.increments = increments; + } + + public MultiChoiceOrOther getOperationalScope() { + return operationalScope; + } + + public void setOperationalScope(MultiChoiceOrOther operationalScope) { + if (operationalScope != null) { + operationalScope.resolveEnum(OperationalScope.class); + } + this.operationalScope = operationalScope; + } + + /** + * Gets threshold for artifact. + * + * @return the threshold for artifact + */ + public ThresholdForXml getThresholdForArtifact() { + ThresholdForXml threshold = new ThresholdForXml(); + threshold.setUnit(getThresholdUnit() == null ? null : getThresholdUnit().name()); + threshold.setValue(getThresholdValue()); + return threshold; + } + + /** + * Gets version for artifact. + * + * @return version in format suitable for artifact + */ + public String getVersionForArtifact() { + return version.toString(); + } + + public String getStartDate() { + return startDate; + } + + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getExpiryDate() { + return expiryDate; + } + + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } + + public Collection getLimits() { + return limits; + } + + public void setLimits(Collection limits) { + this.limits = limits; + } + + public LimitForXml getSPLimits() { + if (limits != null) { + Set hs = new HashSet<>(); + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.ServiceProvider)) { + LimitXml xmlObj = new LimitXml(); + xmlObj.setDescription(obj.getDescription()); + xmlObj.setMetric(obj.getMetric()); + xmlObj.setValues(obj.getValue()); + xmlObj.setUnit(obj.getUnit()); + xmlObj.setAggregationFunction(obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); + xmlObj.setTime(obj.getTime()); + hs.add(xmlObj); + } + } + LimitForXml spLimitForXml = new LimitForXml(); + spLimitForXml.setLimits(hs); + return spLimitForXml; + } + return null; + } + + public LimitForXml getVendorLimits() { + if (limits != null) { + Set hs = new HashSet<>(); + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.Vendor)) { + LimitXml xmlObj = new LimitXml(); + xmlObj.setDescription(obj.getDescription()); + xmlObj.setMetric(obj.getMetric()); + xmlObj.setValues(obj.getValue()); + xmlObj.setUnit(obj.getUnit()); + xmlObj.setAggregationFunction(obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); + xmlObj.setTime(obj.getTime()); + hs.add(xmlObj); + } + } + LimitForXml vendorLimitForXml = new LimitForXml(); + vendorLimitForXml.setLimits(hs); + return vendorLimitForXml; + } + return null; + } + + @Override + public int hashCode() { + return Objects.hash(vendorLicenseModelId, version, id, name, description, type, thresholdValue, thresholdUnit, increments, operationalScope, + referencingFeatureGroups, startDate, expiryDate); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; } - } - LimitForXml spLimitForXml = new LimitForXml(); - spLimitForXml.setLimits(hs); - return spLimitForXml; - } - - return null; - } - - public LimitForXml getVendorLimits() { - if (limits != null) { - Set hs = new HashSet<>(); - for (LimitEntity obj : limits) { - if (obj.getType().equals(LimitType.Vendor)) { - LimitXml xmlObj = new LimitXml(); - xmlObj.setDescription(obj.getDescription()); - xmlObj.setMetric(obj.getMetric()); - xmlObj.setValues(obj.getValue()); - xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction( - obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); - xmlObj.setTime(obj.getTime()); - hs.add(xmlObj); + if (obj == null || getClass() != obj.getClass()) { + return false; } - } - LimitForXml vendorLimitForXml = new LimitForXml(); - vendorLimitForXml.setLimits(hs); - return vendorLimitForXml; - } - - return null; - } - - - @Override - public int hashCode() { - return Objects - .hash(vendorLicenseModelId, version, id, name, description, type, thresholdValue, thresholdUnit, - increments, operationalScope, referencingFeatureGroups, startDate, expiryDate); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - EntitlementPoolEntity that = (EntitlementPoolEntity) obj; - return Objects.equals(that.thresholdValue, thresholdValue) - && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && type == that.type - && Objects.equals(thresholdUnit, that.thresholdUnit) - && Objects.equals(increments, that.increments) - && Objects.equals(that.operationalScope, operationalScope) - && Objects.equals(startDate, that.startDate) - && Objects.equals(expiryDate, that.expiryDate) - && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) - && Objects.equals(version, that.version); - } - - @Override - public String toString() { - return "EntitlementPoolEntity{" - + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' - + ", version=" + version - + ", id='" + id + '\'' - + ", name='" + name + '\'' - + ", description='" + description + '\'' - + ", type=" + type - + ", thresholdValue=" + thresholdValue - + ", thresholdUnit='" + thresholdUnit + '\'' - + ", increments='" + increments + '\'' - + ", operationalScope=" + operationalScope - + ", referencingFeatureGroups=" + referencingFeatureGroups - + ", version_uuid=" + versionUuId - + ", startDate=" + startDate - + ", expiryDate=" + expiryDate - + '}'; - } - - /** - * Gets operational scope for artifact. - * - * @return the operational scope for artifact - */ - public OperationalScopeForXml getOperationalScopeForArtifact() { - OperationalScopeForXml obj = new OperationalScopeForXml(); - if (operationalScope != null) { - if (operationalScope.getResults().size() > 0) { - obj.setValue(operationalScope.getResults()); - } - } - return obj; - } - - //Defined and used only for License Artifcat XMLs - public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { - this.manufacturerReferenceNumber = manufacturerReferenceNumber; - } - - public String getManufacturerReferenceNumber() { - return manufacturerReferenceNumber; - } - - public String getIsoFormatStartDate() { - String isoFormatStartDate = null; - if (!StringUtils.isEmpty(startDate)) { - isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); - } - return isoFormatStartDate; - } - - - public String getIsoFormatExpiryDate() { - String isoFormatExpDate = null; - if (!StringUtils.isEmpty(expiryDate)) { - isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); - } - return isoFormatExpDate; - } + EntitlementPoolEntity that = (EntitlementPoolEntity) obj; + return Objects.equals(that.thresholdValue, thresholdValue) && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) && Objects + .equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) && type == that.type && Objects + .equals(thresholdUnit, that.thresholdUnit) && Objects.equals(increments, that.increments) && Objects + .equals(that.operationalScope, operationalScope) && Objects.equals(startDate, that.startDate) && Objects + .equals(expiryDate, that.expiryDate) && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) && Objects + .equals(version, that.version); + } + + @Override + public String toString() { + return "EntitlementPoolEntity{" + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' + ", version=" + version + ", id='" + id + '\'' + + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type=" + type + ", thresholdValue=" + thresholdValue + + ", thresholdUnit='" + thresholdUnit + '\'' + ", increments='" + increments + '\'' + ", operationalScope=" + operationalScope + + ", referencingFeatureGroups=" + referencingFeatureGroups + ", version_uuid=" + versionUuId + ", startDate=" + startDate + + ", expiryDate=" + expiryDate + '}'; + } + + /** + * Gets operational scope for artifact. + * + * @return the operational scope for artifact + */ + public OperationalScopeForXml getOperationalScopeForArtifact() { + OperationalScopeForXml obj = new OperationalScopeForXml(); + if (operationalScope != null) { + if (operationalScope.getResults().size() > 0) { + obj.setValue(operationalScope.getResults()); + } + } + return obj; + } + + public String getManufacturerReferenceNumber() { + return manufacturerReferenceNumber; + } + + //Defined and used only for License Artifcat XMLs + public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { + this.manufacturerReferenceNumber = manufacturerReferenceNumber; + } + + public String getIsoFormatStartDate() { + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + } + return isoFormatStartDate; + } + + public String getIsoFormatExpiryDate() { + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + } + return isoFormatExpDate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolType.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolType.java index 1a851a54ac..f75351ff41 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolType.java @@ -17,15 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; public enum EntitlementPoolType { - Universal, - Unique, - One_Time; + Universal, Unique, One_Time; public static EntitlementPoolType permissiveValueOf(String name) { return name == null ? Universal : EntitlementPoolType.valueOf(name); } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementTime.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementTime.java index 78576d1e7d..91d95953a8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementTime.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementTime.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; public enum EntitlementTime { //TODO MetricTime ? ask Segev... - Hour, - Day, - Month, - Quarter, - Year, - Other; + Hour, Day, Month, Quarter, Year, Other; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupEntity.java index d19d780c7b..6fed37bf7b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -25,198 +24,181 @@ import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - import java.util.HashSet; import java.util.Objects; import java.util.Set; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionableEntity; @Table(name = "feature_group", keyspace = "dox") public class FeatureGroupEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Feature Group"; - - @PartitionKey - @Column(name = "vlm_id") - private String vendorLicenseModelId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "fg_id") - private String id; - private String name; - private String description; - @Column(name = "part_num") - private String partNumber; - @Column(name = "manufacturer_ref_num") - private String manufacturerReferenceNumber; - @Column(name = "lkg_ids") - private Set licenseKeyGroupIds = new HashSet<>(); - @Column(name = "ep_ids") - private Set entitlementPoolIds = new HashSet<>(); - @Column(name = "ref_la_ids") - private Set referencingLicenseAgreements = new HashSet<>(); - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public FeatureGroupEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new Feature group entity. - * - * @param vendorLicenseModelId the vendor license model id - * @param version the version - * @param id the id - */ - public FeatureGroupEntity(String vendorLicenseModelId, Version version, String id) { - this.vendorLicenseModelId = vendorLicenseModelId; - this.version = version; - this.id = id; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVendorLicenseModelId(); - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public String getVendorLicenseModelId() { - return vendorLicenseModelId; - } - - public void setVendorLicenseModelId(String vendorLicenseModelId) { - this.vendorLicenseModelId = vendorLicenseModelId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getPartNumber() { - return partNumber; - } - - public void setPartNumber(String partNumber) { - this.partNumber = partNumber; - } - - public String getManufacturerReferenceNumber() { - return manufacturerReferenceNumber; - } - - public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { - this.manufacturerReferenceNumber = manufacturerReferenceNumber; - } - - public Set getLicenseKeyGroupIds() { - return licenseKeyGroupIds; - } - - public void setLicenseKeyGroupIds(Set licenseKeyGroupIds) { - this.licenseKeyGroupIds = licenseKeyGroupIds; - } - - public Set getEntitlementPoolIds() { - return entitlementPoolIds; - } - - public void setEntitlementPoolIds(Set entitlementPoolIds) { - this.entitlementPoolIds = entitlementPoolIds; - } - - public Set getReferencingLicenseAgreements() { - return referencingLicenseAgreements; - } - - public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { - this.referencingLicenseAgreements = referencingLicenseAgreements; - } - - @Override - public int hashCode() { - return Objects - .hash(vendorLicenseModelId, version, id, name, description, partNumber, - manufacturerReferenceNumber, licenseKeyGroupIds, entitlementPoolIds, - referencingLicenseAgreements); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - FeatureGroupEntity that = (FeatureGroupEntity) obj; - return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(version, that.version) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && Objects.equals(partNumber, that.partNumber) - && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) - && Objects.equals(licenseKeyGroupIds, that.licenseKeyGroupIds) - && Objects.equals(entitlementPoolIds, that.entitlementPoolIds) - && Objects.equals(referencingLicenseAgreements, that.referencingLicenseAgreements); - } - - @Override - public String toString() { - return "FeatureGroupEntity{" - + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' - + ", version=" + version - + ", id='" + id + '\'' - + ", name='" + name + '\'' - + ", description='" + description + '\'' - + ", partNumber='" + partNumber + '\'' - + ", manufacturerReferenceNumber='" + manufacturerReferenceNumber + '\'' - + ", licenseKeyGroupIds=" + licenseKeyGroupIds - + ", entitlementPoolIds=" + entitlementPoolIds - + ", referencingLicenseAgreements=" + referencingLicenseAgreements - + '}'; - } + + private static final String ENTITY_TYPE = "Feature Group"; + @PartitionKey + @Column(name = "vlm_id") + private String vendorLicenseModelId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "fg_id") + private String id; + private String name; + private String description; + @Column(name = "part_num") + private String partNumber; + @Column(name = "manufacturer_ref_num") + private String manufacturerReferenceNumber; + @Column(name = "lkg_ids") + private Set licenseKeyGroupIds = new HashSet<>(); + @Column(name = "ep_ids") + private Set entitlementPoolIds = new HashSet<>(); + @Column(name = "ref_la_ids") + private Set referencingLicenseAgreements = new HashSet<>(); + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public FeatureGroupEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new Feature group entity. + * + * @param vendorLicenseModelId the vendor license model id + * @param version the version + * @param id the id + */ + public FeatureGroupEntity(String vendorLicenseModelId, Version version, String id) { + this.vendorLicenseModelId = vendorLicenseModelId; + this.version = version; + this.id = id; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVendorLicenseModelId(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public String getVendorLicenseModelId() { + return vendorLicenseModelId; + } + + public void setVendorLicenseModelId(String vendorLicenseModelId) { + this.vendorLicenseModelId = vendorLicenseModelId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getPartNumber() { + return partNumber; + } + + public void setPartNumber(String partNumber) { + this.partNumber = partNumber; + } + + public String getManufacturerReferenceNumber() { + return manufacturerReferenceNumber; + } + + public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { + this.manufacturerReferenceNumber = manufacturerReferenceNumber; + } + + public Set getLicenseKeyGroupIds() { + return licenseKeyGroupIds; + } + + public void setLicenseKeyGroupIds(Set licenseKeyGroupIds) { + this.licenseKeyGroupIds = licenseKeyGroupIds; + } + + public Set getEntitlementPoolIds() { + return entitlementPoolIds; + } + + public void setEntitlementPoolIds(Set entitlementPoolIds) { + this.entitlementPoolIds = entitlementPoolIds; + } + + public Set getReferencingLicenseAgreements() { + return referencingLicenseAgreements; + } + + public void setReferencingLicenseAgreements(Set referencingLicenseAgreements) { + this.referencingLicenseAgreements = referencingLicenseAgreements; + } + + @Override + public int hashCode() { + return Objects.hash(vendorLicenseModelId, version, id, name, description, partNumber, manufacturerReferenceNumber, licenseKeyGroupIds, + entitlementPoolIds, referencingLicenseAgreements); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + FeatureGroupEntity that = (FeatureGroupEntity) obj; + return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) && Objects.equals(version, that.version) && Objects.equals(id, that.id) + && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(partNumber, that.partNumber) + && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) && Objects + .equals(licenseKeyGroupIds, that.licenseKeyGroupIds) && Objects.equals(entitlementPoolIds, that.entitlementPoolIds) && Objects + .equals(referencingLicenseAgreements, that.referencingLicenseAgreements); + } + + @Override + public String toString() { + return "FeatureGroupEntity{" + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' + ", version=" + version + ", id='" + id + '\'' + + ", name='" + name + '\'' + ", description='" + description + '\'' + ", partNumber='" + partNumber + '\'' + + ", manufacturerReferenceNumber='" + manufacturerReferenceNumber + '\'' + ", licenseKeyGroupIds=" + licenseKeyGroupIds + + ", entitlementPoolIds=" + entitlementPoolIds + ", referencingLicenseAgreements=" + referencingLicenseAgreements + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupModel.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupModel.java index 7e4ba8051e..93b953c52b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupModel.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/FeatureGroupModel.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,62 +17,59 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import java.util.HashSet; import java.util.Set; public class FeatureGroupModel { - private FeatureGroupEntity featureGroup; - private Set entitlementPools = new HashSet<>(); - - private Set licenseKeyGroups = new HashSet<>(); - - public FeatureGroupEntity getFeatureGroup() { - return featureGroup; - } - public void setFeatureGroup(FeatureGroupEntity featureGroup) { - this.featureGroup = featureGroup; - } + private FeatureGroupEntity featureGroup; + private Set entitlementPools = new HashSet<>(); + private Set licenseKeyGroups = new HashSet<>(); - public Set getEntitlementPools() { - return entitlementPools; - } + public FeatureGroupEntity getFeatureGroup() { + return featureGroup; + } - public void setEntitlementPools(Set entitlementPools) { - this.entitlementPools = entitlementPools; - } + public void setFeatureGroup(FeatureGroupEntity featureGroup) { + this.featureGroup = featureGroup; + } - public Set getLicenseKeyGroups() { - return licenseKeyGroups; - } + public Set getEntitlementPools() { + return entitlementPools; + } - public void setLicenseKeyGroups(Set licenseKeyGroups) { - this.licenseKeyGroups = licenseKeyGroups; - } + public void setEntitlementPools(Set entitlementPools) { + this.entitlementPools = entitlementPools; + } - //for XML Artifact - public String getEntityName() { - return featureGroup.getName(); - } + public Set getLicenseKeyGroups() { + return licenseKeyGroups; + } - public String getEntityDesc() { - return featureGroup.getDescription(); - } + public void setLicenseKeyGroups(Set licenseKeyGroups) { + this.licenseKeyGroups = licenseKeyGroups; + } - public String getEntityId() { - return featureGroup.getId(); - } + //for XML Artifact + public String getEntityName() { + return featureGroup.getName(); + } - public String getEntityPartNumber() { - return featureGroup.getPartNumber(); - } + public String getEntityDesc() { + return featureGroup.getDescription(); + } - public String getEntityManufacturerReferenceNumber(){ - return featureGroup.getManufacturerReferenceNumber(); - } + public String getEntityId() { + return featureGroup.getId(); + } + public String getEntityPartNumber() { + return featureGroup.getPartNumber(); + } + public String getEntityManufacturerReferenceNumber() { + return featureGroup.getManufacturerReferenceNumber(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementEntity.java index 43017e7757..1646ba9b61 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -25,165 +24,152 @@ import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - import java.util.HashSet; import java.util.Objects; import java.util.Set; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionableEntity; @Table(keyspace = "dox", name = "license_agreement") public class LicenseAgreementEntity implements VersionableEntity { - public static final String ENTITY_TYPE = "License Agreement"; - - @PartitionKey(value = 0) - @Column(name = "vlm_id") - private String vendorLicenseModelId; - - @PartitionKey(value = 1) - @Frozen - private Version version; - - @ClusteringColumn - @Column(name = "la_id") - private String id; - private String name; - private String description; - - @Column(name = "lic_term") - @Frozen - private ChoiceOrOther licenseTerm; - - @Column(name = "req_const") - private String requirementsAndConstrains; - - @Column(name = "fg_ids") - private Set featureGroupIds = new HashSet<>(); - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public LicenseAgreementEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new License agreement entity. - * - * @param vlmId the vlm id - * @param version the version - * @param id the id - */ - public LicenseAgreementEntity(String vlmId, Version version, String id) { - this.vendorLicenseModelId = vlmId; - this.id = id; - this.version = version; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVendorLicenseModelId(); - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public String getVendorLicenseModelId() { - return vendorLicenseModelId; - } - - public void setVendorLicenseModelId(String vendorLicenseModelId) { - this.vendorLicenseModelId = vendorLicenseModelId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ChoiceOrOther getLicenseTerm() { - return licenseTerm; - } - - public void setLicenseTerm(ChoiceOrOther licenseTerm) { - licenseTerm.resolveEnum(LicenseTerm.class); - this.licenseTerm = licenseTerm; - } - - public String getRequirementsAndConstrains() { - return requirementsAndConstrains; - } - - public void setRequirementsAndConstrains(String requirementsAndConstrains) { - this.requirementsAndConstrains = requirementsAndConstrains; - } - - public Set getFeatureGroupIds() { - return featureGroupIds; - } - - public void setFeatureGroupIds(Set featureGroupIds) { - this.featureGroupIds = featureGroupIds; - } - - @Override - public int hashCode() { - return Objects.hash(vendorLicenseModelId, version, id, name, description, licenseTerm, - requirementsAndConstrains, featureGroupIds); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - LicenseAgreementEntity that = (LicenseAgreementEntity) obj; - return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(version, that.version) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && Objects.equals(licenseTerm, that.licenseTerm) - && Objects.equals(requirementsAndConstrains, that.requirementsAndConstrains) - && Objects.equals(featureGroupIds, that.featureGroupIds); - } + + public static final String ENTITY_TYPE = "License Agreement"; + @PartitionKey(value = 0) + @Column(name = "vlm_id") + private String vendorLicenseModelId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "la_id") + private String id; + private String name; + private String description; + @Column(name = "lic_term") + @Frozen + private ChoiceOrOther licenseTerm; + @Column(name = "req_const") + private String requirementsAndConstrains; + @Column(name = "fg_ids") + private Set featureGroupIds = new HashSet<>(); + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public LicenseAgreementEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new License agreement entity. + * + * @param vlmId the vlm id + * @param version the version + * @param id the id + */ + public LicenseAgreementEntity(String vlmId, Version version, String id) { + this.vendorLicenseModelId = vlmId; + this.id = id; + this.version = version; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVendorLicenseModelId(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public String getVendorLicenseModelId() { + return vendorLicenseModelId; + } + + public void setVendorLicenseModelId(String vendorLicenseModelId) { + this.vendorLicenseModelId = vendorLicenseModelId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public ChoiceOrOther getLicenseTerm() { + return licenseTerm; + } + + public void setLicenseTerm(ChoiceOrOther licenseTerm) { + licenseTerm.resolveEnum(LicenseTerm.class); + this.licenseTerm = licenseTerm; + } + + public String getRequirementsAndConstrains() { + return requirementsAndConstrains; + } + + public void setRequirementsAndConstrains(String requirementsAndConstrains) { + this.requirementsAndConstrains = requirementsAndConstrains; + } + + public Set getFeatureGroupIds() { + return featureGroupIds; + } + + public void setFeatureGroupIds(Set featureGroupIds) { + this.featureGroupIds = featureGroupIds; + } + + @Override + public int hashCode() { + return Objects.hash(vendorLicenseModelId, version, id, name, description, licenseTerm, requirementsAndConstrains, featureGroupIds); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + LicenseAgreementEntity that = (LicenseAgreementEntity) obj; + return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) && Objects.equals(version, that.version) && Objects.equals(id, that.id) + && Objects.equals(name, that.name) && Objects.equals(description, that.description) && Objects.equals(licenseTerm, that.licenseTerm) + && Objects.equals(requirementsAndConstrains, that.requirementsAndConstrains) && Objects.equals(featureGroupIds, that.featureGroupIds); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementModel.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementModel.java index 1e65f70cc0..f1923701fd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementModel.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseAgreementModel.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,29 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import java.util.HashSet; import java.util.Set; public class LicenseAgreementModel { - private LicenseAgreementEntity licenseAgreement; - private Set featureGroups = new HashSet<>(); - public LicenseAgreementEntity getLicenseAgreement() { - return licenseAgreement; - } + private LicenseAgreementEntity licenseAgreement; + private Set featureGroups = new HashSet<>(); + + public LicenseAgreementEntity getLicenseAgreement() { + return licenseAgreement; + } - public void setLicenseAgreement(LicenseAgreementEntity licenseAgreement) { - this.licenseAgreement = licenseAgreement; - } + public void setLicenseAgreement(LicenseAgreementEntity licenseAgreement) { + this.licenseAgreement = licenseAgreement; + } - public Set getFeatureGroups() { - return featureGroups; - } + public Set getFeatureGroups() { + return featureGroups; + } - public void setFeatureGroups(Set featureGroups) { - this.featureGroups = featureGroups; - } + public void setFeatureGroups(Set featureGroups) { + this.featureGroups = featureGroups; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java index c84df9ca95..57849a890a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -25,379 +24,354 @@ import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; -import org.openecomp.sdc.vendorlicense.dao.types.xml.*; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LicenseKeyTypeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionableEntity; @Table(keyspace = "dox", name = "license_key_group") public class LicenseKeyGroupEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "License Key Group"; - - @PartitionKey - @Column(name = "vlm_id") - private String vendorLicenseModelId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "lkg_id") - private String id; - private String name; - private String description; - private LicenseKeyType type; - @Column(name = "operational_scope") - @Frozen - private MultiChoiceOrOther operationalScope; - @Column(name = "ref_fg_ids") - private Set referencingFeatureGroups = new HashSet<>(); - @Column(name = "version_uuid") - private String versionUuId; - private Integer thresholdValue; - private ThresholdUnit thresholdUnits; - private String increments; - - private Collection limits; - private String startDate; - private String expiryDate; - - //Defined and used only for License Artifcat XMLs - private String manufacturerReferenceNumber; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public LicenseKeyGroupEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new License key group entity. - * - * @param vendorLicenseModelId the vendor license model id - * @param version the version - * @param id the id - */ - public LicenseKeyGroupEntity(String vendorLicenseModelId, Version version, String id) { - this.vendorLicenseModelId = vendorLicenseModelId; - this.version = version; - this.id = id; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVendorLicenseModelId(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - @Override - public String getVersionUuId() { - return versionUuId; - } - - @Override - public void setVersionUuId(String uuId) { - versionUuId = uuId; - } - - public String getVendorLicenseModelId() { - return vendorLicenseModelId; - } - - public void setVendorLicenseModelId(String vendorLicenseModelId) { - this.vendorLicenseModelId = vendorLicenseModelId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public LicenseKeyType getType() { - return type; - } - - public void setType(LicenseKeyType type) { - this.type = type; - } - - public MultiChoiceOrOther getOperationalScope() { - return operationalScope; - } - - public void setOperationalScope(MultiChoiceOrOther operationalScope) { - if (operationalScope != null) { - operationalScope.resolveEnum(OperationalScope.class); - } - this.operationalScope = operationalScope; - } - - public Set getReferencingFeatureGroups() { - return referencingFeatureGroups; - } - - public void setReferencingFeatureGroups(Set referencingFeatureGroups) { - this.referencingFeatureGroups = referencingFeatureGroups; - } - - public Integer getThresholdValue() { - return thresholdValue; - } - - public void setThresholdValue(Integer thresholdValue) { - this.thresholdValue = thresholdValue; - } - - public ThresholdUnit getThresholdUnits() { - return thresholdUnits; - } - - public void setThresholdUnits(ThresholdUnit thresholdUnit) { - this.thresholdUnits = thresholdUnit; - } - - public String getIncrements() { - return increments; - } - - public void setIncrements(String increments) { - this.increments = increments; - } - - public ThresholdForXml getThresholdForArtifact() { - ThresholdForXml threshold = new ThresholdForXml(); - threshold.setUnit(getThresholdUnits() == null ? null : getThresholdUnits().name()); - threshold.setValue(getThresholdValue()); - return threshold; - } - - public Collection getLimits() { - return limits; - } - - public void setLimits(Collection limits) { - this.limits = limits; - } - - public LimitForXml getSPLimits() { - if (limits != null) { - Set hs = new HashSet<>(); - for (LimitEntity obj : limits) { - if (obj.getType().equals(LimitType.ServiceProvider)) { - LimitXml xmlObj = new LimitXml(); - xmlObj.setDescription(obj.getDescription()); - xmlObj.setMetric(obj.getMetric()); - xmlObj.setValues(obj.getValue()); - xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction( - obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); - xmlObj.setTime(obj.getTime()); - hs.add(xmlObj); + + private static final String ENTITY_TYPE = "License Key Group"; + @PartitionKey + @Column(name = "vlm_id") + private String vendorLicenseModelId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "lkg_id") + private String id; + private String name; + private String description; + private LicenseKeyType type; + @Column(name = "operational_scope") + @Frozen + private MultiChoiceOrOther operationalScope; + @Column(name = "ref_fg_ids") + private Set referencingFeatureGroups = new HashSet<>(); + @Column(name = "version_uuid") + private String versionUuId; + private Integer thresholdValue; + private ThresholdUnit thresholdUnits; + private String increments; + private Collection limits; + private String startDate; + private String expiryDate; + //Defined and used only for License Artifcat XMLs + private String manufacturerReferenceNumber; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public LicenseKeyGroupEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new License key group entity. + * + * @param vendorLicenseModelId the vendor license model id + * @param version the version + * @param id the id + */ + public LicenseKeyGroupEntity(String vendorLicenseModelId, Version version, String id) { + this.vendorLicenseModelId = vendorLicenseModelId; + this.version = version; + this.id = id; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVendorLicenseModelId(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Version getVersion() { + return version; + } + + public void setVersion(Version version) { + this.version = version; + } + + @Override + public String getVersionUuId() { + return versionUuId; + } + + @Override + public void setVersionUuId(String uuId) { + versionUuId = uuId; + } + + public String getVendorLicenseModelId() { + return vendorLicenseModelId; + } + + public void setVendorLicenseModelId(String vendorLicenseModelId) { + this.vendorLicenseModelId = vendorLicenseModelId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public LicenseKeyType getType() { + return type; + } + + public void setType(LicenseKeyType type) { + this.type = type; + } + + public MultiChoiceOrOther getOperationalScope() { + return operationalScope; + } + + public void setOperationalScope(MultiChoiceOrOther operationalScope) { + if (operationalScope != null) { + operationalScope.resolveEnum(OperationalScope.class); + } + this.operationalScope = operationalScope; + } + + public Set getReferencingFeatureGroups() { + return referencingFeatureGroups; + } + + public void setReferencingFeatureGroups(Set referencingFeatureGroups) { + this.referencingFeatureGroups = referencingFeatureGroups; + } + + public Integer getThresholdValue() { + return thresholdValue; + } + + public void setThresholdValue(Integer thresholdValue) { + this.thresholdValue = thresholdValue; + } + + public ThresholdUnit getThresholdUnits() { + return thresholdUnits; + } + + public void setThresholdUnits(ThresholdUnit thresholdUnit) { + this.thresholdUnits = thresholdUnit; + } + + public String getIncrements() { + return increments; + } + + public void setIncrements(String increments) { + this.increments = increments; + } + + public ThresholdForXml getThresholdForArtifact() { + ThresholdForXml threshold = new ThresholdForXml(); + threshold.setUnit(getThresholdUnits() == null ? null : getThresholdUnits().name()); + threshold.setValue(getThresholdValue()); + return threshold; + } + + public Collection getLimits() { + return limits; + } + + public void setLimits(Collection limits) { + this.limits = limits; + } + + public LimitForXml getSPLimits() { + if (limits != null) { + Set hs = new HashSet<>(); + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.ServiceProvider)) { + LimitXml xmlObj = new LimitXml(); + xmlObj.setDescription(obj.getDescription()); + xmlObj.setMetric(obj.getMetric()); + xmlObj.setValues(obj.getValue()); + xmlObj.setUnit(obj.getUnit()); + xmlObj.setAggregationFunction(obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); + xmlObj.setTime(obj.getTime()); + hs.add(xmlObj); + } + } + LimitForXml spLimitForXml = new LimitForXml(); + spLimitForXml.setLimits(hs); + return spLimitForXml; } - } - LimitForXml spLimitForXml = new LimitForXml(); - spLimitForXml.setLimits(hs); - return spLimitForXml; - } - - return null; - } - - public LimitForXml getVendorLimits() { - if (limits != null) { - Set hs = new HashSet<>(); - for (LimitEntity obj : limits) { - if (obj.getType().equals(LimitType.Vendor)) { - LimitXml xmlObj = new LimitXml(); - xmlObj.setDescription(obj.getDescription()); - xmlObj.setMetric(obj.getMetric()); - xmlObj.setValues(obj.getValue()); - xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction( - obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); - xmlObj.setTime(obj.getTime()); - hs.add(xmlObj); + return null; + } + + public LimitForXml getVendorLimits() { + if (limits != null) { + Set hs = new HashSet<>(); + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.Vendor)) { + LimitXml xmlObj = new LimitXml(); + xmlObj.setDescription(obj.getDescription()); + xmlObj.setMetric(obj.getMetric()); + xmlObj.setValues(obj.getValue()); + xmlObj.setUnit(obj.getUnit()); + xmlObj.setAggregationFunction(obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); + xmlObj.setTime(obj.getTime()); + hs.add(xmlObj); + } + } + LimitForXml vendorLimitForXml = new LimitForXml(); + vendorLimitForXml.setLimits(hs); + return vendorLimitForXml; } - } - LimitForXml vendorLimitForXml = new LimitForXml(); - vendorLimitForXml.setLimits(hs); - return vendorLimitForXml; - } - - return null; - } - - public String getStartDate() { - return startDate; - } - - public void setStartDate(String startDate) { - this.startDate = startDate; - } - - public String getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(String expiryDate) { - this.expiryDate = expiryDate; - } - - @Override - public int hashCode() { - return Objects - .hash(vendorLicenseModelId, version, id, name, description, type, operationalScope, - referencingFeatureGroups, startDate, expiryDate, - thresholdValue, thresholdUnits, increments); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - LicenseKeyGroupEntity that = (LicenseKeyGroupEntity) obj; - return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(version, that.version) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && type == that.type - && Objects.equals(that.operationalScope, operationalScope) - && Objects.equals(startDate, that.startDate) - && Objects.equals(expiryDate, that.expiryDate) - && Objects.equals(thresholdValue, that.thresholdValue) - && Objects.equals(thresholdUnits, that.thresholdUnits) - && Objects.equals(increments, that.increments) - && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber); - } - - @Override - public String toString() { - return "LicenseKeyGroupEntity{" + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' - + ", version=" + version - + ", id='" + id + '\'' - + ", name='" + name + '\'' - + ", description='" + description + '\'' - + ", type=" + type - + ", operationalScope=" + operationalScope - + ", referencingFeatureGroups=" + referencingFeatureGroups - + ", versionUuId='" + versionUuId + '\'' - + ", startDate=" + startDate - + ", expiryDate=" + expiryDate - + ", thresholdValue='" + thresholdValue + '\'' - + ", thresholdUnits='" + thresholdUnits + '\'' - + ", increments='" + increments + '\'' - + '}'; - } - - /** - * Gets operational scope for artifact. - * - * @return the operational scope for artifact - */ - public OperationalScopeForXml getOperationalScopeForArtifact() { - OperationalScopeForXml obj = new OperationalScopeForXml(); - if (operationalScope != null) { - if (operationalScope.getResults().size() > 0) { - obj.setValue(operationalScope.getResults()); - } - } - return obj; - } - - /** - * Gets version for artifact. - * - * @return version in format suitable for artifact - */ - public String getVersionForArtifact() { - return version.toString(); - } - - /** - * Gets type for artifact. - * - * @return the type for artifact - */ - public LicenseKeyTypeForXml getTypeForArtifact() { - LicenseKeyTypeForXml typeXml = new LicenseKeyTypeForXml(); - if (type != null) { - typeXml.setValue(type.toString()); - } else { - typeXml.setValue(null); - } - return typeXml; - } - - //Defined and used only for License Artifcat XMLs - public String getManufacturerReferenceNumber() { - return manufacturerReferenceNumber; - } - - public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { - this.manufacturerReferenceNumber = manufacturerReferenceNumber; - } - - public String getIsoFormatStartDate() { - String isoFormatStartDate = null; - if (!StringUtils.isEmpty(startDate)) { - isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); - } - return isoFormatStartDate; - } - - - public String getIsoFormatExpiryDate() { - String isoFormatExpDate = null; - if (!StringUtils.isEmpty(expiryDate)) { - isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); - } - return isoFormatExpDate; - } + return null; + } + + public String getStartDate() { + return startDate; + } + public void setStartDate(String startDate) { + this.startDate = startDate; + } + + public String getExpiryDate() { + return expiryDate; + } + public void setExpiryDate(String expiryDate) { + this.expiryDate = expiryDate; + } + + @Override + public int hashCode() { + return Objects + .hash(vendorLicenseModelId, version, id, name, description, type, operationalScope, referencingFeatureGroups, startDate, expiryDate, + thresholdValue, thresholdUnits, increments); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + LicenseKeyGroupEntity that = (LicenseKeyGroupEntity) obj; + return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) && Objects.equals(version, that.version) && Objects.equals(id, that.id) + && Objects.equals(name, that.name) && Objects.equals(description, that.description) && type == that.type && Objects + .equals(that.operationalScope, operationalScope) && Objects.equals(startDate, that.startDate) && Objects + .equals(expiryDate, that.expiryDate) && Objects.equals(thresholdValue, that.thresholdValue) && Objects + .equals(thresholdUnits, that.thresholdUnits) && Objects.equals(increments, that.increments) && Objects + .equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber); + } + + @Override + public String toString() { + return "LicenseKeyGroupEntity{" + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' + ", version=" + version + ", id='" + id + '\'' + + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type=" + type + ", operationalScope=" + operationalScope + + ", referencingFeatureGroups=" + referencingFeatureGroups + ", versionUuId='" + versionUuId + '\'' + ", startDate=" + startDate + + ", expiryDate=" + expiryDate + ", thresholdValue='" + thresholdValue + '\'' + ", thresholdUnits='" + thresholdUnits + '\'' + + ", increments='" + increments + '\'' + '}'; + } + + /** + * Gets operational scope for artifact. + * + * @return the operational scope for artifact + */ + public OperationalScopeForXml getOperationalScopeForArtifact() { + OperationalScopeForXml obj = new OperationalScopeForXml(); + if (operationalScope != null) { + if (operationalScope.getResults().size() > 0) { + obj.setValue(operationalScope.getResults()); + } + } + return obj; + } + + /** + * Gets version for artifact. + * + * @return version in format suitable for artifact + */ + public String getVersionForArtifact() { + return version.toString(); + } + + /** + * Gets type for artifact. + * + * @return the type for artifact + */ + public LicenseKeyTypeForXml getTypeForArtifact() { + LicenseKeyTypeForXml typeXml = new LicenseKeyTypeForXml(); + if (type != null) { + typeXml.setValue(type.toString()); + } else { + typeXml.setValue(null); + } + return typeXml; + } + + //Defined and used only for License Artifcat XMLs + public String getManufacturerReferenceNumber() { + return manufacturerReferenceNumber; + } + + public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { + this.manufacturerReferenceNumber = manufacturerReferenceNumber; + } + + public String getIsoFormatStartDate() { + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + } + return isoFormatStartDate; + } + + public String getIsoFormatExpiryDate() { + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + } + return isoFormatExpDate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyType.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyType.java index 35e6f217e8..4046d209f4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; -public enum LicenseKeyType { - Universal, - Unique, - One_Time; -} +public enum LicenseKeyType {Universal, Unique, One_Time;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseTerm.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseTerm.java index b8a7f9d09b..0374f7616b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseTerm.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseTerm.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; -public enum LicenseTerm { - Fixed_Term, - Perpetual, - Unlimited, - Other; -} +public enum LicenseTerm {Fixed_Term, Perpetual, Unlimited, Other;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java index fb9ea5a763..c4b169b3d3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java @@ -19,207 +19,184 @@ */ package org.openecomp.sdc.vendorlicense.dao.types; +import java.util.Objects; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.util.Objects; - public class LimitEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Limit"; - - private String id; - private String vendorLicenseModelId; - private String epLkgId; - private String name; - private LimitType type; - private String description; - private String metric; - private Version version; - private String value; - private String unit; - private AggregationFunction aggregationFunction; - private String time; - //Defined and used only to find parent(EP/LKG) of Limit. Not to be persisted in DB and License - // Xmls - private String parent; - - public LimitEntity() { - } - - public LimitEntity(String vlmId, Version version, String epLkgId, String id) { - this.vendorLicenseModelId = vlmId; - this.version = version; - this.epLkgId = epLkgId; - this.id = id; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public AggregationFunction getAggregationFunction() { - return aggregationFunction; - } - - public void setAggregationFunction( - AggregationFunction aggregationFunction) { - this.aggregationFunction = aggregationFunction; - } - - public String getTime() { - return time; - } - - public void setTime(String time) { - this.time = time; - } - - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVendorLicenseModelId(); - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - public String getEpLkgId() { - return epLkgId; - } - - public void setEpLkgId(String epLkgId) { - this.epLkgId = epLkgId; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public String getVendorLicenseModelId() { - return vendorLicenseModelId; - } - - public void setVendorLicenseModelId(String vendorLicenseModelId) { - this.vendorLicenseModelId = vendorLicenseModelId; - } - - public LimitType getType() { - return type; - } - - public void setType(LimitType type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getMetric() { - return metric; - } - - public void setMetric(String metric) { - this.metric = metric; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - //Defined and used only to find parent(EP/LKG) of Limit. Not to be persisted in DB and License - // Xmls - public String getParent() { - return parent; - } - - public void setParent(String parent) { - this.parent = parent; - } - - @Override - public int hashCode() { - return Objects.hash(vendorLicenseModelId, version, epLkgId, id, name, description, type, - metric, unit, time, aggregationFunction, value); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - LimitEntity that = (LimitEntity) obj; - return Objects.equals(that.unit, unit) - && Objects.equals(that.value, value) - && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(epLkgId, that.epLkgId) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && Objects.equals(type, that.type) - && Objects.equals(metric, that.metric) - && Objects.equals(aggregationFunction, that.aggregationFunction); - - } - - @Override - public String toString() { - return "LimitEntity{" - + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' - + ", version=" + version - + ", epLkgId=" + epLkgId - + ", id='" + id + '\'' - + ", name='" + name + '\'' - + ", description='" + description + '\'' - + ", type=" + type - + ", metric=" + metric - + ", value='" + value + '\'' - + ", unit='" + unit + '\'' - + ", aggregationFunction=" + aggregationFunction - + ", time=" + time - - + '}'; - } + private static final String ENTITY_TYPE = "Limit"; + private String id; + private String vendorLicenseModelId; + private String epLkgId; + private String name; + private LimitType type; + private String description; + private String metric; + private Version version; + private String value; + private String unit; + private AggregationFunction aggregationFunction; + private String time; + //Defined and used only to find parent(EP/LKG) of Limit. Not to be persisted in DB and License + + // Xmls + private String parent; + + public LimitEntity() { + } + + public LimitEntity(String vlmId, Version version, String epLkgId, String id) { + this.vendorLicenseModelId = vlmId; + this.version = version; + this.epLkgId = epLkgId; + this.id = id; + } + + public String getUnit() { + return unit; + } + + public void setUnit(String unit) { + this.unit = unit; + } + + public AggregationFunction getAggregationFunction() { + return aggregationFunction; + } + + public void setAggregationFunction(AggregationFunction aggregationFunction) { + this.aggregationFunction = aggregationFunction; + } + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVendorLicenseModelId(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public String getEpLkgId() { + return epLkgId; + } + + public void setEpLkgId(String epLkgId) { + this.epLkgId = epLkgId; + } + + public String getVendorLicenseModelId() { + return vendorLicenseModelId; + } + + public void setVendorLicenseModelId(String vendorLicenseModelId) { + this.vendorLicenseModelId = vendorLicenseModelId; + } + + public LimitType getType() { + return type; + } + + public void setType(LimitType type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMetric() { + return metric; + } + + public void setMetric(String metric) { + this.metric = metric; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + //Defined and used only to find parent(EP/LKG) of Limit. Not to be persisted in DB and License + + // Xmls + public String getParent() { + return parent; + } + + public void setParent(String parent) { + this.parent = parent; + } + + @Override + public int hashCode() { + return Objects.hash(vendorLicenseModelId, version, epLkgId, id, name, description, type, metric, unit, time, aggregationFunction, value); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + LimitEntity that = (LimitEntity) obj; + return Objects.equals(that.unit, unit) && Objects.equals(that.value, value) && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) + && Objects.equals(epLkgId, that.epLkgId) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects + .equals(description, that.description) && Objects.equals(type, that.type) && Objects.equals(metric, that.metric) && Objects + .equals(aggregationFunction, that.aggregationFunction); + } + + @Override + public String toString() { + return "LimitEntity{" + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' + ", version=" + version + ", epLkgId=" + epLkgId + ", id='" + + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type=" + type + ", metric=" + metric + ", value='" + + value + '\'' + ", unit='" + unit + '\'' + ", aggregationFunction=" + aggregationFunction + ", time=" + time + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitType.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitType.java index 20bc3640bf..6c7231ac51 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitType.java @@ -19,8 +19,4 @@ */ package org.openecomp.sdc.vendorlicense.dao.types; -public enum LimitType { - ServiceProvider, - Vendor; - -} +public enum LimitType {ServiceProvider, Vendor;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/MultiChoiceOrOther.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/MultiChoiceOrOther.java index d70bc426e1..d46f815226 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/MultiChoiceOrOther.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/MultiChoiceOrOther.java @@ -13,165 +13,149 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.Transient; import com.datastax.driver.mapping.annotations.UDT; +import java.util.HashSet; +import java.util.Set; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; -import java.util.HashSet; -import java.util.Set; - @UDT(keyspace = "dox", name = "multi_choice_or_other") public class MultiChoiceOrOther> { - private static final String MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID = - "MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID"; - - private static final String MULTI_CHOICE_OR_OTHER_INVALID_ENUM_MSG = - "Enum used as part of MultiChoiceOrOther type must contain the value 'Other'"; - - public static final String OTHER_ENUM_VALUE = "Other"; - - @Transient - private Set choices; - @Transient - private String other; - - - private Set results; - - public MultiChoiceOrOther() { - // Default constructor - } - - /** - * Instantiates a new Multi choice or other. - * - * @param choices the choices - * @param other the other - */ - public MultiChoiceOrOther(Set choices, String other) { - this.choices = choices; - this.other = other; - results = resolveResult(); - } + public static final String OTHER_ENUM_VALUE = "Other"; + private static final String MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID = "MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID"; + private static final String MULTI_CHOICE_OR_OTHER_INVALID_ENUM_MSG = "Enum used as part of MultiChoiceOrOther type must contain the value 'Other'"; + @Transient + private Set choices; + @Transient + private String other; + private Set results; + + public MultiChoiceOrOther() { + // Default constructor + } - public Set getChoices() { - return choices; - } + /** + * Instantiates a new Multi choice or other. + * + * @param choices the choices + * @param other the other + */ + public MultiChoiceOrOther(Set choices, String other) { + this.choices = choices; + this.other = other; + results = resolveResult(); + } - public void setChoices(Set choices) { - this.choices = choices; - } + public Set getChoices() { + return choices; + } - public String getOther() { - return other; - } + public void setChoices(Set choices) { + this.choices = choices; + } - public void setOther(String other) { - this.other = other; - } + public String getOther() { + return other; + } - public Set getResults() { - return results; - } + public void setOther(String other) { + this.other = other; + } - /** - * Sets results. - * - * @param results the results - */ - public void setResults(Set results) { - if (choices != null) { - if (results == null) { - this.results = resolveResult(); - } - } else { - this.results = results; + public Set getResults() { + return results; } - } - private Set resolveResult() { - if (choices != null) { - results = new HashSet<>(); - if (choices.size() == 1 && OTHER_ENUM_VALUE.equals(choices.iterator().next().name())) { - results.add(other); - } else { - for (E choice : choices) { - results.add(choice.name()); + /** + * Sets results. + * + * @param results the results + */ + public void setResults(Set results) { + if (choices != null) { + if (results == null) { + this.results = resolveResult(); } + } else { + this.results = results; } } - return results; - } - - /** - * Resolve enum. - * - * @param enumClass the enum class - */ - public void resolveEnum(Class enumClass) { - if (choices != null || CollectionUtils.isEmpty(results)) { - return; - } - - choices = new HashSet<>(); - if (results.size() > 1) { - for (String result : results) { - choices.add(E.valueOf(enumClass, result)); - } - } else { - String result = results.iterator().next(); - try { - choices.add(E.valueOf(enumClass, result)); - } catch (IllegalArgumentException exception) { - try { - choices.add(E.valueOf(enumClass, OTHER_ENUM_VALUE)); - } catch (IllegalArgumentException ex) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withId(MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID) - .withMessage(MULTI_CHOICE_OR_OTHER_INVALID_ENUM_MSG).build()); + private Set resolveResult() { + if (choices != null) { + results = new HashSet<>(); + if (choices.size() == 1 && OTHER_ENUM_VALUE.equals(choices.iterator().next().name())) { + results.add(other); + } else { + for (E choice : choices) { + results.add(choice.name()); + } + } } - other = result; - } + return results; } - } - @Override - public int hashCode() { - int result = choices != null ? choices.hashCode() : 0; - result = 31 * result + (other != null ? other.hashCode() : 0); - result = 31 * result + (results != null ? results.hashCode() : 0); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null && choices == null && other == null && results == null ) { - return true; + /** + * Resolve enum. + * + * @param enumClass the enum class + */ + public void resolveEnum(Class enumClass) { + if (choices != null || CollectionUtils.isEmpty(results)) { + return; + } + choices = new HashSet<>(); + if (results.size() > 1) { + for (String result : results) { + choices.add(E.valueOf(enumClass, result)); + } + } else { + String result = results.iterator().next(); + try { + choices.add(E.valueOf(enumClass, result)); + } catch (IllegalArgumentException exception) { + try { + choices.add(E.valueOf(enumClass, OTHER_ENUM_VALUE)); + } catch (IllegalArgumentException ex) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withId(MULTI_CHOICE_OR_OTHER_INVALID_ENUM_ERR_ID) + .withMessage(MULTI_CHOICE_OR_OTHER_INVALID_ENUM_MSG).build()); + } + other = result; + } + } } - if (obj == null || getClass() != obj.getClass()) { - return false; + @Override + public int hashCode() { + int result = choices != null ? choices.hashCode() : 0; + result = 31 * result + (other != null ? other.hashCode() : 0); + result = 31 * result + (results != null ? results.hashCode() : 0); + return result; } - MultiChoiceOrOther that = (MultiChoiceOrOther) obj; - - if (choices != null ? !choices.equals(that.choices) : that.choices != null) { - return false; - } - if (other != null ? !other.equals(that.other) : that.other != null) { - return false; + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null && choices == null && other == null && results == null) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + MultiChoiceOrOther that = (MultiChoiceOrOther) obj; + if (choices != null ? !choices.equals(that.choices) : that.choices != null) { + return false; + } + if (other != null ? !other.equals(that.other) : that.other != null) { + return false; + } + return results != null ? results.equals(that.results) : that.results == null; } - return results != null ? results.equals(that.results) : that.results == null; - - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/OperationalScope.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/OperationalScope.java index 69cdb2dabb..ffebbe8b52 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/OperationalScope.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/OperationalScope.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; -public enum OperationalScope { - Network_Wide, - Availability_Zone, - Data_Center, - Tenant, - VM, - CPU, - Core, - Other; -} +public enum OperationalScope {Network_Wide, Availability_Zone, Data_Center, Tenant, VM, CPU, Core, Other;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ThresholdUnit.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ThresholdUnit.java index bd0fa41073..be7e02078e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ThresholdUnit.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/ThresholdUnit.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; -public enum ThresholdUnit { - Absolute, - Percentage -} +public enum ThresholdUnit {Absolute, Percentage} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java index cef444bc76..f6e155b0a2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types; import com.datastax.driver.mapping.annotations.Column; @@ -25,128 +24,118 @@ import com.datastax.driver.mapping.annotations.Computed; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - - +import java.util.Objects; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.util.Objects; - @Table(keyspace = "dox", name = "vendor_license_model") public class VendorLicenseModelEntity implements VersionableEntity { - public static final String ENTITY_TYPE = "Vendor License Model"; - - @PartitionKey - @Column(name = "vlm_id") - private String id; - - @PartitionKey(value = 1) - @Frozen - private Version version; - - @Column(name = "vendor_name") - private String vendorName; - private String description; - private String oldVersion; - @Column(name = "icon") - private String iconRef; - - @Computed("writetime(vendor_name)") - private Long writetimeMicroSeconds; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public VendorLicenseModelEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - public VendorLicenseModelEntity(String id, Version version) { - this.id = id; - this.version = version; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getId(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public String getVendorName() { - return vendorName; - } - - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getIconRef() { - return iconRef; - } - - public void setIconRef(String iconRef) { - this.iconRef = iconRef; - } - - public void setOldVersion(String oldVersion) { - this.oldVersion = oldVersion; - } - - public String getOldVersion() { - return oldVersion; - } - - - @Override - public int hashCode() { - return Objects.hash(id, version, vendorName, description, iconRef); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - VendorLicenseModelEntity that = (VendorLicenseModelEntity) obj; - return Objects.equals(id, that.id) - && Objects.equals(version, that.version) - && Objects.equals(vendorName, that.vendorName) - && Objects.equals(description, that.description) - && Objects.equals(iconRef, that.iconRef); - } + + public static final String ENTITY_TYPE = "Vendor License Model"; + @PartitionKey + @Column(name = "vlm_id") + private String id; + @PartitionKey(value = 1) + @Frozen + private Version version; + @Column(name = "vendor_name") + private String vendorName; + private String description; + private String oldVersion; + @Column(name = "icon") + private String iconRef; + @Computed("writetime(vendor_name)") + private Long writetimeMicroSeconds; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public VendorLicenseModelEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + public VendorLicenseModelEntity(String id, Version version) { + this.id = id; + this.version = version; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getId(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getIconRef() { + return iconRef; + } + + public void setIconRef(String iconRef) { + this.iconRef = iconRef; + } + + public String getOldVersion() { + return oldVersion; + } + + public void setOldVersion(String oldVersion) { + this.oldVersion = oldVersion; + } + + @Override + public int hashCode() { + return Objects.hash(id, version, vendorName, description, iconRef); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + VendorLicenseModelEntity that = (VendorLicenseModelEntity) obj; + return Objects.equals(id, that.id) && Objects.equals(version, that.version) && Objects.equals(vendorName, that.vendorName) && Objects + .equals(description, that.description) && Objects.equals(iconRef, that.iconRef); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/AggregationFunctionForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/AggregationFunctionForXml.java index e2a6be6b9e..b3c1cafcad 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/AggregationFunctionForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/AggregationFunctionForXml.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; public class AggregationFunctionForXml { - private String value; - public String getValue() { - return value; - } + private String value; + + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementMetricForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementMetricForXml.java index 8a449446ec..5134e73536 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementMetricForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementMetricForXml.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; public class EntitlementMetricForXml { - private String value; - public String getValue() { - return value; - } + private String value; + + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementTimeForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementTimeForXml.java index c78a2d6d91..7ebf1367bb 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementTimeForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/EntitlementTimeForXml.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; public class EntitlementTimeForXml { - private String value; - public String getValue() { - return value; - } + private String value; + + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LicenseKeyTypeForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LicenseKeyTypeForXml.java index c8c0d3067e..bfe047a213 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LicenseKeyTypeForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LicenseKeyTypeForXml.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; public class LicenseKeyTypeForXml { - private String value; - public String getValue() { - return value; - } + private String value; + + public String getValue() { + return value; + } - public void setValue(String value) { - this.value = value; - } + public void setValue(String value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitForXml.java index 0a3680b719..f57d48595a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitForXml.java @@ -17,26 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; - import java.util.Set; public class LimitForXml { - Set limits; + Set limits; - @JacksonXmlProperty(isAttribute = false, localName = "limit") - @JacksonXmlElementWrapper(localName = "limits", useWrapping = false) - public Set getLimits() { - return limits; - } + @JacksonXmlProperty(isAttribute = false, localName = "limit") + @JacksonXmlElementWrapper(localName = "limits", useWrapping = false) + public Set getLimits() { + return limits; + } - public void setLimits( - Set limits) { - this.limits = limits; - } + public void setLimits(Set limits) { + this.limits = limits; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitXml.java index 0c989cb3f9..e175ab4070 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/LimitXml.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; import lombok.Getter; @@ -26,27 +25,27 @@ import lombok.Setter; @Getter @Setter public class LimitXml { - String description; - String metric; - String values; - String unit; - String time; - String aggregationFunction; - public EntitlementTimeForXml getTimeForArtifact() { - EntitlementTimeForXml timeForXml = new EntitlementTimeForXml(); - if (time != null) { - timeForXml.setValue(time); - } + String description; + String metric; + String values; + String unit; + String time; + String aggregationFunction; - return timeForXml; - } + public EntitlementTimeForXml getTimeForArtifact() { + EntitlementTimeForXml timeForXml = new EntitlementTimeForXml(); + if (time != null) { + timeForXml.setValue(time); + } + return timeForXml; + } - public AggregationFunctionForXml getAggregationFunctionForArtifact() { - AggregationFunctionForXml aggregationFunctionForXml = new AggregationFunctionForXml(); - if (aggregationFunction != null) { - aggregationFunctionForXml.setValue(aggregationFunction); + public AggregationFunctionForXml getAggregationFunctionForArtifact() { + AggregationFunctionForXml aggregationFunctionForXml = new AggregationFunctionForXml(); + if (aggregationFunction != null) { + aggregationFunctionForXml.setValue(aggregationFunction); + } + return aggregationFunctionForXml; } - return aggregationFunctionForXml; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/OperationalScopeForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/OperationalScopeForXml.java index f51a4127c0..55de51370b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/OperationalScopeForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/OperationalScopeForXml.java @@ -17,22 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; - import java.util.Set; public class OperationalScopeForXml { - Set value; - @JacksonXmlElementWrapper(localName = "value", useWrapping = false) - public Set getValue() { - return value; - } + Set value; + + @JacksonXmlElementWrapper(localName = "value", useWrapping = false) + public Set getValue() { + return value; + } - public void setValue(Set value) { - this.value = value; - } + public void setValue(Set value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/ThresholdForXml.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/ThresholdForXml.java index a50b815069..ceeee10490 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/ThresholdForXml.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/xml/ThresholdForXml.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.types.xml; public class ThresholdForXml { - String unit; - Integer value; - public String getUnit() { - return unit; - } + String unit; + Integer value; + + public String getUnit() { + return unit; + } - public void setUnit(String unit) { - this.unit = unit; - } + public void setUnit(String unit) { + this.unit = unit; + } - public Integer getValue() { - return value; - } + public Integer getValue() { + return value; + } - public void setValue(Integer value) { - this.value = value; - } + public void setValue(Integer value) { + this.value = value; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/InvalidDateErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/InvalidDateErrorBuilder.java index e1857532a8..9aeef8b470 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/InvalidDateErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/InvalidDateErrorBuilder.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,19 +24,16 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class InvalidDateErrorBuilder { - private static final String DATE_RANGE_INVALID = "Vendor license model with id %s has invalid " + - "date range."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - public InvalidDateErrorBuilder(String vendorLicenseModelId){ - builder.withId(VendorLicenseErrorCodes.DATE_RANGE_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(DATE_RANGE_INVALID, vendorLicenseModelId)); - } + private static final String DATE_RANGE_INVALID = "Vendor license model with id %s has invalid " + "date range."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public ErrorCode build() { - return builder.build(); - } + public InvalidDateErrorBuilder(String vendorLicenseModelId) { + builder.withId(VendorLicenseErrorCodes.DATE_RANGE_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(DATE_RANGE_INVALID, vendorLicenseModelId)); + } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/JsonErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/JsonErrorBuilder.java index a11092bbe3..6164d5eb5a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/JsonErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/JsonErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,27 +24,22 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class JsonErrorBuilder { - private static final String JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID = - "JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID"; - private static final String JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID_MSG = - "Json error occured during artifact generation:%s."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Json error builder. - * - * @param exceptionMessage the exception message - */ - public JsonErrorBuilder(String exceptionMessage) { - builder.withId(JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID_MSG, exceptionMessage)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID = "JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID"; + private static final String JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID_MSG = "Json error occured during artifact generation:%s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Json error builder. + * + * @param exceptionMessage the exception message + */ + public JsonErrorBuilder(String exceptionMessage) { + builder.withId(JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(JSON_ERROR_OCCURED_DURING_ARTIFACT_GENERATION_ERR_ID_MSG, exceptionMessage)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/LicensingDataInvalidErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/LicensingDataInvalidErrorBuilder.java index dfc9a93751..0a9839a0e4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/LicensingDataInvalidErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/LicensingDataInvalidErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.errors; +import java.util.List; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import java.util.List; - public class LicensingDataInvalidErrorBuilder { - private static final String LICENSING_DATA_INVALID_MSG = "Invalid licensing data: %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Licensing data invalid error builder. - * - * @param licensingDataErrors the licensing data errors - */ - public LicensingDataInvalidErrorBuilder(List licensingDataErrors) { - builder.withId(VendorLicenseErrorCodes.LICENSING_DATA_INVALID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(LICENSING_DATA_INVALID_MSG, - CommonMethods.listToSeparatedString(licensingDataErrors, ','))); - } + private static final String LICENSING_DATA_INVALID_MSG = "Invalid licensing data: %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public ErrorCode build() { - return builder.build(); - } + /** + * Instantiates a new Licensing data invalid error builder. + * + * @param licensingDataErrors the licensing data errors + */ + public LicensingDataInvalidErrorBuilder(List licensingDataErrors) { + builder.withId(VendorLicenseErrorCodes.LICENSING_DATA_INVALID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(LICENSING_DATA_INVALID_MSG, CommonMethods.listToSeparatedString(licensingDataErrors, ','))); + } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/SubmitUncompletedLicenseModelErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/SubmitUncompletedLicenseModelErrorBuilder.java index 1b25421052..1686078911 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/SubmitUncompletedLicenseModelErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/SubmitUncompletedLicenseModelErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.errors; import org.openecomp.sdc.common.errors.ErrorCode; public class SubmitUncompletedLicenseModelErrorBuilder { - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); /** @@ -38,6 +36,4 @@ public class SubmitUncompletedLicenseModelErrorBuilder { public ErrorCode build() { return builder.build(); } - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/UncompletedVendorLicenseModelErrorType.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/UncompletedVendorLicenseModelErrorType.java index fa35553ecc..cfc1997413 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/UncompletedVendorLicenseModelErrorType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/UncompletedVendorLicenseModelErrorType.java @@ -23,16 +23,14 @@ package org.openecomp.sdc.vendorlicense.errors; * Created by ayalaben on 5/8/2017 */ public enum UncompletedVendorLicenseModelErrorType { - + // @formatter:off SUBMIT_UNCOMPLETED_VLM_MSG_MISSING_LA("Uncompleted vendor license model - cannot be submitted. \n" - + "It must contain a license agreement(s)."), - + + "It must contain a license agreement(s)."), SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG("Uncompleted vendor license model - cannot be submitted. \n" - + "The license agreement(s) must contain at least one feature group."), - + + "The license agreement(s) must contain at least one feature group."), SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP("Uncompleted vendor license model - cannot be submitted. \n" + "The feature group(s) must contain at least one entitlement pool."); - + // @formatter:on private String errorMessage; @@ -44,4 +42,3 @@ public enum UncompletedVendorLicenseModelErrorType { return errorMessage; } } - diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseErrorCodes.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseErrorCodes.java index e8c252f7be..62ea84b48b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseErrorCodes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.errors; - public class VendorLicenseErrorCodes { - public static final String VENDOR_LICENSE_MODEL_NOT_FOUND = "VENDOR_LICENSE_MODEL_NOT_FOUND"; - public static final String SUBMIT_UNCOMPLETED_LICENSE_MODEL = "SUBMIT_UNCOMPLETED_LICENSE_MODEL"; - public static final String LICENSING_DATA_INVALID = "LICENSING_DATA_INVALID"; - - public static final String LIMIT_INVALID_TYPE = "LIMIT_INVALID_TYPE"; - public static final String LIMIT_INVALID_METRIC = "LIMIT_INVALID_METRIC"; - public static final String LIMIT_INVALID_AGGREGATIONFUNCTION = "LIMIT_INVALID_AGGREGATIONFUNCTION"; - public static final String LIMIT_INVALID_TIME = "LIMIT_INVALID_TIME"; - public static final String DUPLICATE_LIMIT_NAME_NOT_ALLOWED = - "DUPLICATE_LIMIT_NAME_NOT_ALLOWED"; - public static final String DATE_RANGE_INVALID = "DATE_RANGE_INVALID"; + public static final String VENDOR_LICENSE_MODEL_NOT_FOUND = "VENDOR_LICENSE_MODEL_NOT_FOUND"; + public static final String SUBMIT_UNCOMPLETED_LICENSE_MODEL = "SUBMIT_UNCOMPLETED_LICENSE_MODEL"; + public static final String LICENSING_DATA_INVALID = "LICENSING_DATA_INVALID"; + public static final String LIMIT_INVALID_TYPE = "LIMIT_INVALID_TYPE"; + public static final String LIMIT_INVALID_METRIC = "LIMIT_INVALID_METRIC"; + public static final String LIMIT_INVALID_AGGREGATIONFUNCTION = "LIMIT_INVALID_AGGREGATIONFUNCTION"; + public static final String LIMIT_INVALID_TIME = "LIMIT_INVALID_TIME"; + public static final String DUPLICATE_LIMIT_NAME_NOT_ALLOWED = "DUPLICATE_LIMIT_NAME_NOT_ALLOWED"; + public static final String DATE_RANGE_INVALID = "DATE_RANGE_INVALID"; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseModelNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseModelNotFoundErrorBuilder.java index e3eb27f342..da95e437c6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseModelNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/errors/VendorLicenseModelNotFoundErrorBuilder.java @@ -13,30 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.errors; import org.openecomp.sdc.common.errors.ErrorCode; public class VendorLicenseModelNotFoundErrorBuilder { - private static final String VENDOR_LICENSE_MODEL_NOT_FOUND_MSG = - "Vendor license model with id %s not found."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Vendor license model not found error builder. - * - * @param vendorLicenseModelId the vendor license model id - */ - public VendorLicenseModelNotFoundErrorBuilder(String vendorLicenseModelId) { - builder.withId(VendorLicenseErrorCodes.VENDOR_LICENSE_MODEL_NOT_FOUND); - builder.withMessage(String.format(VENDOR_LICENSE_MODEL_NOT_FOUND_MSG, vendorLicenseModelId)); - } - - public ErrorCode build() { - return builder.build(); - } - - + private static final String VENDOR_LICENSE_MODEL_NOT_FOUND_MSG = "Vendor license model with id %s not found."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Vendor license model not found error builder. + * + * @param vendorLicenseModelId the vendor license model id + */ + public VendorLicenseModelNotFoundErrorBuilder(String vendorLicenseModelId) { + builder.withId(VendorLicenseErrorCodes.VENDOR_LICENSE_MODEL_NOT_FOUND); + builder.withMessage(String.format(VENDOR_LICENSE_MODEL_NOT_FOUND_MSG, vendorLicenseModelId)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java index d25a18909e..aab0aa89a8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,60 +17,60 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.facade; +import java.util.Collection; import java.util.Optional; import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.vendorlicense.dao.types.*; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementModel; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface VendorLicenseFacade { - LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId); - - LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId); + LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, String licenseAgreementId); - LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); + LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, String licenseAgreementId); - Collection listFeatureGroups(String vlmId, Version version); + LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); - FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup); + Collection listFeatureGroups(String vlmId, Version version); - FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); + FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup); - FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup); + FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); - Collection listEntitlementPools(String vlmId, Version version); + FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup); - EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); + Collection listEntitlementPools(String vlmId, Version version); - void updateEntitlementPool(EntitlementPoolEntity entitlementPool); + EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); - Collection listLicenseKeyGroups(String vlmId, Version version); + void updateEntitlementPool(EntitlementPoolEntity entitlementPool); - LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + Collection listLicenseKeyGroups(String vlmId, Version version); - void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - Collection listLimits(String vlmId, Version version, String epLkgId); + void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LimitEntity createLimit(LimitEntity limit); + Collection listLimits(String vlmId, Version version, String epLkgId); - void updateLimit(LimitEntity limit); + LimitEntity createLimit(LimitEntity limit); - VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); + void updateLimit(LimitEntity limit); + VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); - Collection validateLicensingData(String vlmId, Version vlmVersion, - String licenseAgreementId, - Collection featureGroupIds); + Collection validateLicensingData(String vlmId, Version vlmVersion, String licenseAgreementId, Collection featureGroupIds); - Optional validateVendorForUsage(String vlmId, Version version); + Optional validateVendorForUsage(String vlmId, Version version); - void validate(String vendorLicenseModelId, Version version); + void validate(String vendorLicenseModelId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacadeFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacadeFactory.java index 540cc5ba66..114680c83b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacadeFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacadeFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.facade; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class VendorLicenseFacadeFactory - extends AbstractComponentFactory { +public abstract class VendorLicenseFacadeFactory extends AbstractComponentFactory { - public static VendorLicenseFacadeFactory getInstance() { - return AbstractFactory.getInstance(VendorLicenseFacadeFactory.class); - } + public static VendorLicenseFacadeFactory getInstance() { + return AbstractFactory.getInstance(VendorLicenseFacadeFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java index a3a5b7263f..d06b04a820 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.healing; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public interface HealingService { - VersionableEntity heal(VersionableEntity toHeal); + VersionableEntity heal(VersionableEntity toHeal); - void persistNoHealing(VersionableEntity alreadyHealed); + void persistNoHealing(VersionableEntity alreadyHealed); } - - diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java index 66ac7ab33f..6482178dec 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts; +import java.util.List; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; - public interface VendorLicenseArtifactsService { - FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List featureGroups); + FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, List featureGroups); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/types/VersionedVendorLicenseModel.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/types/VersionedVendorLicenseModel.java index deb321f14e..89d952c976 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/types/VersionedVendorLicenseModel.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/types/VersionedVendorLicenseModel.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,38 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.types; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.versioning.types.VersionInfo; public class VersionedVendorLicenseModel { - private VendorLicenseModelEntity vendorLicenseModel; - private VersionInfo versionInfo; - public VersionedVendorLicenseModel() { - } + private VendorLicenseModelEntity vendorLicenseModel; + private VersionInfo versionInfo; + + public VersionedVendorLicenseModel() { + } - public VersionedVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModel, - VersionInfo versionInfo) { - this.vendorLicenseModel = vendorLicenseModel; - this.versionInfo = versionInfo; - } + public VersionedVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModel, VersionInfo versionInfo) { + this.vendorLicenseModel = vendorLicenseModel; + this.versionInfo = versionInfo; + } - public VendorLicenseModelEntity getVendorLicenseModel() { - return vendorLicenseModel; - } + public VendorLicenseModelEntity getVendorLicenseModel() { + return vendorLicenseModel; + } - public void setVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModel) { - this.vendorLicenseModel = vendorLicenseModel; - } + public void setVendorLicenseModel(VendorLicenseModelEntity vendorLicenseModel) { + this.vendorLicenseModel = vendorLicenseModel; + } - public VersionInfo getVersionInfo() { - return versionInfo; - } + public VersionInfo getVersionInfo() { + return versionInfo; + } - public void setVersionInfo(VersionInfo versionInfo) { - this.versionInfo = versionInfo; - } + public void setVersionInfo(VersionInfo versionInfo) { + this.versionInfo = versionInfo; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/SimpleHealingServiceServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/SimpleHealingServiceServiceFactoryImpl.java index 987e8f41d5..1eae03d3df 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/SimpleHealingServiceServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/SimpleHealingServiceServiceFactoryImpl.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense; import org.openecomp.sdc.vendorlicense.healing.HealingService; import org.openecomp.sdc.vendorlicense.healing.impl.SimpleHealingServiceImpl; public class SimpleHealingServiceServiceFactoryImpl extends HealingServiceFactory { - private static final HealingService INSTANCE = new SimpleHealingServiceImpl(); - @Override - public HealingService createInterface() { - return INSTANCE; - } + private static final HealingService INSTANCE = new SimpleHealingServiceImpl(); + @Override + public HealingService createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactoryImpl.java index 558c32f79c..162af148ae 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseArtifactServiceFactoryImpl.java @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense; import org.openecomp.sdc.vendorlicense.licenseartifacts.VendorLicenseArtifactsService; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.VendorLicenseArtifactsServiceImpl; public class VendorLicenseArtifactServiceFactoryImpl extends VendorLicenseArtifactServiceFactory { - private static final VendorLicenseArtifactsService INSTANCE = new VendorLicenseArtifactsServiceImpl(); - @Override - public VendorLicenseArtifactsService createInterface() { - return INSTANCE; - } + private static final VendorLicenseArtifactsService INSTANCE = new VendorLicenseArtifactsServiceImpl(); + @Override + public VendorLicenseArtifactsService createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/EntitlementPoolDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/EntitlementPoolDaoFactoryImpl.java index bcabffb4cd..c456fc5339 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/EntitlementPoolDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/EntitlementPoolDaoFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -21,13 +20,12 @@ import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDaoFactory; import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.EntitlementPoolZusammenDaoImpl; - public class EntitlementPoolDaoFactoryImpl extends EntitlementPoolDaoFactory { - private static EntitlementPoolDao instance = new EntitlementPoolZusammenDaoImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public EntitlementPoolDao createInterface() { - return instance; - } + private static EntitlementPoolDao instance = new EntitlementPoolZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public EntitlementPoolDao createInterface() { + return instance; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupDaoFactoryImpl.java index ca0e090567..295f3c82a1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupDaoFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -21,13 +20,12 @@ import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory; import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.FeatureGroupDaoZusammenImpl; - public class FeatureGroupDaoFactoryImpl extends FeatureGroupDaoFactory { - private static FeatureGroupDao instance = new FeatureGroupDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public FeatureGroupDao createInterface() { - return instance; - } + private static FeatureGroupDao instance = new FeatureGroupDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public FeatureGroupDao createInterface() { + return instance; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseAgreementDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseAgreementDaoFactoryImpl.java index 25a5f69f02..3a18f6a92e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseAgreementDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseAgreementDaoFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -22,12 +21,11 @@ import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.LicenseAgreementDaoZusammenImpl; public class LicenseAgreementDaoFactoryImpl extends LicenseAgreementDaoFactory { - - private static final LicenseAgreementDao INSTANCE = new LicenseAgreementDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public LicenseAgreementDao createInterface() { - return INSTANCE; - } + private static final LicenseAgreementDao INSTANCE = new LicenseAgreementDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public LicenseAgreementDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseKeyGroupDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseKeyGroupDaoFactoryImpl.java index fbe7dd517e..fe614d8d28 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseKeyGroupDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LicenseKeyGroupDaoFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -22,11 +21,11 @@ import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDaoFactory; import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.LicenseKeyGroupZusammenDaoImpl; public class LicenseKeyGroupDaoFactoryImpl extends LicenseKeyGroupDaoFactory { - private static final LicenseKeyGroupDao INSTANCE = new LicenseKeyGroupZusammenDaoImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public LicenseKeyGroupDao createInterface() { - return INSTANCE; - } + private static final LicenseKeyGroupDao INSTANCE = new LicenseKeyGroupZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public LicenseKeyGroupDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LimitDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LimitDaoFactoryImpl.java index bad6d3299f..980fc557a2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LimitDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/LimitDaoFactoryImpl.java @@ -26,11 +26,10 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.LimitZusammenDaoImpl; public class LimitDaoFactoryImpl extends LimitDaoFactory { - private static final LimitDao INSTANCE = new LimitZusammenDaoImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); + private static final LimitDao INSTANCE = new LimitZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public LimitDao createInterface() { - return INSTANCE; - } + @Override + public LimitDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/VendorLicenseModelDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/VendorLicenseModelDaoFactoryImpl.java index 79d0677da7..6cdec701c1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/VendorLicenseModelDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/VendorLicenseModelDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -27,11 +26,10 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VendorLicenseModelDaoZu public class VendorLicenseModelDaoFactoryImpl extends VendorLicenseModelDaoFactory { - private static VendorLicenseModelDao INSTANCE = new VendorLicenseModelDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); + private static VendorLicenseModelDao INSTANCE = new VendorLicenseModelDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public VendorLicenseModelDao createInterface() { - return INSTANCE; - } + @Override + public VendorLicenseModelDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementPropertyName.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementPropertyName.java index 4b81cfcd87..540bf50362 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementPropertyName.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementPropertyName.java @@ -19,7 +19,4 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; -public enum ElementPropertyName { - type, - compositionData -} +public enum ElementPropertyName {type, compositionData} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementType.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementType.java index 6807476605..4dd9ac22e5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/ElementType.java @@ -19,7 +19,4 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; -public enum ElementType { - Limit - -} +public enum ElementType {Limit} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java index e084cf1c1b..aa90df8389 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java @@ -19,6 +19,8 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -27,6 +29,11 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; import org.openecomp.sdc.datatypes.model.ElementType; @@ -35,228 +42,162 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToEnti import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.types.ElementPropertyName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; - public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { - private ZusammenAdaptor zusammenAdaptor; - - public EntitlementPoolZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - //no need - } - - @Override - public void create(EntitlementPoolEntity entitlementPool) { - ZusammenElement entitlementPoolElement = - buildEntitlementPoolElement(entitlementPool, Action.CREATE); - - ZusammenElement entitlementPoolsElement = - ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.IGNORE); - - ZusammenElement limitsElement = - ZusammenUtil.buildStructuralElement(ElementType.Limits, Action.CREATE); - - entitlementPoolElement.addSubElement(limitsElement); - entitlementPoolsElement.addSubElement(entitlementPoolElement); - - SessionContext context = ZusammenUtil.createSessionContext(); - Element epsSavedElement = zusammenAdaptor.saveElement(context, - new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()), - entitlementPoolsElement, "Create entitlement pool"); + private ZusammenAdaptor zusammenAdaptor; - entitlementPool - .setId(epsSavedElement.getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(EntitlementPoolEntity entitlementPool) { - ZusammenElement entitlmentpoolElement = - buildEntitlementPoolElement(entitlementPool, Action.UPDATE); - - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - - Optional epFromDb = zusammenAdaptor.getElementInfo(context, elementContext, - new Id(entitlementPool.getId())); + public EntitlementPoolZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - if (epFromDb.isPresent()) { - if (entitlmentpoolElement.getRelations() == null) { - entitlmentpoolElement.setRelations(new ArrayList<>()); - } - if (epFromDb.get().getRelations() != null && !epFromDb.get().getRelations().isEmpty()) { - entitlmentpoolElement.getRelations().addAll(epFromDb.get().getRelations()); - } + @Override + public void registerVersioning(String versionableEntityType) { + //no need } - zusammenAdaptor.saveElement(context, elementContext, entitlmentpoolElement, - String.format("Update entitlement pool with id %s", entitlementPool.getId())); - } + @Override + public void create(EntitlementPoolEntity entitlementPool) { + ZusammenElement entitlementPoolElement = buildEntitlementPoolElement(entitlementPool, Action.CREATE); + ZusammenElement entitlementPoolsElement = ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.IGNORE); + ZusammenElement limitsElement = ZusammenUtil.buildStructuralElement(ElementType.Limits, Action.CREATE); + entitlementPoolElement.addSubElement(limitsElement); + entitlementPoolsElement.addSubElement(entitlementPoolElement); + SessionContext context = ZusammenUtil.createSessionContext(); + Element epsSavedElement = zusammenAdaptor + .saveElement(context, new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()), + entitlementPoolsElement, "Create entitlement pool"); + entitlementPool.setId(epsSavedElement.getSubElements().iterator().next().getElementId().getValue()); + } - @Override - public EntitlementPoolEntity get(EntitlementPoolEntity entitlementPool) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())) - .map(elementInfo -> { - EntitlementPoolEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); - entity.setVersion(entitlementPool.getVersion()); - return entity; - }) - .orElse(null); - } + @Override + public void update(EntitlementPoolEntity entitlementPool) { + ZusammenElement entitlmentpoolElement = buildEntitlementPoolElement(entitlementPool, Action.UPDATE); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + Optional epFromDb = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); + if (epFromDb.isPresent()) { + if (entitlmentpoolElement.getRelations() == null) { + entitlmentpoolElement.setRelations(new ArrayList<>()); + } + if (epFromDb.get().getRelations() != null && !epFromDb.get().getRelations().isEmpty()) { + entitlmentpoolElement.getRelations().addAll(epFromDb.get().getRelations()); + } + } + zusammenAdaptor.saveElement(context, elementContext, entitlmentpoolElement, + String.format("Update entitlement pool with id %s", entitlementPool.getId())); + } - @Override - public void delete(EntitlementPoolEntity entitlementPool) { - ZusammenElement zusammenElement = buildElement(new Id(entitlementPool.getId()), Action.DELETE); + @Override + public EntitlementPoolEntity get(EntitlementPoolEntity entitlementPool) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())).map(elementInfo -> { + EntitlementPoolEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); + entity.setVersion(entitlementPool.getVersion()); + return entity; + }).orElse(null); + } - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete entitlement pool. id:" + entitlementPool.getId() + "."); - } + @Override + public void delete(EntitlementPoolEntity entitlementPool) { + ZusammenElement zusammenElement = buildElement(new Id(entitlementPool.getId()), Action.DELETE); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete entitlement pool. id:" + entitlementPool.getId() + "."); + } - @Override - public Collection list(EntitlementPoolEntity entitlementPool) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()) - .stream().map(elementInfo -> { - EntitlementPoolEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); - entity.setVersion(entitlementPool.getVersion()); - return entity; + @Override + public Collection list(EntitlementPoolEntity entitlementPool) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()).stream().map(elementInfo -> { + EntitlementPoolEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); + entity.setVersion(entitlementPool.getVersion()); + return entity; }).collect(Collectors.toList()); - } - - @Override - public long count(EntitlementPoolEntity entitlementPool) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()) - .size(); - } - - @Override - public void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, - String referencingFeatureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); - - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.setRelations(elementInfo.get().getRelations().stream() - .filter(relation -> !referencingFeatureGroupId - .equals(relation.getEdge2().getElementId().getValue())) - .collect(Collectors.toList())); - - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "remove referencing feature group"); } - } - @Override - public void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, - String referencingFeatureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); + @Override + public long count(EntitlementPoolEntity entitlementPool) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()).size(); + } - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); + @Override + public void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.setRelations(elementInfo.get().getRelations().stream() + .filter(relation -> !referencingFeatureGroupId.equals(relation.getEdge2().getElementId().getValue())).collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "remove referencing feature group"); + } + } - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - if (zusammenElement.getRelations() == null) { - zusammenElement.setRelations(new ArrayList<>()); - } - zusammenElement.getRelations().add(VlmZusammenUtil - .createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, - referencingFeatureGroupId)); - zusammenAdaptor - .saveElement(context, elementContext, zusammenElement, "add referencing feature group"); + @Override + public void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + if (zusammenElement.getRelations() == null) { + zusammenElement.setRelations(new ArrayList<>()); + } + zusammenElement.getRelations() + .add(VlmZusammenUtil.createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, referencingFeatureGroupId)); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "add referencing feature group"); + } } - } - @Override - public void deleteAll(EntitlementPoolEntity entitlementPool) { - //not supported - } + @Override + public void deleteAll(EntitlementPoolEntity entitlementPool) { + //not supported + } - @Override - public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = - new ElementContext(entitlementPoolEntity.getVendorLicenseModelId(), + @Override + public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPoolEntity.getVendorLicenseModelId(), entitlementPoolEntity.getVersion().getId()); - - Optional elementInfo1 = zusammenAdaptor - .getElementInfo(context, elementContext, new Id(entitlementPoolEntity.getId())); - Map properties = elementInfo1.get().getInfo().getProperties(); - String manufacturerReferenceNumber = null; - if (properties != null && properties.containsKey("manufacturerReferenceNumber")) { - manufacturerReferenceNumber = (String) properties.get("manufacturerReferenceNumber"); + Optional elementInfo1 = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPoolEntity.getId())); + Map properties = elementInfo1.get().getInfo().getProperties(); + String manufacturerReferenceNumber = null; + if (properties != null && properties.containsKey("manufacturerReferenceNumber")) { + manufacturerReferenceNumber = (String) properties.get("manufacturerReferenceNumber"); + } + return manufacturerReferenceNumber; } - return manufacturerReferenceNumber; - } - - private ZusammenElement buildEntitlementPoolElement(EntitlementPoolEntity entitlementPool, - Action action) { - ZusammenElement entitlementPoolElement = - buildElement(entitlementPool.getId() == null ? null : new Id(entitlementPool.getId()), - action); - Info info = new Info(); - info.setName(entitlementPool.getName()); - info.setDescription(entitlementPool.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.EntitlementPool); - info.addProperty("version_uuid", entitlementPool.getVersionUuId()); - info.addProperty("EntitlementPoolType", entitlementPool.getType()); - info.addProperty("thresholdValue", entitlementPool.getThresholdValue()); - info.addProperty("threshold_unit", entitlementPool.getThresholdUnit()); - info.addProperty("increments", entitlementPool.getIncrements()); - info.addProperty("operational_scope", entitlementPool.getOperationalScope()); - info.addProperty("startDate", entitlementPool.getStartDate()); - info.addProperty("expiryDate", entitlementPool.getExpiryDate()); - info.addProperty("manufacturerReferenceNumber", entitlementPool.getManufacturerReferenceNumber()); - entitlementPoolElement.setInfo(info); - if (entitlementPool.getReferencingFeatureGroups() != null - && !entitlementPool.getReferencingFeatureGroups().isEmpty()) { - entitlementPoolElement.setRelations(entitlementPool.getReferencingFeatureGroups().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, rel)) - .collect(Collectors.toList())); + private ZusammenElement buildEntitlementPoolElement(EntitlementPoolEntity entitlementPool, Action action) { + ZusammenElement entitlementPoolElement = buildElement(entitlementPool.getId() == null ? null : new Id(entitlementPool.getId()), action); + Info info = new Info(); + info.setName(entitlementPool.getName()); + info.setDescription(entitlementPool.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.EntitlementPool); + info.addProperty("version_uuid", entitlementPool.getVersionUuId()); + info.addProperty("EntitlementPoolType", entitlementPool.getType()); + info.addProperty("thresholdValue", entitlementPool.getThresholdValue()); + info.addProperty("threshold_unit", entitlementPool.getThresholdUnit()); + info.addProperty("increments", entitlementPool.getIncrements()); + info.addProperty("operational_scope", entitlementPool.getOperationalScope()); + info.addProperty("startDate", entitlementPool.getStartDate()); + info.addProperty("expiryDate", entitlementPool.getExpiryDate()); + info.addProperty("manufacturerReferenceNumber", entitlementPool.getManufacturerReferenceNumber()); + entitlementPoolElement.setInfo(info); + if (entitlementPool.getReferencingFeatureGroups() != null && !entitlementPool.getReferencingFeatureGroups().isEmpty()) { + entitlementPoolElement.setRelations(entitlementPool.getReferencingFeatureGroups().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, rel)).collect(Collectors.toList())); + } + return entitlementPoolElement; } - return entitlementPoolElement; - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java index fce2722e63..aacb10982d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java @@ -19,6 +19,10 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +32,11 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; @@ -35,289 +44,199 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToFeat import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.types.ElementPropertyName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { - private ZusammenAdaptor zusammenAdaptor; - - public FeatureGroupDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - //no need - } - - @Override - public void create(FeatureGroupEntity featureGroup) { - ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.CREATE); - - ZusammenElement featureGroupsElement = - buildStructuralElement(ElementType.FeatureGroups, Action.IGNORE); - - featureGroupsElement.addSubElement(featureGroupElement); - - SessionContext context = createSessionContext(); - Element featureGroupsSavedElement = zusammenAdaptor.saveElement(context, - new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()), featureGroupsElement, "Create feature group"); - - featureGroup.setId( - featureGroupsSavedElement.getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(FeatureGroupEntity featureGroup) { - ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()), featureGroupElement, - String.format("Update feature group with id %s", featureGroup.getId())); - } - - @Override - public FeatureGroupEntity get(FeatureGroupEntity featureGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())) - .map(elementInfo -> { - FeatureGroupEntity entity = new ElementToFeatureGroupConvertor().convert(elementInfo); - entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); - entity.setVersion(featureGroup.getVersion()); - return entity; - }) - .orElse(null); - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public void delete(FeatureGroupEntity featureGroup) { - ZusammenElement zusammenElement = buildElement(new Id(featureGroup.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete feature group. id:" + featureGroup.getId() + "."); - } - - @Override - public Collection list(FeatureGroupEntity featureGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - - ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()) - .stream().map(elementInfo -> { - FeatureGroupEntity entity = convertor.convert( - elementInfo); - entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); - entity.setVersion(featureGroup.getVersion()); - return entity; - }) - .collect(Collectors.toList()); - } - - @Override - public long count(FeatureGroupEntity featureGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()) - .size(); - } - - @Override - public void removeEntitlementPool(FeatureGroupEntity featureGroup, String entitlementPoolId) { - removeRelationToContainedEntity(featureGroup, entitlementPoolId, "entitlement pool"); - } - - @Override - public void removeLicenseKeyGroup(FeatureGroupEntity featureGroup, String licenseKeyGroupId) { - removeRelationToContainedEntity(featureGroup, licenseKeyGroupId, "license Key Group"); - } - - private void removeRelationToContainedEntity(FeatureGroupEntity featureGroup, - String containedEntityId, - String containedEntityType) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - - Optional elementInfo = zusammenAdaptor.getElementInfo(context, - elementContext, new Id(featureGroup.getId())); - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.setRelations(elementInfo.get().getRelations().stream() - .filter( - relation -> !containedEntityId.equals(relation.getEdge2().getElementId().getValue())) - .collect(Collectors.toList())); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - String.format("remove %s", containedEntityType)); + public FeatureGroupDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - } - - @Override - public void updateFeatureGroup(FeatureGroupEntity featureGroup, - Set addedEntitlementPools, - Set removedEntitlementPools, - Set addedLicenseKeyGroups, - Set removedLicenseKeyGroups) { - ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); - ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); - Optional elementInfo = zusammenAdaptor.getElementInfo(context, - elementContext, new Id(featureGroup.getId())); - if (elementInfo.isPresent()) { - FeatureGroupEntity currentFeatureGroup = convertor.convert(elementInfo.get()); - currentFeatureGroup.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); - currentFeatureGroup.setVersion(featureGroup.getVersion()); - if (!(removedEntitlementPools == null)) { - currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); - } - if (!(addedEntitlementPools == null)) { - currentFeatureGroup.getEntitlementPoolIds().addAll(addedEntitlementPools); - } - - if (featureGroupElement.getRelations() == null) { - featureGroupElement.setRelations(new ArrayList<>()); - } - featureGroupElement.getRelations() - .addAll(currentFeatureGroup.getEntitlementPoolIds().stream() - .map(relation -> VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToEntitlmentPool, relation)) - .collect(Collectors.toList())); - if (!(removedLicenseKeyGroups == null)) { - currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); - } - if (!(addedLicenseKeyGroups == null)) { - currentFeatureGroup.getLicenseKeyGroupIds().addAll(addedLicenseKeyGroups); - } - - featureGroupElement.getRelations() - .addAll(currentFeatureGroup.getLicenseKeyGroupIds().stream() - .map(relation -> VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToLicenseKeyGroup, relation)) - .collect(Collectors.toList())); - - Collection laRelations = elementInfo.get().getRelations().stream().filter - (rel -> rel.getType() - .equals(RelationType.FeatureGroupToReferencingLicenseAgreement.name())) - .map(rel -> VlmZusammenUtil.createRelation(RelationType - .FeatureGroupToReferencingLicenseAgreement, rel.getEdge2().getElementId().toString())) - .collect(Collectors.toList()); + @Override + public void registerVersioning(String versionableEntityType) { + //no need + } - featureGroupElement.getRelations().addAll(laRelations); + @Override + public void create(FeatureGroupEntity featureGroup) { + ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.CREATE); + ZusammenElement featureGroupsElement = buildStructuralElement(ElementType.FeatureGroups, Action.IGNORE); + featureGroupsElement.addSubElement(featureGroupElement); + SessionContext context = createSessionContext(); + Element featureGroupsSavedElement = zusammenAdaptor + .saveElement(context, new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()), featureGroupsElement, + "Create feature group"); + featureGroup.setId(featureGroupsSavedElement.getSubElements().iterator().next().getElementId().getValue()); + } - zusammenAdaptor - .saveElement(context, elementContext, featureGroupElement, "update feature group"); + @Override + public void update(FeatureGroupEntity featureGroup) { + ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()), featureGroupElement, + String.format("Update feature group with id %s", featureGroup.getId())); } - } - @Override - public void deleteAll(FeatureGroupEntity featureGroup) { - //not supported - } + @Override + public FeatureGroupEntity get(FeatureGroupEntity featureGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())).map(elementInfo -> { + FeatureGroupEntity entity = new ElementToFeatureGroupConvertor().convert(elementInfo); + entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + entity.setVersion(featureGroup.getVersion()); + return entity; + }).orElse(null); + } + @Override + public void delete(FeatureGroupEntity featureGroup) { + ZusammenElement zusammenElement = buildElement(new Id(featureGroup.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete feature group. id:" + featureGroup.getId() + "."); + } - @Override - public void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, - String licenseAgreementId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); + @Override + public Collection list(FeatureGroupEntity featureGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()).stream().map(elementInfo -> { + FeatureGroupEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + entity.setVersion(featureGroup.getVersion()); + return entity; + }).collect(Collectors.toList()); + } - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.getRelations().add(VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToReferencingLicenseAgreement, - licenseAgreementId)); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "add referencing license agreement"); + @Override + public long count(FeatureGroupEntity featureGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()).size(); } - } - @Override - public void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, - String licenseAgreementId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion().getId()); + @Override + public void removeEntitlementPool(FeatureGroupEntity featureGroup, String entitlementPoolId) { + removeRelationToContainedEntity(featureGroup, entitlementPoolId, "entitlement pool"); + } - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.setRelations(elementInfo.get().getRelations().stream() - .filter( - relation -> !licenseAgreementId.equals(relation.getEdge2().getElementId().getValue())) - .collect(Collectors.toList())); + @Override + public void removeLicenseKeyGroup(FeatureGroupEntity featureGroup, String licenseKeyGroupId) { + removeRelationToContainedEntity(featureGroup, licenseKeyGroupId, "license Key Group"); + } - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "remove referencing license agreement"); + private void removeRelationToContainedEntity(FeatureGroupEntity featureGroup, String containedEntityId, String containedEntityType) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.setRelations( + elementInfo.get().getRelations().stream().filter(relation -> !containedEntityId.equals(relation.getEdge2().getElementId().getValue())) + .collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, String.format("remove %s", containedEntityType)); + } } - } - private ZusammenElement buildFeatureGroupElement(FeatureGroupEntity featureGroup, Action action) { - ZusammenElement featureGroupElement = - buildElement(featureGroup.getId() == null ? null : new Id(featureGroup.getId()), action); - Info info = new Info(); - info.setName(featureGroup.getName()); - info.setDescription(featureGroup.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.FeatureGroup); - info.addProperty("partNumber", featureGroup.getPartNumber()); - featureGroupElement.setInfo(info); + @Override + public void updateFeatureGroup(FeatureGroupEntity featureGroup, Set addedEntitlementPools, Set removedEntitlementPools, + Set addedLicenseKeyGroups, Set removedLicenseKeyGroups) { + ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); + if (elementInfo.isPresent()) { + FeatureGroupEntity currentFeatureGroup = convertor.convert(elementInfo.get()); + currentFeatureGroup.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + currentFeatureGroup.setVersion(featureGroup.getVersion()); + if (!(removedEntitlementPools == null)) { + currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); + } + if (!(addedEntitlementPools == null)) { + currentFeatureGroup.getEntitlementPoolIds().addAll(addedEntitlementPools); + } + if (featureGroupElement.getRelations() == null) { + featureGroupElement.setRelations(new ArrayList<>()); + } + featureGroupElement.getRelations().addAll(currentFeatureGroup.getEntitlementPoolIds().stream() + .map(relation -> VlmZusammenUtil.createRelation(RelationType.FeatureGroupToEntitlmentPool, relation)).collect(Collectors.toList())); + if (!(removedLicenseKeyGroups == null)) { + currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); + } + if (!(addedLicenseKeyGroups == null)) { + currentFeatureGroup.getLicenseKeyGroupIds().addAll(addedLicenseKeyGroups); + } + featureGroupElement.getRelations().addAll(currentFeatureGroup.getLicenseKeyGroupIds().stream() + .map(relation -> VlmZusammenUtil.createRelation(RelationType.FeatureGroupToLicenseKeyGroup, relation)).collect(Collectors.toList())); + Collection laRelations = elementInfo.get().getRelations().stream() + .filter(rel -> rel.getType().equals(RelationType.FeatureGroupToReferencingLicenseAgreement.name())).map(rel -> VlmZusammenUtil + .createRelation(RelationType.FeatureGroupToReferencingLicenseAgreement, rel.getEdge2().getElementId().toString())) + .collect(Collectors.toList()); + featureGroupElement.getRelations().addAll(laRelations); + zusammenAdaptor.saveElement(context, elementContext, featureGroupElement, "update feature group"); + } + } - featureGroupElement.setRelations(new ArrayList<>()); + @Override + public void deleteAll(FeatureGroupEntity featureGroup) { + //not supported + } - if (featureGroup.getEntitlementPoolIds() != null && - !featureGroup.getEntitlementPoolIds().isEmpty()) { - featureGroupElement.getRelations().addAll(featureGroup.getEntitlementPoolIds().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToEntitlmentPool, rel)) - .collect(Collectors.toList())); + @Override + public void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.getRelations() + .add(VlmZusammenUtil.createRelation(RelationType.FeatureGroupToReferencingLicenseAgreement, licenseAgreementId)); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "add referencing license agreement"); + } } - if (featureGroup.getLicenseKeyGroupIds() != null && - !featureGroup.getLicenseKeyGroupIds().isEmpty()) { - featureGroupElement.getRelations() - .addAll(featureGroup.getLicenseKeyGroupIds().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToLicenseKeyGroup, rel)) - .collect(Collectors.toList())); + @Override + public void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.setRelations(elementInfo.get().getRelations().stream() + .filter(relation -> !licenseAgreementId.equals(relation.getEdge2().getElementId().getValue())).collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "remove referencing license agreement"); + } } - if (featureGroup.getReferencingLicenseAgreements() != null && - !featureGroup.getReferencingLicenseAgreements().isEmpty()) { - featureGroupElement.getRelations() - .addAll(featureGroup.getReferencingLicenseAgreements().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.FeatureGroupToReferencingLicenseAgreement, - rel)) - .collect(Collectors.toList())); + private ZusammenElement buildFeatureGroupElement(FeatureGroupEntity featureGroup, Action action) { + ZusammenElement featureGroupElement = buildElement(featureGroup.getId() == null ? null : new Id(featureGroup.getId()), action); + Info info = new Info(); + info.setName(featureGroup.getName()); + info.setDescription(featureGroup.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.FeatureGroup); + info.addProperty("partNumber", featureGroup.getPartNumber()); + featureGroupElement.setInfo(info); + featureGroupElement.setRelations(new ArrayList<>()); + if (featureGroup.getEntitlementPoolIds() != null && !featureGroup.getEntitlementPoolIds().isEmpty()) { + featureGroupElement.getRelations().addAll(featureGroup.getEntitlementPoolIds().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.FeatureGroupToEntitlmentPool, rel)).collect(Collectors.toList())); + } + if (featureGroup.getLicenseKeyGroupIds() != null && !featureGroup.getLicenseKeyGroupIds().isEmpty()) { + featureGroupElement.getRelations().addAll(featureGroup.getLicenseKeyGroupIds().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.FeatureGroupToLicenseKeyGroup, rel)).collect(Collectors.toList())); + } + if (featureGroup.getReferencingLicenseAgreements() != null && !featureGroup.getReferencingLicenseAgreements().isEmpty()) { + featureGroupElement.getRelations().addAll(featureGroup.getReferencingLicenseAgreements().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.FeatureGroupToReferencingLicenseAgreement, rel)) + .collect(Collectors.toList())); + } + return featureGroupElement; } - return featureGroupElement; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java index d30931c8c7..1e4f7ce29c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java @@ -13,9 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -24,6 +27,10 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.Collection; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; @@ -32,187 +39,134 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLice import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.types.ElementPropertyName; -import java.util.Collection; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - @AllArgsConstructor public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { - private ZusammenAdaptor zusammenAdaptor; - - @Override - public void registerVersioning(String versionableEntityType) { - //no need - } - - @Override - public void create(LicenseAgreementEntity licenseAgreement) { - ZusammenElement licenseAgreementElement = - buildLicenseAgreementElement(licenseAgreement, Action.CREATE); - ZusammenElement licenseAgreementsElement = - buildStructuralElement(ElementType.LicenseAgreements, Action.IGNORE); - licenseAgreementsElement.addSubElement(licenseAgreementElement); - - SessionContext context = createSessionContext(); - Element licenseAgreementsSavedElement = zusammenAdaptor.saveElement(context, - new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()), licenseAgreementsElement, - "Create license agreement"); - licenseAgreement - .setId(licenseAgreementsSavedElement.getSubElements().iterator().next().getElementId() - .getValue()); - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public void update(LicenseAgreementEntity licenseAgreement) { - ZusammenElement licenseAgreementElement = - buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()), licenseAgreementElement, - String.format("Update license agreement with id %s", licenseAgreement.getId())); - } - - @Override - public LicenseAgreementEntity get(LicenseAgreementEntity licenseAgreement) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); - ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())) - .map(elementInfo -> { - LicenseAgreementEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); - entity.setVersion(licenseAgreement.getVersion()); - return entity; - }) - .orElse(null); - } - - @Override - public void delete(LicenseAgreementEntity licenseAgreement) { - ZusammenElement zusammenElement = buildElement(new Id(licenseAgreement.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete license agreement. id:" + licenseAgreement.getId() + "."); - } - - - @Override - public Collection list(LicenseAgreementEntity licenseAgreement) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); - ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); - return zusammenAdaptor - .listElementsByName(context, elementContext, null, - ElementType.LicenseAgreements.name()) - .stream().map(elementInfo -> { - LicenseAgreementEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); - entity.setVersion(licenseAgreement.getVersion()); - return entity; - }) - .collect(Collectors.toList()); - } + @Override + public void registerVersioning(String versionableEntityType) { + //no need + } - @Override - public long count(LicenseAgreementEntity licenseAgreement) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); + @Override + public void create(LicenseAgreementEntity licenseAgreement) { + ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.CREATE); + ZusammenElement licenseAgreementsElement = buildStructuralElement(ElementType.LicenseAgreements, Action.IGNORE); + licenseAgreementsElement.addSubElement(licenseAgreementElement); + SessionContext context = createSessionContext(); + Element licenseAgreementsSavedElement = zusammenAdaptor + .saveElement(context, new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()), + licenseAgreementsElement, "Create license agreement"); + licenseAgreement.setId(licenseAgreementsSavedElement.getSubElements().iterator().next().getElementId().getValue()); + } - return zusammenAdaptor.listElementsByName(context, elementContext, null, - ElementType.LicenseAgreements.name()) - .size(); - } + @Override + public void update(LicenseAgreementEntity licenseAgreement) { + ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()), + licenseAgreementElement, String.format("Update license agreement with id %s", licenseAgreement.getId())); + } - @Override - public void deleteAll(LicenseAgreementEntity entity) { - //not supported - } + @Override + public LicenseAgreementEntity get(LicenseAgreementEntity licenseAgreement) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())).map(elementInfo -> { + LicenseAgreementEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + entity.setVersion(licenseAgreement.getVersion()); + return entity; + }).orElse(null); + } - @Override - public void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); + @Override + public void delete(LicenseAgreementEntity licenseAgreement) { + ZusammenElement zusammenElement = buildElement(new Id(licenseAgreement.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete license agreement. id:" + licenseAgreement.getId() + "."); + } - Optional elementInfo = zusammenAdaptor.getElementInfo(context, - elementContext, new Id(licenseAgreement.getId())); - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.setRelations(elementInfo.get().getRelations().stream() - .filter(relation -> !featureGroupId.equals(relation.getEdge2().getElementId().getValue())) - .collect(Collectors.toList())); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "remove feature group"); + @Override + public Collection list(LicenseAgreementEntity licenseAgreement) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.LicenseAgreements.name()).stream().map(elementInfo -> { + LicenseAgreementEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + entity.setVersion(licenseAgreement.getVersion()); + return entity; + }).collect(Collectors.toList()); } - } - @Override - public void updateColumnsAndDeltaFeatureGroupIds(LicenseAgreementEntity licenseAgreement, - Set addedFeatureGroupIds, - Set removedFeatureGroupIds) { - ZusammenElement licenseAgreementElement = - buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); + @Override + public long count(LicenseAgreementEntity licenseAgreement) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.LicenseAgreements.name()).size(); + } - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion().getId()); - ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); - if (elementInfo.isPresent()) { - LicenseAgreementEntity currentLicenseAgreement = - convertor.convert(elementInfo.get()); - currentLicenseAgreement.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); - currentLicenseAgreement.setVersion(licenseAgreement.getVersion()); - if (!(removedFeatureGroupIds == null)) { - currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); - } + @Override + public void deleteAll(LicenseAgreementEntity entity) { + //not supported + } - if (!(addedFeatureGroupIds == null)) { - currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); - } - licenseAgreementElement.setRelations(currentLicenseAgreement.getFeatureGroupIds().stream() - .map(relation -> VlmZusammenUtil - .createRelation(RelationType.LicenseAgreementToFeatureGroup, relation)) - .collect(Collectors.toList())); - zusammenAdaptor.saveElement(context, elementContext, licenseAgreementElement, - "update license agreement"); + @Override + public void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.setRelations( + elementInfo.get().getRelations().stream().filter(relation -> !featureGroupId.equals(relation.getEdge2().getElementId().getValue())) + .collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "remove feature group"); + } } - } - private ZusammenElement buildLicenseAgreementElement(LicenseAgreementEntity licenseAgreement, - Action action) { - ZusammenElement licenseAgreementElement = - buildElement(licenseAgreement.getId() == null ? null : new Id(licenseAgreement.getId()), - action); - Info info = new Info(); - info.setName(licenseAgreement.getName()); - info.setDescription(licenseAgreement.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseAgreement); - info.addProperty("licenseTerm", licenseAgreement.getLicenseTerm()); - info.addProperty("requirementsAndConstrains", licenseAgreement.getRequirementsAndConstrains()); - licenseAgreementElement.setInfo(info); + @Override + public void updateColumnsAndDeltaFeatureGroupIds(LicenseAgreementEntity licenseAgreement, Set addedFeatureGroupIds, + Set removedFeatureGroupIds) { + ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); + if (elementInfo.isPresent()) { + LicenseAgreementEntity currentLicenseAgreement = convertor.convert(elementInfo.get()); + currentLicenseAgreement.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + currentLicenseAgreement.setVersion(licenseAgreement.getVersion()); + if (!(removedFeatureGroupIds == null)) { + currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); + } + if (!(addedFeatureGroupIds == null)) { + currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); + } + licenseAgreementElement.setRelations(currentLicenseAgreement.getFeatureGroupIds().stream() + .map(relation -> VlmZusammenUtil.createRelation(RelationType.LicenseAgreementToFeatureGroup, relation)).collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, licenseAgreementElement, "update license agreement"); + } + } - if (licenseAgreement.getFeatureGroupIds() != null && - !licenseAgreement.getFeatureGroupIds().isEmpty()) { - licenseAgreementElement.setRelations(licenseAgreement.getFeatureGroupIds().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.LicenseAgreementToFeatureGroup, rel)) - .collect(Collectors.toList())); + private ZusammenElement buildLicenseAgreementElement(LicenseAgreementEntity licenseAgreement, Action action) { + ZusammenElement licenseAgreementElement = buildElement(licenseAgreement.getId() == null ? null : new Id(licenseAgreement.getId()), action); + Info info = new Info(); + info.setName(licenseAgreement.getName()); + info.setDescription(licenseAgreement.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseAgreement); + info.addProperty("licenseTerm", licenseAgreement.getLicenseTerm()); + info.addProperty("requirementsAndConstrains", licenseAgreement.getRequirementsAndConstrains()); + licenseAgreementElement.setInfo(info); + if (licenseAgreement.getFeatureGroupIds() != null && !licenseAgreement.getFeatureGroupIds().isEmpty()) { + licenseAgreementElement.setRelations(licenseAgreement.getFeatureGroupIds().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.LicenseAgreementToFeatureGroup, rel)).collect(Collectors.toList())); + } + return licenseAgreementElement; } - return licenseAgreementElement; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java index e5a08ae93a..6d44d1a66a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java @@ -19,6 +19,10 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -27,6 +31,10 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; @@ -35,206 +43,145 @@ import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLice import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.types.ElementPropertyName; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - @AllArgsConstructor public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { - private ZusammenAdaptor zusammenAdaptor; - - @Override - public void registerVersioning(String versionableEntityType) { - //no need - } - - @Override - public void create(LicenseKeyGroupEntity licenseKeyGroup) { - ZusammenElement licenseKeyGroupElement = - buildLicenseKeyGroupElement(licenseKeyGroup, Action.CREATE); - - ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, Action.CREATE); - licenseKeyGroupElement.addSubElement(limitsElement); - - ZusammenElement lkgsElement = - buildStructuralElement(ElementType.LicenseKeyGroups, Action.IGNORE); - lkgsElement.addSubElement(licenseKeyGroupElement); - - SessionContext context = createSessionContext(); - Element lkgsSavedElement = zusammenAdaptor.saveElement(context, - new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()), lkgsElement, "Create license Key Group"); - - licenseKeyGroup - .setId(lkgsSavedElement.getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(LicenseKeyGroupEntity licenseKeyGroup) { - ZusammenElement licenseKeyGroupElement = - buildLicenseKeyGroupElement(licenseKeyGroup, Action.UPDATE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - Optional lkgFromDb = zusammenAdaptor.getElementInfo(context, elementContext, - new Id(licenseKeyGroup.getId())); + private ZusammenAdaptor zusammenAdaptor; - if (lkgFromDb.isPresent()) { - - if (licenseKeyGroupElement.getRelations() == null) { - licenseKeyGroupElement.setRelations(new ArrayList<>()); - } - - if (lkgFromDb.get().getRelations() != null && !lkgFromDb.get().getRelations().isEmpty()) { - licenseKeyGroupElement.getRelations().addAll(lkgFromDb.get().getRelations()); - } + @Override + public void registerVersioning(String versionableEntityType) { + //no need } - zusammenAdaptor.saveElement(context, elementContext, licenseKeyGroupElement, - String.format("Update license key group with id %s", licenseKeyGroup.getId())); - } - - @Override - public LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())) - .map(elementInfo -> { - LicenseKeyGroupEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); - entity.setVersion(licenseKeyGroup.getVersion()); - return entity; - }) - .orElse(null); - } - - @Override - public void delete(LicenseKeyGroupEntity licenseKeyGroup) { - ZusammenElement zusammenElement = buildElement(new Id(licenseKeyGroup.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete license key group. id:" + licenseKeyGroup.getId() + "."); - } - - @Override - public Collection list(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()) - .stream().map(elementInfo -> { - LicenseKeyGroupEntity entity = convertor.convert(elementInfo); - entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); - entity.setVersion(licenseKeyGroup.getVersion()); - return entity; - }) - .collect(Collectors.toList()); - } - - @Override - public long count(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - - return zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()) - .size(); - } - @Override - public void deleteAll(LicenseKeyGroupEntity licenseKeyGroup) { - //not supported - } - - @Override - public void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, - String featureGroupId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); + @Override + public void create(LicenseKeyGroupEntity licenseKeyGroup) { + ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.CREATE); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, Action.CREATE); + licenseKeyGroupElement.addSubElement(limitsElement); + ZusammenElement lkgsElement = buildStructuralElement(ElementType.LicenseKeyGroups, Action.IGNORE); + lkgsElement.addSubElement(licenseKeyGroupElement); + SessionContext context = createSessionContext(); + Element lkgsSavedElement = zusammenAdaptor + .saveElement(context, new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()), lkgsElement, + "Create license Key Group"); + licenseKeyGroup.setId(lkgsSavedElement.getSubElements().iterator().next().getElementId().getValue()); + } - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - zusammenElement.setRelations(elementInfo.get().getRelations().stream() - .filter(relation -> !featureGroupId - .equals(relation.getEdge2().getElementId().getValue())) - .collect(Collectors.toList())); + @Override + public void update(LicenseKeyGroupEntity licenseKeyGroup) { + ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + Optional lkgFromDb = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); + if (lkgFromDb.isPresent()) { + if (licenseKeyGroupElement.getRelations() == null) { + licenseKeyGroupElement.setRelations(new ArrayList<>()); + } + if (lkgFromDb.get().getRelations() != null && !lkgFromDb.get().getRelations().isEmpty()) { + licenseKeyGroupElement.getRelations().addAll(lkgFromDb.get().getRelations()); + } + } + zusammenAdaptor.saveElement(context, elementContext, licenseKeyGroupElement, + String.format("Update license key group with id %s", licenseKeyGroup.getId())); + } - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "remove referencing feature group"); + @Override + public LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())).map(elementInfo -> { + LicenseKeyGroupEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); + entity.setVersion(licenseKeyGroup.getVersion()); + return entity; + }).orElse(null); } - } - @Override - public void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, - String featureGroupId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); + @Override + public void delete(LicenseKeyGroupEntity licenseKeyGroup) { + ZusammenElement zusammenElement = buildElement(new Id(licenseKeyGroup.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete license key group. id:" + licenseKeyGroup.getId() + "."); + } - Optional elementInfo = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); + @Override + public Collection list(LicenseKeyGroupEntity licenseKeyGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()).stream().map(elementInfo -> { + LicenseKeyGroupEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); + entity.setVersion(licenseKeyGroup.getVersion()); + return entity; + }).collect(Collectors.toList()); + } - if (elementInfo.isPresent()) { - ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); - zusammenElement.setAction(Action.UPDATE); - if (zusammenElement.getRelations() == null) { - zusammenElement.setRelations(new ArrayList<>()); - } - zusammenElement.getRelations().add(VlmZusammenUtil - .createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, - featureGroupId)); - zusammenAdaptor - .saveElement(context, elementContext, zusammenElement, "add referencing feature group"); + @Override + public long count(LicenseKeyGroupEntity licenseKeyGroup) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()).size(); } - } - private ZusammenElement buildLicenseKeyGroupElement(LicenseKeyGroupEntity licenseKeyGroup, - Action action) { - ZusammenElement lkgElement = - buildElement(licenseKeyGroup.getId() == null ? null : new Id(licenseKeyGroup.getId()), - action); - Info info = new Info(); - info.setName(licenseKeyGroup.getName()); - info.setDescription(licenseKeyGroup.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseKeyGroup); - info.addProperty("version_uuid", licenseKeyGroup.getVersionUuId()); - info.addProperty("LicenseKeyType", licenseKeyGroup.getType()); - info.addProperty("operational_scope", licenseKeyGroup.getOperationalScope()); - info.addProperty("startDate", licenseKeyGroup.getStartDate()); - info.addProperty("expiryDate", licenseKeyGroup.getExpiryDate()); - info.addProperty("thresholdValue", licenseKeyGroup.getThresholdValue()); - info.addProperty("thresholdUnits", licenseKeyGroup.getThresholdUnits()); - info.addProperty("increments", licenseKeyGroup.getIncrements()); - info.addProperty("manufacturerReferenceNumber", licenseKeyGroup.getManufacturerReferenceNumber()); - lkgElement.setInfo(info); + @Override + public void deleteAll(LicenseKeyGroupEntity licenseKeyGroup) { + //not supported + } - if (licenseKeyGroup.getReferencingFeatureGroups() != null - && !licenseKeyGroup.getReferencingFeatureGroups().isEmpty()) { - lkgElement.setRelations(licenseKeyGroup.getReferencingFeatureGroups().stream() - .map(rel -> VlmZusammenUtil - .createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, rel)) - .collect(Collectors.toList())); + @Override + public void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + zusammenElement.setRelations( + elementInfo.get().getRelations().stream().filter(relation -> !featureGroupId.equals(relation.getEdge2().getElementId().getValue())) + .collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "remove referencing feature group"); + } } - return lkgElement; - } + @Override + public void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + Optional elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); + if (elementInfo.isPresent()) { + ZusammenElement zusammenElement = VlmZusammenUtil.getZusammenElement(elementInfo.get()); + zusammenElement.setAction(Action.UPDATE); + if (zusammenElement.getRelations() == null) { + zusammenElement.setRelations(new ArrayList<>()); + } + zusammenElement.getRelations().add(VlmZusammenUtil.createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, featureGroupId)); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "add referencing feature group"); + } + } + private ZusammenElement buildLicenseKeyGroupElement(LicenseKeyGroupEntity licenseKeyGroup, Action action) { + ZusammenElement lkgElement = buildElement(licenseKeyGroup.getId() == null ? null : new Id(licenseKeyGroup.getId()), action); + Info info = new Info(); + info.setName(licenseKeyGroup.getName()); + info.setDescription(licenseKeyGroup.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseKeyGroup); + info.addProperty("version_uuid", licenseKeyGroup.getVersionUuId()); + info.addProperty("LicenseKeyType", licenseKeyGroup.getType()); + info.addProperty("operational_scope", licenseKeyGroup.getOperationalScope()); + info.addProperty("startDate", licenseKeyGroup.getStartDate()); + info.addProperty("expiryDate", licenseKeyGroup.getExpiryDate()); + info.addProperty("thresholdValue", licenseKeyGroup.getThresholdValue()); + info.addProperty("thresholdUnits", licenseKeyGroup.getThresholdUnits()); + info.addProperty("increments", licenseKeyGroup.getIncrements()); + info.addProperty("manufacturerReferenceNumber", licenseKeyGroup.getManufacturerReferenceNumber()); + lkgElement.setInfo(info); + if (licenseKeyGroup.getReferencingFeatureGroups() != null && !licenseKeyGroup.getReferencingFeatureGroups().isEmpty()) { + lkgElement.setRelations(licenseKeyGroup.getReferencingFeatureGroups().stream() + .map(rel -> VlmZusammenUtil.createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, rel)).collect(Collectors.toList())); + } + return lkgElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java index 9fe3b38565..7b90a270bf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java @@ -19,6 +19,10 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -27,6 +31,9 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.Collection; +import java.util.Collections; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LimitDao; @@ -36,163 +43,120 @@ import org.openecomp.sdc.vendorlicense.dao.types.LimitType; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.util.Collection; -import java.util.Collections; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class LimitZusammenDaoImpl implements LimitDao { - private static final String LIMT_TYPE = "type"; - private static final String METRIC = "metric"; - private static final String AGGREGATIONFUNCTION = "aggregationfunction"; - private static final String TIME = "time"; - private static final String UNIT = "unit"; - private static final String VALUE = "value"; - private ZusammenAdaptor zusammenAdaptor; - - public LimitZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void create(LimitEntity limitEntity) { - ZusammenElement limitElement = limitToZusammen(limitEntity, Action.CREATE); - - ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, null); - limitsElement.setSubElements(Collections.singletonList(limitElement)); - - ZusammenElement epLkgElement = buildElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); - epLkgElement.setSubElements(Collections.singletonList(limitsElement)); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - - Element savedElement = - zusammenAdaptor.saveElement(context, elementContext, epLkgElement, "Create limit"); - limitEntity.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public boolean isLimitPresent(LimitEntity limitEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - - Collection elementInfos = zusammenAdaptor.listElementsByName(context, - elementContext, new Id(limitEntity.getEpLkgId()), ElementType.Limits.name()); + private static final String LIMT_TYPE = "type"; + private static final String METRIC = "metric"; + private static final String AGGREGATIONFUNCTION = "aggregationfunction"; + private static final String TIME = "time"; + private static final String UNIT = "unit"; + private static final String VALUE = "value"; + private ZusammenAdaptor zusammenAdaptor; - for (ElementInfo elementInfo : elementInfos) { - if (elementInfo.getId().getValue().equals(limitEntity.getId())) { - return true; - } + public LimitZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - return false; - } - - @Override - public Collection list(LimitEntity limitEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - - return listLimits(context, elementContext, limitEntity); - } - - private Collection listLimits(SessionContext context, ElementContext elementContext, - LimitEntity limitEntity) { - return zusammenAdaptor - .listElementsByName(context, elementContext, new Id(limitEntity.getEpLkgId()), - ElementType.Limits.name()) - .stream().map(elementInfo -> mapElementInfoToLimit( - limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), - limitEntity.getEpLkgId(), elementInfo)) - .collect(Collectors.toList()); - } - - private LimitEntity mapElementInfoToLimit(String vlmId, Version version, - String epLkgId, ElementInfo elementInfo) { - LimitEntity limitEntity = - new LimitEntity(vlmId, version, epLkgId, elementInfo.getId().getValue()); - - limitEntity.setName(elementInfo.getInfo().getName()); - limitEntity.setDescription(elementInfo.getInfo().getDescription()); - limitEntity.setType(elementInfo.getInfo().getProperties().get(LIMT_TYPE) != null ? - LimitType.valueOf((String) elementInfo.getInfo().getProperties().get(LIMT_TYPE)) : - null); - limitEntity.setTime((String) elementInfo.getInfo().getProperties().get(TIME)); - limitEntity.setMetric((String) elementInfo.getInfo().getProperties().get(METRIC)); - limitEntity.setAggregationFunction(elementInfo.getInfo().getProperties().get - (AGGREGATIONFUNCTION) != null ? - AggregationFunction.valueOf((String) elementInfo.getInfo().getProperties() - .get(AGGREGATIONFUNCTION)) : null); - Object unit = elementInfo.getInfo().getProperties().get(UNIT); - limitEntity.setUnit((String) unit); - Object value = elementInfo.getInfo().getProperties().get(VALUE); - limitEntity.setValue((String) value); - - return limitEntity; - } + @Override + public void create(LimitEntity limitEntity) { + ZusammenElement limitElement = limitToZusammen(limitEntity, Action.CREATE); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, null); + limitsElement.setSubElements(Collections.singletonList(limitElement)); + ZusammenElement epLkgElement = buildElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); + epLkgElement.setSubElements(Collections.singletonList(limitsElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, epLkgElement, "Create limit"); + limitEntity.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - @Override - public void update(LimitEntity limitEntity) { - ZusammenElement limitElement = limitToZusammen(limitEntity, Action.UPDATE); + @Override + public boolean isLimitPresent(LimitEntity limitEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + Collection elementInfos = zusammenAdaptor + .listElementsByName(context, elementContext, new Id(limitEntity.getEpLkgId()), ElementType.Limits.name()); + for (ElementInfo elementInfo : elementInfos) { + if (elementInfo.getId().getValue().equals(limitEntity.getId())) { + return true; + } + } + return false; + } - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + @Override + public Collection list(LimitEntity limitEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + return listLimits(context, elementContext, limitEntity); + } - zusammenAdaptor.saveElement(context, elementContext, limitElement, - String.format("Update limit with id %s", limitEntity.getId())); - } + private Collection listLimits(SessionContext context, ElementContext elementContext, LimitEntity limitEntity) { + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(limitEntity.getEpLkgId()), ElementType.Limits.name()).stream().map( + elementInfo -> mapElementInfoToLimit(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), limitEntity.getEpLkgId(), + elementInfo)).collect(Collectors.toList()); + } - @Override - public LimitEntity get(LimitEntity limitEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + private LimitEntity mapElementInfoToLimit(String vlmId, Version version, String epLkgId, ElementInfo elementInfo) { + LimitEntity limitEntity = new LimitEntity(vlmId, version, epLkgId, elementInfo.getId().getValue()); + limitEntity.setName(elementInfo.getInfo().getName()); + limitEntity.setDescription(elementInfo.getInfo().getDescription()); + limitEntity.setType(elementInfo.getInfo().getProperties().get(LIMT_TYPE) != null ? LimitType + .valueOf((String) elementInfo.getInfo().getProperties().get(LIMT_TYPE)) : null); + limitEntity.setTime((String) elementInfo.getInfo().getProperties().get(TIME)); + limitEntity.setMetric((String) elementInfo.getInfo().getProperties().get(METRIC)); + limitEntity.setAggregationFunction(elementInfo.getInfo().getProperties().get(AGGREGATIONFUNCTION) != null ? AggregationFunction + .valueOf((String) elementInfo.getInfo().getProperties().get(AGGREGATIONFUNCTION)) : null); + Object unit = elementInfo.getInfo().getProperties().get(UNIT); + limitEntity.setUnit((String) unit); + Object value = elementInfo.getInfo().getProperties().get(VALUE); + limitEntity.setValue((String) value); + return limitEntity; + } - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(limitEntity.getId())) - .map(elementInfo -> mapElementInfoToLimit( - limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), limitEntity - .getEpLkgId(), elementInfo)) - .orElse(null); - } + @Override + public void update(LimitEntity limitEntity) { + ZusammenElement limitElement = limitToZusammen(limitEntity, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, limitElement, String.format("Update limit with id %s", limitEntity.getId())); + } - @Override - public void delete(LimitEntity limitEntity) { - ZusammenElement zusammenElement = buildElement(new Id(limitEntity.getId()), Action.DELETE); + @Override + public LimitEntity get(LimitEntity limitEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(limitEntity.getId())).map( + elementInfo -> mapElementInfoToLimit(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), limitEntity.getEpLkgId(), + elementInfo)).orElse(null); + } - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete limit Id:" + limitEntity.getId() + "."); - } + @Override + public void delete(LimitEntity limitEntity) { + ZusammenElement zusammenElement = buildElement(new Id(limitEntity.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete limit Id:" + limitEntity.getId() + "."); + } - @Override - public void registerVersioning(String versionableEntityType) { - //registerVersioning not implemented for LimitZusammenDaoImpl - } + @Override + public void registerVersioning(String versionableEntityType) { + //registerVersioning not implemented for LimitZusammenDaoImpl + } - private ZusammenElement limitToZusammen(LimitEntity limit, Action action) { - ZusammenElement limitElement = - buildElement(limit.getId() == null ? null : new Id(limit.getId()), action); - Info info = new Info(); - info.setName(limit.getName()); - info.setDescription(limit.getDescription()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Limit); - info.addProperty(LIMT_TYPE, limit.getType()); - info.addProperty(METRIC, limit.getMetric()); - info.addProperty(AGGREGATIONFUNCTION, limit.getAggregationFunction()); - info.addProperty(TIME, limit.getTime()); - info.addProperty(VALUE, limit.getValue()); - info.addProperty(UNIT, limit.getUnit()); - limitElement.setInfo(info); - return limitElement; - } + private ZusammenElement limitToZusammen(LimitEntity limit, Action action) { + ZusammenElement limitElement = buildElement(limit.getId() == null ? null : new Id(limit.getId()), action); + Info info = new Info(); + info.setName(limit.getName()); + info.setDescription(limit.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Limit); + info.addProperty(LIMT_TYPE, limit.getType()); + info.addProperty(METRIC, limit.getMetric()); + info.addProperty(AGGREGATIONFUNCTION, limit.getAggregationFunction()); + info.addProperty(TIME, limit.getTime()); + info.addProperty(VALUE, limit.getValue()); + info.addProperty(UNIT, limit.getUnit()); + limitElement.setInfo(info); + return limitElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java index 031d415127..2c4702aec1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -21,6 +20,8 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.Collection; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; import org.openecomp.sdc.datatypes.model.ElementType; @@ -31,130 +32,85 @@ import org.openecomp.sdc.versioning.ActionVersioningManagerFactory; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; -import java.util.Collection; -import java.util.stream.Collectors; - public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao { - private ZusammenAdaptor zusammenAdaptor; - - public VendorLicenseModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorLicenseModel", - null, null); - - ActionVersioningManagerFactory.getInstance().createInterface() - .register(versionableEntityType, metadata); - } - - @Override - public Collection list( - VendorLicenseModelEntity vendorLicenseModelEntity) { - - ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); - return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream() - .filter(item -> "VendorLicenseModel".equals(item.getInfo().getProperty("item_type"))) - .map(item -> { - VendorLicenseModelEntity entity = convertor.convert(item); - entity.setId(item.getId().getValue()); - entity.setVersion(null); - return entity; - }) - .collect(Collectors.toList()); - } - - @Override - public void create(VendorLicenseModelEntity vendorLicenseModel) { - - SessionContext context = ZusammenUtil.createSessionContext(); - - ElementContext elementContext = new ElementContext(vendorLicenseModel.getId(), - vendorLicenseModel.getVersion().getId()); - - ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.CREATE); - - zusammenAdaptor.saveElement(context, elementContext, generalElement, - "Create VLM General Info Element"); - - ZusammenElement licenseAgreementsElement = - ZusammenUtil.buildStructuralElement(ElementType.LicenseAgreements, Action.CREATE); - - zusammenAdaptor.saveElement(context, elementContext, licenseAgreementsElement, - "Create VLM licenseAgreementsElement"); - - ZusammenElement featureGroupsElement = - ZusammenUtil.buildStructuralElement(ElementType.FeatureGroups, Action.CREATE); - - zusammenAdaptor.saveElement(context, elementContext, featureGroupsElement, - "Create VLM featureGroupsElement"); - - ZusammenElement lkgsElement = - ZusammenUtil.buildStructuralElement(ElementType.LicenseKeyGroups, Action.CREATE); - - zusammenAdaptor.saveElement(context, elementContext, lkgsElement, - "Create VLM lkgsElement"); - - ZusammenElement entitlementPoolsElement = - ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.CREATE); - - zusammenAdaptor.saveElement(context, elementContext, entitlementPoolsElement, - "Create VLM entitlementPoolsElement"); - } - - @Override - public void update(VendorLicenseModelEntity vendorLicenseModel) { - ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.UPDATE); - - SessionContext context = ZusammenUtil.createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()), - generalElement, "Update VSP General Info Element"); - } - - @Override - public VendorLicenseModelEntity get(VendorLicenseModelEntity vendorLicenseModel) { - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = - new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()); - ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); - return zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VendorLicenseModel.name()) - .map(generalElementInfo -> { - VendorLicenseModelEntity entity = convertor.convert(generalElementInfo); - entity.setId(vendorLicenseModel.getId()); - entity.setVersion(vendorLicenseModel.getVersion()); - return entity; - }) - .orElse(null); - } - - @Override - public void delete(VendorLicenseModelEntity entity) { - throw new UnsupportedOperationException("Delete vlm version is done using versioning manager"); - } - - private ZusammenElement mapVlmToZusammenElement(VendorLicenseModelEntity vendorLicenseModel, - Action action) { - ZusammenElement generalElement = - ZusammenUtil.buildStructuralElement(ElementType.VendorLicenseModel, action); - addVlmToInfo(generalElement.getInfo(), vendorLicenseModel); - return generalElement; - } - - private void addVlmToInfo(Info info, VendorLicenseModelEntity vendorLicenseModel) { - info.addProperty(InfoPropertyName.name.name(), vendorLicenseModel.getVendorName()); - info.addProperty(InfoPropertyName.description.name(), vendorLicenseModel.getDescription()); - info.addProperty(InfoPropertyName.iconRef.name(), vendorLicenseModel.getIconRef()); - } - - public enum InfoPropertyName { - name, - description, - iconRef, - } + private ZusammenAdaptor zusammenAdaptor; + + public VendorLicenseModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public void registerVersioning(String versionableEntityType) { + VersionableEntityMetadata metadata = new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorLicenseModel", null, null); + ActionVersioningManagerFactory.getInstance().createInterface().register(versionableEntityType, metadata); + } + + @Override + public Collection list(VendorLicenseModelEntity vendorLicenseModelEntity) { + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); + return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream() + .filter(item -> "VendorLicenseModel".equals(item.getInfo().getProperty("item_type"))).map(item -> { + VendorLicenseModelEntity entity = convertor.convert(item); + entity.setId(item.getId().getValue()); + entity.setVersion(null); + return entity; + }).collect(Collectors.toList()); + } + + @Override + public void create(VendorLicenseModelEntity vendorLicenseModel) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()); + ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.CREATE); + zusammenAdaptor.saveElement(context, elementContext, generalElement, "Create VLM General Info Element"); + ZusammenElement licenseAgreementsElement = ZusammenUtil.buildStructuralElement(ElementType.LicenseAgreements, Action.CREATE); + zusammenAdaptor.saveElement(context, elementContext, licenseAgreementsElement, "Create VLM licenseAgreementsElement"); + ZusammenElement featureGroupsElement = ZusammenUtil.buildStructuralElement(ElementType.FeatureGroups, Action.CREATE); + zusammenAdaptor.saveElement(context, elementContext, featureGroupsElement, "Create VLM featureGroupsElement"); + ZusammenElement lkgsElement = ZusammenUtil.buildStructuralElement(ElementType.LicenseKeyGroups, Action.CREATE); + zusammenAdaptor.saveElement(context, elementContext, lkgsElement, "Create VLM lkgsElement"); + ZusammenElement entitlementPoolsElement = ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.CREATE); + zusammenAdaptor.saveElement(context, elementContext, entitlementPoolsElement, "Create VLM entitlementPoolsElement"); + } + + @Override + public void update(VendorLicenseModelEntity vendorLicenseModel) { + ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.UPDATE); + SessionContext context = ZusammenUtil.createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()), generalElement, + "Update VSP General Info Element"); + } + + @Override + public VendorLicenseModelEntity get(VendorLicenseModelEntity vendorLicenseModel) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()); + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); + return zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VendorLicenseModel.name()).map(generalElementInfo -> { + VendorLicenseModelEntity entity = convertor.convert(generalElementInfo); + entity.setId(vendorLicenseModel.getId()); + entity.setVersion(vendorLicenseModel.getVersion()); + return entity; + }).orElse(null); + } + + @Override + public void delete(VendorLicenseModelEntity entity) { + throw new UnsupportedOperationException("Delete vlm version is done using versioning manager"); + } + + private ZusammenElement mapVlmToZusammenElement(VendorLicenseModelEntity vendorLicenseModel, Action action) { + ZusammenElement generalElement = ZusammenUtil.buildStructuralElement(ElementType.VendorLicenseModel, action); + addVlmToInfo(generalElement.getInfo(), vendorLicenseModel); + return generalElement; + } + + private void addVlmToInfo(Info info, VendorLicenseModelEntity vendorLicenseModel) { + info.addProperty(InfoPropertyName.name.name(), vendorLicenseModel.getVendorName()); + info.addProperty(InfoPropertyName.description.name(), vendorLicenseModel.getDescription()); + info.addProperty(InfoPropertyName.iconRef.name(), vendorLicenseModel.getIconRef()); + } + + public enum InfoPropertyName {name, description, iconRef,} } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java index 01a15304a9..96c9e2ff83 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java @@ -24,42 +24,39 @@ import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.item.Relation; import com.amdocs.zusammen.datatypes.item.RelationEdge; - import java.util.stream.Collectors; public class VlmZusammenUtil { - static ZusammenElement getZusammenElement(ElementInfo elementInfo) { - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setElementId(elementInfo.getId()); - zusammenElement.setInfo(elementInfo.getInfo()); - zusammenElement.setRelations(elementInfo.getRelations()); - zusammenElement.setSubElements(elementInfo.getSubElements().stream() - .map(VlmZusammenUtil::getZusammenElement) - .collect(Collectors.toList())); - return zusammenElement; - } - - public static Relation createRelation(RelationType type, String to) { - Relation relation = new Relation(); - relation.setType(type.name()); - RelationEdge edge2 = new RelationEdge(); - edge2.setElementId(new Id(to)); - relation.setEdge2(edge2); - return relation; - } + static ZusammenElement getZusammenElement(ElementInfo elementInfo) { + ZusammenElement zusammenElement = new ZusammenElement(); + zusammenElement.setElementId(elementInfo.getId()); + zusammenElement.setInfo(elementInfo.getInfo()); + zusammenElement.setRelations(elementInfo.getRelations()); + zusammenElement.setSubElements(elementInfo.getSubElements().stream().map(VlmZusammenUtil::getZusammenElement).collect(Collectors.toList())); + return zusammenElement; + } - public static Integer toInteger(Object val) { - if (val == null) { - return null; + public static Relation createRelation(RelationType type, String to) { + Relation relation = new Relation(); + relation.setType(type.name()); + RelationEdge edge2 = new RelationEdge(); + edge2.setElementId(new Id(to)); + relation.setEdge2(edge2); + return relation; } - if (val instanceof Double) { - return ((Double) val).intValue(); - } else if (val instanceof String) { - return new Integer((String) val); - } else if (val instanceof Integer) { - return (Integer) val; + + public static Integer toInteger(Object val) { + if (val == null) { + return null; + } + if (val instanceof Double) { + return ((Double) val).intValue(); + } else if (val instanceof String) { + return new Integer((String) val); + } else if (val instanceof Integer) { + return (Integer) val; + } + throw new RuntimeException("invalid value for integer:" + val.getClass()); } - throw new RuntimeException("invalid value for integer:" + val.getClass()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java index 2f06b9b0d0..202e0eac68 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java @@ -19,99 +19,88 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; +import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; -import org.openecomp.convertor.ElementConvertor; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolType; -import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; -import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; -import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; - import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; - -import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; - +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolType; +import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; public class ElementToEntitlementPoolConvertor extends ElementConvertor { - @Override - public EntitlementPoolEntity convert(Element element) { - if (element == null) { - return null; - } - return mapElementToEntitlementPoolEntity(element); - } - @Override - public EntitlementPoolEntity convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public EntitlementPoolEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToEntitlementPoolEntity(element); } - return mapElementInfoToEntitlementPoolEntity(elementInfo); - } - - private EntitlementPoolEntity mapElementToEntitlementPoolEntity(Element element) { - EntitlementPoolEntity entitlementPool = - new EntitlementPoolEntity(); - entitlementPool.setId(element.getElementId().getValue()); - mapInfoToEntitlementPoolEntity(entitlementPool, element.getInfo()); - mapRelationsToEntitlementPoolEntity(entitlementPool, element.getRelations()); - return entitlementPool; - } - private EntitlementPoolEntity mapElementInfoToEntitlementPoolEntity(ElementInfo elementInfo) { - EntitlementPoolEntity entitlementPool = - new EntitlementPoolEntity(); - entitlementPool.setId(elementInfo.getId().getValue()); - mapInfoToEntitlementPoolEntity(entitlementPool, elementInfo.getInfo()); - mapRelationsToEntitlementPoolEntity(entitlementPool, elementInfo.getRelations()); - return entitlementPool; - } + @Override + public EntitlementPoolEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToEntitlementPoolEntity(elementInfo); + } - private void mapInfoToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, Info info) { - entitlementPool.setName(info.getName()); - entitlementPool.setDescription(info.getDescription()); - entitlementPool.setVersionUuId(info.getProperty("version_uuid")); - entitlementPool.setType(EntitlementPoolType.permissiveValueOf(info.getProperty("EntitlementPoolType"))); - entitlementPool.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); - String thresholdUnit = info.getProperty("threshold_unit"); - entitlementPool - .setThresholdUnit(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); - entitlementPool.setIncrements(info.getProperty("increments")); - entitlementPool.setOperationalScope( - getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); - entitlementPool.setStartDate(info.getProperty("startDate")); - entitlementPool.setExpiryDate(info.getProperty("expiryDate")); - entitlementPool.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); - } + private EntitlementPoolEntity mapElementToEntitlementPoolEntity(Element element) { + EntitlementPoolEntity entitlementPool = new EntitlementPoolEntity(); + entitlementPool.setId(element.getElementId().getValue()); + mapInfoToEntitlementPoolEntity(entitlementPool, element.getInfo()); + mapRelationsToEntitlementPoolEntity(entitlementPool, element.getRelations()); + return entitlementPool; + } - private void mapRelationsToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, - Collection relations) { - if (relations != null && relations.size() > 0) { - entitlementPool - .setReferencingFeatureGroups(relations.stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); + private EntitlementPoolEntity mapElementInfoToEntitlementPoolEntity(ElementInfo elementInfo) { + EntitlementPoolEntity entitlementPool = new EntitlementPoolEntity(); + entitlementPool.setId(elementInfo.getId().getValue()); + mapInfoToEntitlementPoolEntity(entitlementPool, elementInfo.getInfo()); + mapRelationsToEntitlementPoolEntity(entitlementPool, elementInfo.getRelations()); + return entitlementPool; } - } - private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther( - Map operationalScope) { - if (operationalScope == null || operationalScope.isEmpty()) { - return null; + private void mapInfoToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, Info info) { + entitlementPool.setName(info.getName()); + entitlementPool.setDescription(info.getDescription()); + entitlementPool.setVersionUuId(info.getProperty("version_uuid")); + entitlementPool.setType(EntitlementPoolType.permissiveValueOf(info.getProperty("EntitlementPoolType"))); + entitlementPool.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); + String thresholdUnit = info.getProperty("threshold_unit"); + entitlementPool.setThresholdUnit(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); + entitlementPool.setIncrements(info.getProperty("increments")); + entitlementPool.setOperationalScope(getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); + entitlementPool.setStartDate(info.getProperty("startDate")); + entitlementPool.setExpiryDate(info.getProperty("expiryDate")); + entitlementPool.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); } - Set choices = new HashSet<>(); - ((List) operationalScope.get("choices")). - forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + private void mapRelationsToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, Collection relations) { + if (relations != null && relations.size() > 0) { + entitlementPool.setReferencingFeatureGroups( + relations.stream().map(relation -> relation.getEdge2().getElementId().getValue()).collect(Collectors.toSet())); + } + } - Object other = operationalScope.get("other"); - return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); - } + private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther(Map operationalScope) { + if (operationalScope == null || operationalScope.isEmpty()) { + return null; + } + Set choices = new HashSet<>(); + ((List) operationalScope.get("choices")).forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + Object other = operationalScope.get("other"); + return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java index 95eee9704c..d12cf3d8ea 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java @@ -23,80 +23,71 @@ import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; -import org.openecomp.convertor.ElementConvertor; -import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; -import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; - import java.util.Collection; import java.util.HashSet; import java.util.Set; - +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; public class ElementToFeatureGroupConvertor extends ElementConvertor { - @Override - public FeatureGroupEntity convert(Element element) { - if (element == null) { - return null; - } - return mapElementToFeatureGroupEntity(element); - - } - @Override - public FeatureGroupEntity convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public FeatureGroupEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToFeatureGroupEntity(element); } - return mapElementInfoToFeatureGroupEntity(elementInfo); - - } - - - private FeatureGroupEntity mapElementToFeatureGroupEntity(Element element) { - FeatureGroupEntity featureGroup = - new FeatureGroupEntity(); - featureGroup.setId(element.getElementId().getValue()); - mapInfoToFeatureGroup(featureGroup, element.getInfo()); - mapRelationsToFeatureGroup(featureGroup, element.getRelations()); - return featureGroup; - } + @Override + public FeatureGroupEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToFeatureGroupEntity(elementInfo); + } - private FeatureGroupEntity mapElementInfoToFeatureGroupEntity(ElementInfo elementInfo) { - FeatureGroupEntity featureGroup = new FeatureGroupEntity(); - featureGroup.setId(elementInfo.getId().getValue()); - mapInfoToFeatureGroup(featureGroup, elementInfo.getInfo()); - mapRelationsToFeatureGroup(featureGroup, elementInfo.getRelations()); - return featureGroup; - } + private FeatureGroupEntity mapElementToFeatureGroupEntity(Element element) { + FeatureGroupEntity featureGroup = new FeatureGroupEntity(); + featureGroup.setId(element.getElementId().getValue()); + mapInfoToFeatureGroup(featureGroup, element.getInfo()); + mapRelationsToFeatureGroup(featureGroup, element.getRelations()); + return featureGroup; + } - private void mapInfoToFeatureGroup(FeatureGroupEntity featureGroup, Info info) { - featureGroup.setName(info.getName()); - featureGroup.setDescription(info.getDescription()); - featureGroup.setPartNumber(info.getProperty("partNumber")); - featureGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); - } + private FeatureGroupEntity mapElementInfoToFeatureGroupEntity(ElementInfo elementInfo) { + FeatureGroupEntity featureGroup = new FeatureGroupEntity(); + featureGroup.setId(elementInfo.getId().getValue()); + mapInfoToFeatureGroup(featureGroup, elementInfo.getInfo()); + mapRelationsToFeatureGroup(featureGroup, elementInfo.getRelations()); + return featureGroup; + } - private void mapRelationsToFeatureGroup(FeatureGroupEntity featureGroup, - Collection relations) { - Set entitlementPoolIds = new HashSet<>(); - Set licenseAgreements = new HashSet<>(); - Set licenseKeyGroupIds = new HashSet<>(); + private void mapInfoToFeatureGroup(FeatureGroupEntity featureGroup, Info info) { + featureGroup.setName(info.getName()); + featureGroup.setDescription(info.getDescription()); + featureGroup.setPartNumber(info.getProperty("partNumber")); + featureGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); + } - if (relations != null) { - for (Relation relation : relations) { - if (RelationType.FeatureGroupToEntitlmentPool.name().equals(relation.getType())) { - entitlementPoolIds.add(relation.getEdge2().getElementId().getValue()); - } else if (RelationType.FeatureGroupToLicenseKeyGroup.name().equals(relation.getType())) { - licenseKeyGroupIds.add(relation.getEdge2().getElementId().getValue()); - } else if (RelationType.FeatureGroupToReferencingLicenseAgreement.name() - .equals(relation.getType())) { - licenseAgreements.add(relation.getEdge2().getElementId().getValue()); + private void mapRelationsToFeatureGroup(FeatureGroupEntity featureGroup, Collection relations) { + Set entitlementPoolIds = new HashSet<>(); + Set licenseAgreements = new HashSet<>(); + Set licenseKeyGroupIds = new HashSet<>(); + if (relations != null) { + for (Relation relation : relations) { + if (RelationType.FeatureGroupToEntitlmentPool.name().equals(relation.getType())) { + entitlementPoolIds.add(relation.getEdge2().getElementId().getValue()); + } else if (RelationType.FeatureGroupToLicenseKeyGroup.name().equals(relation.getType())) { + licenseKeyGroupIds.add(relation.getEdge2().getElementId().getValue()); + } else if (RelationType.FeatureGroupToReferencingLicenseAgreement.name().equals(relation.getType())) { + licenseAgreements.add(relation.getEdge2().getElementId().getValue()); + } + } } - } + featureGroup.setEntitlementPoolIds(entitlementPoolIds); + featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); + featureGroup.setReferencingLicenseAgreements(licenseAgreements); } - featureGroup.setEntitlementPoolIds(entitlementPoolIds); - featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); - featureGroup.setReferencingLicenseAgreements(licenseAgreements); - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java index 0623b10b04..f217c7c4c2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java @@ -23,83 +23,63 @@ import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; +import java.util.Collection; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.convertor.ElementConvertor; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; -import java.util.Collection; -import java.util.Map; -import java.util.stream.Collectors; - - public class ElementToLicenseAgreementConvertor extends ElementConvertor { - @Override - public LicenseAgreementEntity convert(Element element) { - if (element == null) { - return null; - } - return mapElementToLicenseAgreementEntity(element); - - } - - @Override - public LicenseAgreementEntity convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public LicenseAgreementEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLicenseAgreementEntity(element); } - return mapElementInfoToLicenseAgreementEntity(elementInfo); - - } - - private LicenseAgreementEntity mapElementToLicenseAgreementEntity(Element element) { - LicenseAgreementEntity licenseAgreement = - new LicenseAgreementEntity(); - licenseAgreement.setId(element.getElementId().getValue()); - mapInfoToLicenseAgreementEntity(licenseAgreement, element.getInfo()); - mapRelationsToLicenseAgreementEntity(licenseAgreement, element.getRelations()); - return licenseAgreement; - } - - - private LicenseAgreementEntity mapElementInfoToLicenseAgreementEntity(ElementInfo elementInfo) { - LicenseAgreementEntity licenseAgreement = - new LicenseAgreementEntity(); - licenseAgreement.setId( elementInfo.getId().getValue()); - mapInfoToLicenseAgreementEntity(licenseAgreement, elementInfo.getInfo()); - mapRelationsToLicenseAgreementEntity(licenseAgreement, elementInfo.getRelations()); - return licenseAgreement; - } - - private void mapRelationsToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreementEntity, - Collection relations) { - if (relations != null && relations.size() > 0) { - licenseAgreementEntity.setFeatureGroupIds(relations.stream() - .map(relation -> relation.getEdge2().getElementId().getValue()) - .collect(Collectors.toSet())); + @Override + public LicenseAgreementEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToLicenseAgreementEntity(elementInfo); } - } - - private void mapInfoToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreement, Info info) { - - - licenseAgreement.setName(info.getName()); - licenseAgreement.setDescription(info.getDescription()); - - licenseAgreement - .setLicenseTerm(getCoiceOrOther(info.getProperty("licenseTerm"))); - licenseAgreement.setRequirementsAndConstrains( - info.getProperty("requirementsAndConstrains")); + private LicenseAgreementEntity mapElementToLicenseAgreementEntity(Element element) { + LicenseAgreementEntity licenseAgreement = new LicenseAgreementEntity(); + licenseAgreement.setId(element.getElementId().getValue()); + mapInfoToLicenseAgreementEntity(licenseAgreement, element.getInfo()); + mapRelationsToLicenseAgreementEntity(licenseAgreement, element.getRelations()); + return licenseAgreement; + } - } + private LicenseAgreementEntity mapElementInfoToLicenseAgreementEntity(ElementInfo elementInfo) { + LicenseAgreementEntity licenseAgreement = new LicenseAgreementEntity(); + licenseAgreement.setId(elementInfo.getId().getValue()); + mapInfoToLicenseAgreementEntity(licenseAgreement, elementInfo.getInfo()); + mapRelationsToLicenseAgreementEntity(licenseAgreement, elementInfo.getRelations()); + return licenseAgreement; + } - private ChoiceOrOther getCoiceOrOther(Map licenseTerm) { - return new ChoiceOrOther<>(LicenseTerm.valueOf((String) licenseTerm.get("choice")), - (String) licenseTerm.get("other")); - } + private void mapRelationsToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreementEntity, Collection relations) { + if (relations != null && relations.size() > 0) { + licenseAgreementEntity + .setFeatureGroupIds(relations.stream().map(relation -> relation.getEdge2().getElementId().getValue()).collect(Collectors.toSet())); + } + } + private void mapInfoToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreement, Info info) { + licenseAgreement.setName(info.getName()); + licenseAgreement.setDescription(info.getDescription()); + licenseAgreement.setLicenseTerm(getCoiceOrOther(info.getProperty("licenseTerm"))); + licenseAgreement.setRequirementsAndConstrains(info.getProperty("requirementsAndConstrains")); + } + private ChoiceOrOther getCoiceOrOther(Map licenseTerm) { + return new ChoiceOrOther<>(LicenseTerm.valueOf((String) licenseTerm.get("choice")), (String) licenseTerm.get("other")); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java index c22fcf8935..601a5ec35a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java @@ -19,103 +19,88 @@ */ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; +import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; -import org.openecomp.convertor.ElementConvertor; -import org.openecomp.sdc.vendorlicense.dao.types.*; - -import java.util.stream.Collectors; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - - -import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; - +import java.util.stream.Collectors; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; +import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; public class ElementToLicenseKeyGroupConvertor extends ElementConvertor { - @Override - public LicenseKeyGroupEntity convert(Element element) { - if (element == null) { - return null; - } - return mapElementToLicenseKeyGroupEntity(element); - } - - @Override - public LicenseKeyGroupEntity convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public LicenseKeyGroupEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLicenseKeyGroupEntity(element); } - return mapElementInfoToLicenseKeyGroupEntity(elementInfo); - - } - - private LicenseKeyGroupEntity mapElementToLicenseKeyGroupEntity( - Element element) { - LicenseKeyGroupEntity licenseKeyGroup = - new LicenseKeyGroupEntity(); - licenseKeyGroup.setId(element.getElementId().getValue()); - mapInfoToLicenseKeyGroup(licenseKeyGroup, element.getInfo()); - mapRelationsToLicenseKeyGroup(licenseKeyGroup, element.getRelations()); - return licenseKeyGroup; - } - - - private LicenseKeyGroupEntity mapElementInfoToLicenseKeyGroupEntity(ElementInfo elementInfo) { - LicenseKeyGroupEntity licenseKeyGroup = - new LicenseKeyGroupEntity(); - licenseKeyGroup.setId(elementInfo.getId().getValue()); - - mapInfoToLicenseKeyGroup(licenseKeyGroup, elementInfo.getInfo()); - mapRelationsToLicenseKeyGroup(licenseKeyGroup, elementInfo.getRelations()); - return licenseKeyGroup; - } - private void mapInfoToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, Info info) { - licenseKeyGroup.setName(info.getName()); - licenseKeyGroup.setDescription(info.getDescription()); - licenseKeyGroup.setVersionUuId(info.getProperty("version_uuid")); - licenseKeyGroup.setType(LicenseKeyType.valueOf(info.getProperty("LicenseKeyType"))); - licenseKeyGroup.setOperationalScope( - getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); - licenseKeyGroup.setStartDate(info.getProperty("startDate")); - licenseKeyGroup.setExpiryDate(info.getProperty("expiryDate")); - - String thresholdUnit = info.getProperty("thresholdUnits"); - licenseKeyGroup - .setThresholdUnits(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); + @Override + public LicenseKeyGroupEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToLicenseKeyGroupEntity(elementInfo); + } - licenseKeyGroup.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); - licenseKeyGroup.setIncrements(info.getProperty("increments")); - licenseKeyGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); - } + private LicenseKeyGroupEntity mapElementToLicenseKeyGroupEntity(Element element) { + LicenseKeyGroupEntity licenseKeyGroup = new LicenseKeyGroupEntity(); + licenseKeyGroup.setId(element.getElementId().getValue()); + mapInfoToLicenseKeyGroup(licenseKeyGroup, element.getInfo()); + mapRelationsToLicenseKeyGroup(licenseKeyGroup, element.getRelations()); + return licenseKeyGroup; + } - private void mapRelationsToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, - Collection relations) { - if (relations != null && relations.size() > 0) { - licenseKeyGroup - .setReferencingFeatureGroups((relations.stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet()))); + private LicenseKeyGroupEntity mapElementInfoToLicenseKeyGroupEntity(ElementInfo elementInfo) { + LicenseKeyGroupEntity licenseKeyGroup = new LicenseKeyGroupEntity(); + licenseKeyGroup.setId(elementInfo.getId().getValue()); + mapInfoToLicenseKeyGroup(licenseKeyGroup, elementInfo.getInfo()); + mapRelationsToLicenseKeyGroup(licenseKeyGroup, elementInfo.getRelations()); + return licenseKeyGroup; } - } - private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther( - Map operationalScope) { - if (operationalScope == null || operationalScope.isEmpty()) { - return null; + private void mapInfoToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, Info info) { + licenseKeyGroup.setName(info.getName()); + licenseKeyGroup.setDescription(info.getDescription()); + licenseKeyGroup.setVersionUuId(info.getProperty("version_uuid")); + licenseKeyGroup.setType(LicenseKeyType.valueOf(info.getProperty("LicenseKeyType"))); + licenseKeyGroup.setOperationalScope(getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); + licenseKeyGroup.setStartDate(info.getProperty("startDate")); + licenseKeyGroup.setExpiryDate(info.getProperty("expiryDate")); + String thresholdUnit = info.getProperty("thresholdUnits"); + licenseKeyGroup.setThresholdUnits(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); + licenseKeyGroup.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); + licenseKeyGroup.setIncrements(info.getProperty("increments")); + licenseKeyGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); } - Set choices = new HashSet<>(); - ((List) operationalScope.get("choices")). - forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + private void mapRelationsToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, Collection relations) { + if (relations != null && relations.size() > 0) { + licenseKeyGroup.setReferencingFeatureGroups( + (relations.stream().map(relation -> relation.getEdge2().getElementId().getValue()).collect(Collectors.toSet()))); + } + } - Object other = operationalScope.get("other"); - return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); - } + private MultiChoiceOrOther getOperationalScopeMultiChoiceOrOther(Map operationalScope) { + if (operationalScope == null || operationalScope.isEmpty()) { + return null; + } + Set choices = new HashSet<>(); + ((List) operationalScope.get("choices")).forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + Object other = operationalScope.get("other"); + return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java index 20674c669a..ace15af3bf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java @@ -24,36 +24,36 @@ import org.openecomp.sdc.vendorlicense.dao.types.LimitType; * Created by ayalaben on 9/26/2017 */ public class ElementToLimitConvertor extends ElementConvertor { - @Override - public LimitEntity convert(Element element) { - if (element == null) { - return null; - } - return mapElementToLimitEntity(element); - } - private LimitEntity mapElementToLimitEntity(Element element) { - LimitEntity limit = new LimitEntity(); - limit.setId(element.getElementId().getValue()); - limit.setName(element.getInfo().getName()); - limit.setDescription(element.getInfo().getDescription()); - limit.setUnit(element.getInfo().getProperty("unit")); - limit.setMetric(element.getInfo().getProperty("metric")); - limit.setValue(element.getInfo().getProperty("value")); - limit.setTime(element.getInfo().getProperty("time")); - limit.setAggregationFunction(element.getInfo().getProperty("aggregationFunction")); - setLimitType(limit,element.getInfo().getProperty("type")); + @Override + public LimitEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLimitEntity(element); + } - return limit; - } + private LimitEntity mapElementToLimitEntity(Element element) { + LimitEntity limit = new LimitEntity(); + limit.setId(element.getElementId().getValue()); + limit.setName(element.getInfo().getName()); + limit.setDescription(element.getInfo().getDescription()); + limit.setUnit(element.getInfo().getProperty("unit")); + limit.setMetric(element.getInfo().getProperty("metric")); + limit.setValue(element.getInfo().getProperty("value")); + limit.setTime(element.getInfo().getProperty("time")); + limit.setAggregationFunction(element.getInfo().getProperty("aggregationFunction")); + setLimitType(limit, element.getInfo().getProperty("type")); + return limit; + } - private void setLimitType(LimitEntity limit, String type) { - switch (LimitType.valueOf(type)) { - case ServiceProvider: - limit.setType(LimitType.ServiceProvider); - break; - case Vendor: - limit.setType(LimitType.Vendor); + private void setLimitType(LimitEntity limit, String type) { + switch (LimitType.valueOf(type)) { + case ServiceProvider: + limit.setType(LimitType.ServiceProvider); + break; + case Vendor: + limit.setType(LimitType.Vendor); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java index 5dc3b592c0..e274e264c0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java @@ -27,39 +27,37 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VendorLicenseModelDaoZusammenImpl; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; - public class ElementToVLMGeneralConvertor extends ElementConvertor { - @Override - public VendorLicenseModelEntity convert(Element element) { - if(element == null) return null; - return mapInfoToVendorLicenseModelEntity( element.getInfo()); - - } - - @Override - public VendorLicenseModelEntity convert(Item item) { - if(item == null) return null; - return mapInfoToVendorLicenseModelEntity( item.getInfo()); - } - - @Override - public VendorLicenseModelEntity convert(ElementInfo elementInfo) { - if(elementInfo == null) return null; - return mapInfoToVendorLicenseModelEntity( elementInfo.getInfo()); - - } - - private VendorLicenseModelEntity mapInfoToVendorLicenseModelEntity(Info info) { - - VendorLicenseModelEntity vendorLicenseModelEntity = new VendorLicenseModelEntity(); - - vendorLicenseModelEntity.setVendorName(info.getProperty( - VendorLicenseModelDaoZusammenImpl.InfoPropertyName.name.name())); - vendorLicenseModelEntity.setDescription(info.getProperty( - VendorLicenseModelDaoZusammenImpl.InfoPropertyName.description.name())); - vendorLicenseModelEntity.setIconRef(info.getProperty( - VendorLicenseModelDaoZusammenImpl.InfoPropertyName.iconRef.name())); - return vendorLicenseModelEntity; - } + @Override + public VendorLicenseModelEntity convert(Element element) { + if (element == null) { + return null; + } + return mapInfoToVendorLicenseModelEntity(element.getInfo()); + } + + @Override + public VendorLicenseModelEntity convert(Item item) { + if (item == null) { + return null; + } + return mapInfoToVendorLicenseModelEntity(item.getInfo()); + } + + @Override + public VendorLicenseModelEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapInfoToVendorLicenseModelEntity(elementInfo.getInfo()); + } + + private VendorLicenseModelEntity mapInfoToVendorLicenseModelEntity(Info info) { + VendorLicenseModelEntity vendorLicenseModelEntity = new VendorLicenseModelEntity(); + vendorLicenseModelEntity.setVendorName(info.getProperty(VendorLicenseModelDaoZusammenImpl.InfoPropertyName.name.name())); + vendorLicenseModelEntity.setDescription(info.getProperty(VendorLicenseModelDaoZusammenImpl.InfoPropertyName.description.name())); + vendorLicenseModelEntity.setIconRef(info.getProperty(VendorLicenseModelDaoZusammenImpl.InfoPropertyName.iconRef.name())); + return vendorLicenseModelEntity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeFactoryImpl.java index 3cf6d0b806..7eacc8ca9d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.facade.impl; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; public class VendorLicenseFacadeFactoryImpl extends VendorLicenseFacadeFactory { - private static VendorLicenseFacade INSTANCE = new VendorLicenseFacadeImpl(); - @Override - public VendorLicenseFacade createInterface() { - return INSTANCE; - } + private static VendorLicenseFacade INSTANCE = new VendorLicenseFacadeImpl(); + + @Override + public VendorLicenseFacade createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java index 818d772db4..d97b8c8c4d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.facade.impl; import static org.openecomp.sdc.common.errors.ValidationErrorBuilder.FIELD_VALIDATION_ERROR_ERR_ID; @@ -71,337 +70,263 @@ import org.openecomp.sdc.versioning.types.ItemStatus; public class VendorLicenseFacadeImpl implements VendorLicenseFacade { - private static final VendorLicenseModelDao - vendorLicenseModelDao = VendorLicenseModelDaoFactory.getInstance().createInterface(); - private static final LicenseAgreementDao - licenseAgreementDao = LicenseAgreementDaoFactory.getInstance().createInterface(); - private static final FeatureGroupDao featureGroupDao = - FeatureGroupDaoFactory.getInstance().createInterface(); - private static final EntitlementPoolDao - entitlementPoolDao = EntitlementPoolDaoFactory.getInstance().createInterface(); - private static final LicenseKeyGroupDao - licenseKeyGroupDao = LicenseKeyGroupDaoFactory.getInstance().createInterface(); - private static final LimitDao limitDao = LimitDaoFactory.getInstance().createInterface(); - private static final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil - (UniqueValueDaoFactory.getInstance().createInterface()); - private static final ErrorCode USED_VLM_NOT_EXIST_ERROR = - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(FIELD_VALIDATION_ERROR_ERR_ID) - .withMessage("The supplied vendor does not exist").build(); - private static final ErrorCode USED_VLM_ARCHIVE_ERROR = - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(FIELD_VALIDATION_ERROR_ERR_ID) - .withMessage("The supplied vendor is archived and therefore cannot be used").build(); - private static final ErrorCode USED_VLM_IS_DRAFT_ERROR = - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(FIELD_VALIDATION_ERROR_ERR_ID) - .withMessage("The supplied vendor version is draft and therefore can not be used").build(); - - - /** - * Instantiates a new Vendor license facade. - */ - public VendorLicenseFacadeImpl() { - vendorLicenseModelDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - licenseAgreementDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - featureGroupDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - entitlementPoolDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - licenseKeyGroupDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - limitDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); - } - - @Override - public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { - FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); - VersioningUtil - .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); - - return retrieved; - } - - @Override - public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { - FeatureGroupEntity retrieved = getFeatureGroup(featureGroup); - - FeatureGroupModel featureGroupModel = new FeatureGroupModel(); - featureGroupModel.setFeatureGroup(retrieved); - - for (String licenseKeyGroupId : retrieved.getLicenseKeyGroupIds()) { - featureGroupModel.getLicenseKeyGroups().add(licenseKeyGroupDao.get( - new LicenseKeyGroupEntity(retrieved.getVendorLicenseModelId(), retrieved.getVersion(), - licenseKeyGroupId))); + private static final VendorLicenseModelDao vendorLicenseModelDao = VendorLicenseModelDaoFactory.getInstance().createInterface(); + private static final LicenseAgreementDao licenseAgreementDao = LicenseAgreementDaoFactory.getInstance().createInterface(); + private static final FeatureGroupDao featureGroupDao = FeatureGroupDaoFactory.getInstance().createInterface(); + private static final EntitlementPoolDao entitlementPoolDao = EntitlementPoolDaoFactory.getInstance().createInterface(); + private static final LicenseKeyGroupDao licenseKeyGroupDao = LicenseKeyGroupDaoFactory.getInstance().createInterface(); + private static final LimitDao limitDao = LimitDaoFactory.getInstance().createInterface(); + private static final UniqueValueUtil uniqueValueUtil = new UniqueValueUtil(UniqueValueDaoFactory.getInstance().createInterface()); + private static final ErrorCode USED_VLM_NOT_EXIST_ERROR = new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(FIELD_VALIDATION_ERROR_ERR_ID).withMessage("The supplied vendor does not exist").build(); + private static final ErrorCode USED_VLM_ARCHIVE_ERROR = new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(FIELD_VALIDATION_ERROR_ERR_ID).withMessage("The supplied vendor is archived and therefore cannot be used").build(); + private static final ErrorCode USED_VLM_IS_DRAFT_ERROR = new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(FIELD_VALIDATION_ERROR_ERR_ID).withMessage("The supplied vendor version is draft and therefore can not be used").build(); + + /** + * Instantiates a new Vendor license facade. + */ + public VendorLicenseFacadeImpl() { + vendorLicenseModelDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); + licenseAgreementDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); + featureGroupDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); + entitlementPoolDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); + licenseKeyGroupDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); + limitDao.registerVersioning(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE); } - for (String entitlementPoolId : retrieved.getEntitlementPoolIds()) { - featureGroupModel.getEntitlementPools().add(entitlementPoolDao.get( - new EntitlementPoolEntity(retrieved.getVendorLicenseModelId(), retrieved.getVersion(), - entitlementPoolId))); - } - - return featureGroupModel; - } - - @Override - public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId) { - LicenseAgreementEntity retrieved = - getLicenseAgreement(vlmId, version, licenseAgreementId); - - LicenseAgreementModel licenseAgreementModel = new LicenseAgreementModel(); - licenseAgreementModel.setLicenseAgreement(retrieved); - for (String featureGroupId : retrieved.getFeatureGroupIds()) { - licenseAgreementModel.getFeatureGroups().add(featureGroupDao - .get(new FeatureGroupEntity(vlmId, retrieved.getVersion(), featureGroupId))); + @Override + public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { + FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); + VersioningUtil.validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); + return retrieved; } - return licenseAgreementModel; - } - - @Override - public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { - entitlementPool.setVersionUuId(CommonMethods.nextUuId()); - uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId(), - entitlementPool.getName()); - entitlementPoolDao.create(entitlementPool); - return entitlementPool; - } - - @Override - public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { - EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); - VersioningUtil - .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); - if (retrieved.equals(entitlementPool)) { - return; + @Override + public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { + FeatureGroupEntity retrieved = getFeatureGroup(featureGroup); + FeatureGroupModel featureGroupModel = new FeatureGroupModel(); + featureGroupModel.setFeatureGroup(retrieved); + for (String licenseKeyGroupId : retrieved.getLicenseKeyGroupIds()) { + featureGroupModel.getLicenseKeyGroups().add( + licenseKeyGroupDao.get(new LicenseKeyGroupEntity(retrieved.getVendorLicenseModelId(), retrieved.getVersion(), licenseKeyGroupId))); + } + for (String entitlementPoolId : retrieved.getEntitlementPoolIds()) { + featureGroupModel.getEntitlementPools().add( + entitlementPoolDao.get(new EntitlementPoolEntity(retrieved.getVendorLicenseModelId(), retrieved.getVersion(), entitlementPoolId))); + } + return featureGroupModel; } - uniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - retrieved.getName(), entitlementPool.getName(), entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().getId()); - entitlementPool.setVersionUuId(CommonMethods.nextUuId()); - entitlementPoolDao.update(entitlementPool); - } - - @Override - public Collection listLicenseKeyGroups(String vlmId, Version version) { - return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, version, null)); - } - - @Override - public Collection listEntitlementPools(String vlmId, Version version) { - return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, version, null)); - } - @Override - public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); - if (retrieved.equals(licenseKeyGroup)) { - return; + @Override + public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, String licenseAgreementId) { + LicenseAgreementEntity retrieved = getLicenseAgreement(vlmId, version, licenseAgreementId); + LicenseAgreementModel licenseAgreementModel = new LicenseAgreementModel(); + licenseAgreementModel.setLicenseAgreement(retrieved); + for (String featureGroupId : retrieved.getFeatureGroupIds()) { + licenseAgreementModel.getFeatureGroups().add(featureGroupDao.get(new FeatureGroupEntity(vlmId, retrieved.getVersion(), featureGroupId))); + } + return licenseAgreementModel; } - licenseKeyGroup.setVersionUuId((CommonMethods.nextUuId())); - VersioningUtil - .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); - uniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - retrieved.getName(), licenseKeyGroup.getName(), licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().getId()); - licenseKeyGroupDao.update(licenseKeyGroup); - } - @Override - public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { - licenseKeyGroup.setVersionUuId(CommonMethods.nextUuId()); - uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId(), - licenseKeyGroup.getName()); - licenseKeyGroupDao.create(licenseKeyGroup); - return licenseKeyGroup; - } - - @Override - public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { - VendorLicenseModelEntity vendorLicenseModel = - vendorLicenseModelDao.get(new VendorLicenseModelEntity(vlmId, version)); - if (vendorLicenseModel == null) { - throw new CoreException(new VendorLicenseModelNotFoundErrorBuilder(vlmId).build()); + @Override + public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { + entitlementPool.setVersionUuId(CommonMethods.nextUuId()); + uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId(), entitlementPool.getName()); + entitlementPoolDao.create(entitlementPool); + return entitlementPool; } - return vendorLicenseModel; - } - @Override - public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { - VersioningUtil.validateEntitiesExistence(licenseAgreement.getFeatureGroupIds(), - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), - null), - featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); - - uniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), - licenseAgreement.getName()); - - licenseAgreementDao.create(licenseAgreement); - uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), - licenseAgreement.getName()); - if (licenseAgreement.getFeatureGroupIds() != null) { - for (String addedFgId : licenseAgreement.getFeatureGroupIds()) { - featureGroupDao.addReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion(), - addedFgId), licenseAgreement.getId()); - } + @Override + public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { + EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); + VersioningUtil.validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); + if (retrieved.equals(entitlementPool)) { + return; + } + uniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, retrieved.getName(), entitlementPool.getName(), + entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId()); + entitlementPool.setVersionUuId(CommonMethods.nextUuId()); + entitlementPoolDao.update(entitlementPool); } - return licenseAgreement; - } - @Override - public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { - VersioningUtil.validateEntitiesExistence(featureGroup.getLicenseKeyGroupIds(), - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), - null), - licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); - VersioningUtil.validateEntitiesExistence(featureGroup.getEntitlementPoolIds(), - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), - null), - entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE); - uniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), - featureGroup.getName()); - - featureGroupDao.create(featureGroup); - uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), - featureGroup.getName()); + @Override + public Collection listLicenseKeyGroups(String vlmId, Version version) { + return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, version, null)); + } - if (featureGroup.getLicenseKeyGroupIds() != null) { - for (String addedLkgId : featureGroup.getLicenseKeyGroupIds()) { - licenseKeyGroupDao.addReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), addedLkgId), - featureGroup.getId()); - } + @Override + public Collection listEntitlementPools(String vlmId, Version version) { + return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, version, null)); } - if (featureGroup.getEntitlementPoolIds() != null) { - for (String addedEpId : featureGroup.getEntitlementPoolIds()) { - entitlementPoolDao.addReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion(), addedEpId), featureGroup.getId()); - } + @Override + public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); + if (retrieved.equals(licenseKeyGroup)) { + return; + } + licenseKeyGroup.setVersionUuId((CommonMethods.nextUuId())); + VersioningUtil.validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); + uniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, retrieved.getName(), licenseKeyGroup.getName(), + licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId()); + licenseKeyGroupDao.update(licenseKeyGroup); } - return featureGroup; - } - @Override - public Collection listFeatureGroups(String vlmId, Version version) { - return featureGroupDao.list(new FeatureGroupEntity(vlmId, version, null)); - } + @Override + public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { + licenseKeyGroup.setVersionUuId(CommonMethods.nextUuId()); + uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId(), licenseKeyGroup.getName()); + licenseKeyGroupDao.create(licenseKeyGroup); + return licenseKeyGroup; + } + @Override + public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { + VendorLicenseModelEntity vendorLicenseModel = vendorLicenseModelDao.get(new VendorLicenseModelEntity(vlmId, version)); + if (vendorLicenseModel == null) { + throw new CoreException(new VendorLicenseModelNotFoundErrorBuilder(vlmId).build()); + } + return vendorLicenseModel; + } - @Override - public Collection validateLicensingData(String vlmId, Version version, - String licenseAgreementId, - Collection featureGroupIds) { + @Override + public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { + VersioningUtil.validateEntitiesExistence(licenseAgreement.getFeatureGroupIds(), + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), null), featureGroupDao, + VendorLicenseModelEntity.ENTITY_TYPE); + uniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId(), licenseAgreement.getName()); + licenseAgreementDao.create(licenseAgreement); + uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId(), licenseAgreement.getName()); + if (licenseAgreement.getFeatureGroupIds() != null) { + for (String addedFgId : licenseAgreement.getFeatureGroupIds()) { + featureGroupDao.addReferencingLicenseAgreement( + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), addedFgId), + licenseAgreement.getId()); + } + } + return licenseAgreement; + } - List errorMessages = new ArrayList<>(); + @Override + public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { + VersioningUtil.validateEntitiesExistence(featureGroup.getLicenseKeyGroupIds(), + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), null), licenseKeyGroupDao, + VendorLicenseModelEntity.ENTITY_TYPE); + VersioningUtil.validateEntitiesExistence(featureGroup.getEntitlementPoolIds(), + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), null), entitlementPoolDao, + VendorLicenseModelEntity.ENTITY_TYPE); + uniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId(), featureGroup.getName()); + featureGroupDao.create(featureGroup); + uniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId(), featureGroup.getName()); + if (featureGroup.getLicenseKeyGroupIds() != null) { + for (String addedLkgId : featureGroup.getLicenseKeyGroupIds()) { + licenseKeyGroupDao.addReferencingFeatureGroup( + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), addedLkgId), featureGroup.getId()); + } + } + if (featureGroup.getEntitlementPoolIds() != null) { + for (String addedEpId : featureGroup.getEntitlementPoolIds()) { + entitlementPoolDao.addReferencingFeatureGroup( + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), addedEpId), featureGroup.getId()); + } + } + return featureGroup; + } - try { - getLicenseAgreement(vlmId, version, licenseAgreementId); - } catch (CoreException exception) { - errorMessages.add(exception.code()); + @Override + public Collection listFeatureGroups(String vlmId, Version version) { + return featureGroupDao.list(new FeatureGroupEntity(vlmId, version, null)); } - for (String featureGroupId : featureGroupIds) { - try { - FeatureGroupEntity featureGroup = - getFeatureGroup(new FeatureGroupEntity(vlmId, version, featureGroupId)); - if (!featureGroup.getReferencingLicenseAgreements().contains(licenseAgreementId)) { - errorMessages.add(new VersionableSubEntityNotFoundErrorBuilder( - featureGroup.getEntityType(), - featureGroupId, - LicenseAgreementEntity.ENTITY_TYPE, - licenseAgreementId, - version).build()); + @Override + public Collection validateLicensingData(String vlmId, Version version, String licenseAgreementId, Collection featureGroupIds) { + List errorMessages = new ArrayList<>(); + try { + getLicenseAgreement(vlmId, version, licenseAgreementId); + } catch (CoreException exception) { + errorMessages.add(exception.code()); } - } catch (CoreException exception) { - errorMessages.add(exception.code()); - } + for (String featureGroupId : featureGroupIds) { + try { + FeatureGroupEntity featureGroup = getFeatureGroup(new FeatureGroupEntity(vlmId, version, featureGroupId)); + if (!featureGroup.getReferencingLicenseAgreements().contains(licenseAgreementId)) { + errorMessages.add( + new VersionableSubEntityNotFoundErrorBuilder(featureGroup.getEntityType(), featureGroupId, LicenseAgreementEntity.ENTITY_TYPE, + licenseAgreementId, version).build()); + } + } catch (CoreException exception) { + errorMessages.add(exception.code()); + } + } + return errorMessages; } - return errorMessages; - } - @Override public Optional validateVendorForUsage(String vlmId, Version version) { Item vlm = ItemManagerFactory.getInstance().createInterface().get(vlmId); - return vlm == null - ? Optional.of(USED_VLM_NOT_EXIST_ERROR) - : ItemStatus.ARCHIVED == vlm.getStatus() - ? Optional.of(USED_VLM_ARCHIVE_ERROR) - : isDraftVlm(vlm, version) - ? Optional.of(USED_VLM_IS_DRAFT_ERROR) - : Optional.empty(); + return vlm == null ? Optional.of(USED_VLM_NOT_EXIST_ERROR) : ItemStatus.ARCHIVED == vlm.getStatus() ? Optional.of(USED_VLM_ARCHIVE_ERROR) + : isDraftVlm(vlm, version) ? Optional.of(USED_VLM_IS_DRAFT_ERROR) : Optional.empty(); } - private boolean isDraftVlm(Item vlm, Version version) { - return (version == null && isVlmWithoutCertifiedVersions(vlm)) || - (version != null && VersionStatus.Draft.equals(version.getStatus())); - } + private boolean isDraftVlm(Item vlm, Version version) { + return (version == null && isVlmWithoutCertifiedVersions(vlm)) || (version != null && VersionStatus.Draft.equals(version.getStatus())); + } - private boolean isVlmWithoutCertifiedVersions(Item vlm) { + private boolean isVlmWithoutCertifiedVersions(Item vlm) { Integer numOfCertifiedVersions = vlm.getVersionStatusCounters().get(VersionStatus.Certified); return numOfCertifiedVersions == null || numOfCertifiedVersions < 1; } @Override - public LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId) { - LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); - LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); - VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); - return retrieved; - } - - @Override - public Collection listLimits(String vlmId, Version version, String epLkgId) { - return limitDao.list(new LimitEntity(vlmId, version, epLkgId, null)); - } - - @Override - public LimitEntity createLimit(LimitEntity limit) { - limitDao.create(limit); - return limit; - } + public LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, String licenseAgreementId) { + LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); + LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); + VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); + return retrieved; + } - @Override - public void updateLimit(LimitEntity limit) { - limitDao.update(limit); - } + @Override + public Collection listLimits(String vlmId, Version version, String epLkgId) { + return limitDao.list(new LimitEntity(vlmId, version, epLkgId, null)); + } - @Override - public void validate(String vendorLicenseModelId, Version version) { - Collection allFeatureGroupEntities = new HashSet<>(); - Collection licenseAgreements = licenseAgreementDao - .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); + @Override + public LimitEntity createLimit(LimitEntity limit) { + limitDao.create(limit); + return limit; + } - if (CollectionUtils.isNotEmpty(licenseAgreements)) { - licenseAgreements.forEach(licenseAgreement -> { - if (CollectionUtils.isEmpty(licenseAgreement.getFeatureGroupIds())) { - throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder( - SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG).build()); - } - allFeatureGroupEntities.addAll(licenseAgreement.getFeatureGroupIds()); - }); + @Override + public void updateLimit(LimitEntity limit) { + limitDao.update(limit); + } - allFeatureGroupEntities.forEach(fg -> { - FeatureGroupEntity featureGroupEntity = - featureGroupDao.get(new FeatureGroupEntity(vendorLicenseModelId, version, fg)); - if (CollectionUtils.isEmpty(featureGroupEntity.getEntitlementPoolIds())) { - throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder( - SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP).build()); + @Override + public void validate(String vendorLicenseModelId, Version version) { + Collection allFeatureGroupEntities = new HashSet<>(); + Collection licenseAgreements = licenseAgreementDao + .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); + if (CollectionUtils.isNotEmpty(licenseAgreements)) { + licenseAgreements.forEach(licenseAgreement -> { + if (CollectionUtils.isEmpty(licenseAgreement.getFeatureGroupIds())) { + throw new CoreException(new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG).build()); + } + allFeatureGroupEntities.addAll(licenseAgreement.getFeatureGroupIds()); + }); + allFeatureGroupEntities.forEach(fg -> { + FeatureGroupEntity featureGroupEntity = featureGroupDao.get(new FeatureGroupEntity(vendorLicenseModelId, version, fg)); + if (CollectionUtils.isEmpty(featureGroupEntity.getEntitlementPoolIds())) { + throw new CoreException(new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP).build()); + } + }); } - }); } - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java index cc2f8acb97..75326b14d3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.healing.impl; +import java.util.UUID; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDaoFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; @@ -27,48 +27,40 @@ import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.util.UUID; - public class SimpleHealingServiceImpl implements HealingService { - private static final EntitlementPoolDao entitlementPoolDao = - EntitlementPoolDaoFactory.getInstance().createInterface(); - private static final LicenseKeyGroupDao licenseKeyGroupDao = - LicenseKeyGroupDaoFactory.getInstance().createInterface(); - private static final VersioningManager VERSIONING_MANAGER = - VersioningManagerFactory.getInstance().createInterface(); - @Override - public VersionableEntity heal(VersionableEntity toHeal) { - return handleMissingVersionId(toHeal); - } + private static final EntitlementPoolDao entitlementPoolDao = EntitlementPoolDaoFactory.getInstance().createInterface(); + private static final LicenseKeyGroupDao licenseKeyGroupDao = LicenseKeyGroupDaoFactory.getInstance().createInterface(); + private static final VersioningManager VERSIONING_MANAGER = VersioningManagerFactory.getInstance().createInterface(); - @Override - public void persistNoHealing(VersionableEntity alreadyHealed) { - if (alreadyHealed instanceof EntitlementPoolEntity) { - entitlementPoolDao.update((EntitlementPoolEntity) alreadyHealed); - } else if (alreadyHealed instanceof LicenseKeyGroupEntity) { - licenseKeyGroupDao.update((LicenseKeyGroupEntity) alreadyHealed); + @Override + public VersionableEntity heal(VersionableEntity toHeal) { + return handleMissingVersionId(toHeal); } - } - private VersionableEntity handleMissingVersionId(VersionableEntity toHeal) { - if (toHeal != null && toHeal.getVersionUuId() != null) { - return toHeal; + @Override + public void persistNoHealing(VersionableEntity alreadyHealed) { + if (alreadyHealed instanceof EntitlementPoolEntity) { + entitlementPoolDao.update((EntitlementPoolEntity) alreadyHealed); + } else if (alreadyHealed instanceof LicenseKeyGroupEntity) { + licenseKeyGroupDao.update((LicenseKeyGroupEntity) alreadyHealed); + } } - if (toHeal instanceof EntitlementPoolEntity) { - toHeal.setVersionUuId(UUID.randomUUID().toString()); - entitlementPoolDao.update((EntitlementPoolEntity) toHeal); - } else if (toHeal instanceof LicenseKeyGroupEntity) { - toHeal.setVersionUuId(UUID.randomUUID().toString()); - licenseKeyGroupDao.update((LicenseKeyGroupEntity) toHeal); - } else { - throw new UnsupportedOperationException( - "Unsupported operation for 1610 release/1607->1610 migration."); + private VersionableEntity handleMissingVersionId(VersionableEntity toHeal) { + if (toHeal != null && toHeal.getVersionUuId() != null) { + return toHeal; + } + if (toHeal instanceof EntitlementPoolEntity) { + toHeal.setVersionUuId(UUID.randomUUID().toString()); + entitlementPoolDao.update((EntitlementPoolEntity) toHeal); + } else if (toHeal instanceof LicenseKeyGroupEntity) { + toHeal.setVersionUuId(UUID.randomUUID().toString()); + licenseKeyGroupDao.update((LicenseKeyGroupEntity) toHeal); + } else { + throw new UnsupportedOperationException("Unsupported operation for 1610 release/1607->1610 migration."); + } + VERSIONING_MANAGER.publish(toHeal.getFirstClassCitizenId(), toHeal.getVersion(), "Add missing version_uuid on ep/lkg"); + return toHeal; } - - VERSIONING_MANAGER.publish(toHeal.getFirstClassCitizenId(), toHeal.getVersion(), "Add missing version_uuid on ep/lkg"); - - return toHeal; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java index f0f8a6cb7c..7b5902e08f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java @@ -13,9 +13,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl; +import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH; +import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VNF_ARTIFACT_NAME_WITH_PATH; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.filterChangedEntities; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.getFinalVersionsForVlm; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.getVendorName; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.healEPs; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.healLkgs; +import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.prepareForFiltering; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.core.utilities.file.FileContentHandler; @@ -32,155 +47,105 @@ import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.VendorLicense import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.VnfLicenseArtifact; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VNF_ARTIFACT_NAME_WITH_PATH; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.filterChangedEntities; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.getFinalVersionsForVlm; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.getVendorName; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.healEPs; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.healLkgs; -import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorLicenseArtifactsServiceUtils.prepareForFiltering; - public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifactsService { - public static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); - public static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); - private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, String vendorName, - List featureGroups) { - VnfLicenseArtifact artifact = new VnfLicenseArtifact(); - - artifact.setVspId(vspId); - artifact.setVendorName(vendorName); - if (featureGroups != null) { - for (String featureGroupId : featureGroups) { - FeatureGroupModel featureGroupModel = vendorLicenseFacade - .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId)); - Set entitlementPoolEntities = - featureGroupModel.getEntitlementPools(); - String manufacturerReferenceNumber = featureGroupModel.getEntityManufacturerReferenceNumber(); - for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { - entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - entitlementPoolEntity.getId())); - if (Objects.nonNull(manufacturerReferenceNumber) && !manufacturerReferenceNumber.trim().isEmpty()) { - entitlementPoolEntity.setManufacturerReferenceNumber(manufacturerReferenceNumber); - } + public static final VendorLicenseFacade vendorLicenseFacade = VendorLicenseFacadeFactory.getInstance().createInterface(); + public static final HealingService healingService = HealingServiceFactory.getInstance().createInterface(); + + private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, String vendorName, List featureGroups) { + VnfLicenseArtifact artifact = new VnfLicenseArtifact(); + artifact.setVspId(vspId); + artifact.setVendorName(vendorName); + if (featureGroups != null) { + for (String featureGroupId : featureGroups) { + FeatureGroupModel featureGroupModel = vendorLicenseFacade + .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId)); + Set entitlementPoolEntities = featureGroupModel.getEntitlementPools(); + String manufacturerReferenceNumber = featureGroupModel.getEntityManufacturerReferenceNumber(); + for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { + entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, entitlementPoolEntity.getId())); + if (Objects.nonNull(manufacturerReferenceNumber) && !manufacturerReferenceNumber.trim().isEmpty()) { + entitlementPoolEntity.setManufacturerReferenceNumber(manufacturerReferenceNumber); + } + } + Set licenseKeyGroupEntities = featureGroupModel.getLicenseKeyGroups(); + for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { + licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, licenseKeyGroupEntity.getId())); + if (Objects.nonNull(manufacturerReferenceNumber) && !manufacturerReferenceNumber.trim().isEmpty()) { + licenseKeyGroupEntity.setManufacturerReferenceNumber(manufacturerReferenceNumber); + } + } + featureGroupModel.setEntitlementPools( + entitlementPoolEntities.stream().map(entitlementPoolEntity -> (EntitlementPoolEntity) healingService.heal(entitlementPoolEntity)) + .collect(Collectors.toSet())); + featureGroupModel.setLicenseKeyGroups( + licenseKeyGroupEntities.stream().map(licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService.heal(licenseKeyGroupEntity)) + .collect(Collectors.toSet())); + artifact.getFeatureGroups().add(featureGroupModel); + } } + return artifact.toXml().getBytes(); + } - Set licenseKeyGroupEntities = - featureGroupModel.getLicenseKeyGroups(); - for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { - licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - licenseKeyGroupEntity.getId())); - if (Objects.nonNull(manufacturerReferenceNumber) && !manufacturerReferenceNumber.trim().isEmpty()) { - licenseKeyGroupEntity.setManufacturerReferenceNumber(manufacturerReferenceNumber); - } + private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName) { + VendorLicenseArtifact vendorLicenseArtifact = new VendorLicenseArtifact(); + vendorLicenseArtifact.setVendorName(vendorName); + Set entitlementPoolEntities = new HashSet<>(); + Set licenseKeyGroupEntities = new HashSet<>(); + List finalVersions = getFinalVersionsForVlm(vlmId); + for (Version finalVersion : finalVersions) { + Collection eps = vendorLicenseFacade.listEntitlementPools(vlmId, finalVersion); + eps.forEach(entitlementPoolEntity -> { + entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, entitlementPoolEntity.getId())); + Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber( + entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion); + manufacturerReferenceNumber.ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); + }); + entitlementPoolEntities.addAll(eps); + Collection lkgs = vendorLicenseFacade.listLicenseKeyGroups(vlmId, finalVersion); + lkgs.forEach(licenseKeyGroupEntity -> { + licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, licenseKeyGroupEntity.getId())); + Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber( + licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion); + manufacturerReferenceNumber.ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); + }); + licenseKeyGroupEntities.addAll(lkgs); } - - featureGroupModel.setEntitlementPools(entitlementPoolEntities.stream().map( - entitlementPoolEntity -> (EntitlementPoolEntity) healingService - .heal(entitlementPoolEntity)).collect(Collectors.toSet())); - featureGroupModel.setLicenseKeyGroups(licenseKeyGroupEntities.stream().map( - licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService - .heal(licenseKeyGroupEntity)).collect(Collectors.toSet())); - artifact.getFeatureGroups().add(featureGroupModel); - } + entitlementPoolEntities = healEPs(filterChangedEntities(prepareForFiltering(entitlementPoolEntities, true))); + licenseKeyGroupEntities = healLkgs(filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, false))); + vendorLicenseArtifact.setEntitlementPoolEntities(entitlementPoolEntities); + vendorLicenseArtifact.setLicenseKeyGroupEntities(licenseKeyGroupEntities); + return vendorLicenseArtifact.toXml().getBytes(); } - return artifact.toXml().getBytes(); - } - - private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName) { - VendorLicenseArtifact vendorLicenseArtifact = new VendorLicenseArtifact(); - vendorLicenseArtifact.setVendorName(vendorName); - Set entitlementPoolEntities = new HashSet<>(); - Set licenseKeyGroupEntities = new HashSet<>(); - - List finalVersions = getFinalVersionsForVlm(vlmId); - for (Version finalVersion : finalVersions) { - Collection eps = - vendorLicenseFacade.listEntitlementPools(vlmId, finalVersion); - eps.forEach(entitlementPoolEntity -> { - entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - entitlementPoolEntity.getId())); - Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion); - manufacturerReferenceNumber - .ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); - }); - entitlementPoolEntities.addAll(eps); - Collection lkgs = - vendorLicenseFacade.listLicenseKeyGroups(vlmId, finalVersion); - - lkgs.forEach(licenseKeyGroupEntity -> { - licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - licenseKeyGroupEntity.getId())); - Optional manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion); - manufacturerReferenceNumber - .ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); - }); - licenseKeyGroupEntities.addAll(lkgs); + private static Optional getFeatureGroupManufactureRefNumber(Set featureGroupIds, String vlmId, Version finalVersion) { + String manufactureReferenceNumber = null; + if (CollectionUtils.isNotEmpty(featureGroupIds)) { + Object[] featureGroupIdsList = featureGroupIds.toArray(); + if (featureGroupIdsList.length > 0) { + FeatureGroupEntity featureGroup = vendorLicenseFacade + .getFeatureGroup(new FeatureGroupEntity(vlmId, finalVersion, featureGroupIdsList[0].toString())); + manufactureReferenceNumber = featureGroup != null ? featureGroup.getManufacturerReferenceNumber() : null; + } + } + return StringUtils.isNotEmpty(manufactureReferenceNumber) ? Optional.of(manufactureReferenceNumber) : Optional.empty(); } - - entitlementPoolEntities = - healEPs(filterChangedEntities(prepareForFiltering(entitlementPoolEntities, true))); - licenseKeyGroupEntities = - healLkgs(filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, false))); - vendorLicenseArtifact.setEntitlementPoolEntities(entitlementPoolEntities); - vendorLicenseArtifact.setLicenseKeyGroupEntities(licenseKeyGroupEntities); - return vendorLicenseArtifact.toXml().getBytes(); - } - - private static Optional getFeatureGroupManufactureRefNumber(Set featureGroupIds, - String vlmId, - Version finalVersion) { - String manufactureReferenceNumber = null; - if (CollectionUtils.isNotEmpty(featureGroupIds)) { - Object[] featureGroupIdsList = featureGroupIds.toArray(); - if (featureGroupIdsList.length > 0) { - FeatureGroupEntity featureGroup = - vendorLicenseFacade.getFeatureGroup(new FeatureGroupEntity(vlmId, finalVersion, - featureGroupIdsList[0].toString())); - manufactureReferenceNumber = featureGroup != null ? featureGroup - .getManufacturerReferenceNumber() : null; - } + /** + * Create License Artifacts. + * + * @param vspId vspId + * @param vlmId vlmId + * @param vlmVersion vlmVersion + * @param featureGroups featureGroups + * @return FileContentHandler + */ + @Override + public FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, List featureGroups) { + FileContentHandler artifacts = new FileContentHandler(); + String vendorName = getVendorName(vlmId); + artifacts.addFile(VNF_ARTIFACT_NAME_WITH_PATH, createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups)); + artifacts.addFile(VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH, createVendorLicenseArtifact(vlmId, vendorName)); + return artifacts; } - return StringUtils.isNotEmpty(manufactureReferenceNumber) ? Optional.of(manufactureReferenceNumber) : - Optional.empty(); - } - - - /** - * Create License Artifacts. - * - * @param vspId vspId - * @param vlmId vlmId - * @param vlmVersion vlmVersion - * @param featureGroups featureGroups - * @return FileContentHandler - */ - @Override - public FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List featureGroups) { - FileContentHandler artifacts = new FileContentHandler(); - String vendorName = getVendorName(vlmId); - - artifacts.addFile(VNF_ARTIFACT_NAME_WITH_PATH, - createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups)); - artifacts.addFile(VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH, - createVendorLicenseArtifact(vlmId, vendorName)); - return artifacts; - } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VendorLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VendorLicenseArtifact.java index afc1d3151b..a805b75587 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VendorLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VendorLicenseArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import java.util.Collection; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; @@ -31,53 +31,47 @@ import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinE import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLicenseKeyGroupEntityForVendorLicenseArtifact; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLimitArtifact; -import java.util.Collection; - @JacksonXmlRootElement(localName = "vendor-license-model", namespace = "http://xmlns.openecomp.org/asdc/license-model/1.0") public class VendorLicenseArtifact extends XmlArtifact { - @JsonProperty(value = "vendor-name") - String vendorName; - Collection entitlementPoolEntities; - Collection licenseKeyGroupEntities; + @JsonProperty(value = "vendor-name") + String vendorName; + Collection entitlementPoolEntities; + Collection licenseKeyGroupEntities; - public String getVendorName() { - return vendorName; - } + public String getVendorName() { + return vendorName; + } - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } - @JacksonXmlProperty(isAttribute = false, localName = "entitlement-pool") - @JacksonXmlElementWrapper(localName = "entitlement-pool-list") - public Collection getEntitlementPoolEntities() { - return entitlementPoolEntities; - } + @JacksonXmlProperty(isAttribute = false, localName = "entitlement-pool") + @JacksonXmlElementWrapper(localName = "entitlement-pool-list") + public Collection getEntitlementPoolEntities() { + return entitlementPoolEntities; + } - public void setEntitlementPoolEntities( - Collection entitlementPoolEntities) { - this.entitlementPoolEntities = entitlementPoolEntities; - } + public void setEntitlementPoolEntities(Collection entitlementPoolEntities) { + this.entitlementPoolEntities = entitlementPoolEntities; + } - @JacksonXmlProperty(isAttribute = false, localName = "license-key-group") - @JacksonXmlElementWrapper(localName = "license-key-group-list") - public Collection getLicenseKeyGroupEntities() { - return licenseKeyGroupEntities; - } + @JacksonXmlProperty(isAttribute = false, localName = "license-key-group") + @JacksonXmlElementWrapper(localName = "license-key-group-list") + public Collection getLicenseKeyGroupEntities() { + return licenseKeyGroupEntities; + } - public void setLicenseKeyGroupEntities( - Collection licenseKeyGroupEntities) { - this.licenseKeyGroupEntities = licenseKeyGroupEntities; - } + public void setLicenseKeyGroupEntities(Collection licenseKeyGroupEntities) { + this.licenseKeyGroupEntities = licenseKeyGroupEntities; + } - @Override - void initMapper() { - xmlMapper.addMixIn(EntitlementPoolEntity.class, - MixinEntitlementPoolEntityForVendorLicenseArtifact.class); - xmlMapper.addMixIn(LicenseKeyGroupEntity.class, - MixinLicenseKeyGroupEntityForVendorLicenseArtifact.class); - xmlMapper.addMixIn(LimitXml.class, MixinLimitArtifact.class); - } + @Override + void initMapper() { + xmlMapper.addMixIn(EntitlementPoolEntity.class, MixinEntitlementPoolEntityForVendorLicenseArtifact.class); + xmlMapper.addMixIn(LicenseKeyGroupEntity.class, MixinLicenseKeyGroupEntityForVendorLicenseArtifact.class); + xmlMapper.addMixIn(LimitXml.class, MixinLimitArtifact.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java index 91a73b6377..1686b9631d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types; import com.ctc.wstx.api.WstxInputProperties; @@ -29,6 +28,11 @@ import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; @@ -38,63 +42,55 @@ import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinF import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLicenseKeyGroupEntityForVnfArtifact; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLimitArtifact; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; - @JacksonXmlRootElement(localName = "vf-license-model", namespace = "http://xmlns.openecomp.org/asdc/license-model/1.0") public class VnfLicenseArtifact extends XmlArtifact { - @JsonProperty(value = "vendor-name") - String vendorName; - @JsonProperty(value = "vf-id") - String vspId; - List featureGroups = new ArrayList<>(); - - public String getVspId() { - return vspId; - } - - public void setVspId(String vspId) { - this.vspId = vspId; - } - public String getVendorName() { - return vendorName; - } + @JsonProperty(value = "vendor-name") + String vendorName; + @JsonProperty(value = "vf-id") + String vspId; + List featureGroups = new ArrayList<>(); - public void setVendorName(String vendorName) { - this.vendorName = vendorName; - } + public String getVspId() { + return vspId; + } - @JacksonXmlProperty(isAttribute = false, localName = "feature-group") - @JacksonXmlElementWrapper(localName = "feature-group-list") - public List getFeatureGroups() { - return featureGroups; - } + public void setVspId(String vspId) { + this.vspId = vspId; + } - public void setFeatureGroups(List featureGroups) { - this.featureGroups = featureGroups; - } + public String getVendorName() { + return vendorName; + } - void initMapper() { - WstxOutputFactory wstxOutputFactory = new WstxOutputFactory() { - @Override - public XMLStreamWriter createXMLStreamWriter(Writer writer) throws XMLStreamException { - mConfig.setProperty(WstxInputProperties.P_RETURN_NULL_FOR_DEFAULT_NAMESPACE, true); - return super.createXMLStreamWriter(writer); - } - }; - XmlFactory factory = new XmlFactory(new WstxInputFactory(), wstxOutputFactory); + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } - xmlMapper = new XmlMapper(factory); + @JacksonXmlProperty(isAttribute = false, localName = "feature-group") + @JacksonXmlElementWrapper(localName = "feature-group-list") + public List getFeatureGroups() { + return featureGroups; + } + public void setFeatureGroups(List featureGroups) { + this.featureGroups = featureGroups; + } - xmlMapper.addMixIn(EntitlementPoolEntity.class, MixinEntitlementPoolEntityForVnfArtifact.class); - xmlMapper.addMixIn(LicenseKeyGroupEntity.class, MixinLicenseKeyGroupEntityForVnfArtifact.class); - xmlMapper.addMixIn(FeatureGroupModel.class, MixinFeatureGroupModel.class); - xmlMapper.addMixIn(LimitXml.class, MixinLimitArtifact.class); - } + void initMapper() { + WstxOutputFactory wstxOutputFactory = new WstxOutputFactory() { + @Override + public XMLStreamWriter createXMLStreamWriter(Writer writer) throws XMLStreamException { + mConfig.setProperty(WstxInputProperties.P_RETURN_NULL_FOR_DEFAULT_NAMESPACE, true); + return super.createXMLStreamWriter(writer); + } + }; + XmlFactory factory = new XmlFactory(new WstxInputFactory(), wstxOutputFactory); + xmlMapper = new XmlMapper(factory); + xmlMapper.addMixIn(EntitlementPoolEntity.class, MixinEntitlementPoolEntityForVnfArtifact.class); + xmlMapper.addMixIn(LicenseKeyGroupEntity.class, MixinLicenseKeyGroupEntityForVnfArtifact.class); + xmlMapper.addMixIn(FeatureGroupModel.class, MixinFeatureGroupModel.class); + xmlMapper.addMixIn(LimitXml.class, MixinLimitArtifact.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/XmlArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/XmlArtifact.java index 7052d6afb6..dc5089f57a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/XmlArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/XmlArtifact.java @@ -12,8 +12,7 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types; import com.fasterxml.jackson.dataformat.xml.XmlMapper; @@ -23,28 +22,23 @@ import org.openecomp.sdc.vendorlicense.errors.JsonErrorBuilder; public abstract class XmlArtifact { - XmlMapper xmlMapper = new XmlMapper(); - - abstract void initMapper(); - - /** - * To xml string. - * - * @return the string - */ - public String toXml() { - initMapper(); - String xml; - - try { - xml = xmlMapper.writeValueAsString(this); - } catch (com.fasterxml.jackson.core.JsonProcessingException exception) { - throw new CoreException(new JsonErrorBuilder("Failed to write xml value as string ") - .build(), exception); + XmlMapper xmlMapper = new XmlMapper(); + + abstract void initMapper(); + + /** + * To xml string. + * + * @return the string + */ + public String toXml() { + initMapper(); + String xml; + try { + xml = xmlMapper.writeValueAsString(this); + } catch (com.fasterxml.jackson.core.JsonProcessingException exception) { + throw new CoreException(new JsonErrorBuilder("Failed to write xml value as string ").build(), exception); + } + return xml.replaceAll(VendorLicenseConstants.VENDOR_LICENSE_MODEL_ARTIFACT_REGEX_REMOVE, ""); } - - return xml.replaceAll(VendorLicenseConstants.VENDOR_LICENSE_MODEL_ARTIFACT_REGEX_REMOVE, ""); - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java index 5afd0a9ab1..55301c9b7f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,98 +17,104 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.openecomp.sdc.vendorlicense.dao.types.*; -import org.openecomp.sdc.vendorlicense.dao.types.xml.*; - import java.util.Collection; import java.util.Set; - -@JsonPropertyOrder({ "entitlement-pool-invariant-uuid", "entitlement-pool-uuid" }) +import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; +import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementMetric; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementTime; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.xml.AggregationFunctionForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.EntitlementMetricForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.EntitlementTimeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; + +@JsonPropertyOrder({"entitlement-pool-invariant-uuid", "entitlement-pool-uuid"}) public abstract class MixinEntitlementPoolEntityForVendorLicenseArtifact { - @JsonProperty(value = "threshold-value") - abstract ThresholdForXml getThresholdForArtifact(); - - @JsonProperty(value = "entitlement-pool-uuid") - abstract String getVersionUuId(); - - @JsonIgnore - abstract Set getReferencingFeatureGroups(); - @JsonIgnore - abstract String getFirstClassCitizenId(); + @JsonProperty(value = "threshold-value") + abstract ThresholdForXml getThresholdForArtifact(); - @JsonProperty(value = "entitlement-pool-invariant-uuid") - abstract String getId(); + @JsonProperty(value = "entitlement-pool-uuid") + abstract String getVersionUuId(); - @JsonProperty(value = "manufacturer-reference-number") - abstract String getManufacturerReferenceNumber(); + @JsonIgnore + abstract Set getReferencingFeatureGroups(); - @JsonProperty(value = "version") - abstract String getVersionForArtifact(); + @JsonIgnore + abstract String getFirstClassCitizenId(); - @JsonIgnore - abstract String getStartDate(); + @JsonProperty(value = "entitlement-pool-invariant-uuid") + abstract String getId(); - @JsonIgnore - abstract String getExpiryDate(); + @JsonProperty(value = "manufacturer-reference-number") + abstract String getManufacturerReferenceNumber(); - @JsonProperty(value = "start-date") - abstract String getIsoFormatStartDate(); + @JsonProperty(value = "version") + abstract String getVersionForArtifact(); - @JsonProperty(value = "expiry-date") - abstract String getIsoFormatExpiryDate(); + @JsonIgnore + abstract String getStartDate(); - @JsonIgnore - abstract String getVendorLicenseModelId(); + @JsonIgnore + abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); - @JsonIgnore - abstract String getThresholdUnit(); + @JsonIgnore + abstract String getVendorLicenseModelId(); - @JsonIgnore - abstract float getThresholdValue(); + @JsonIgnore + abstract String getThresholdUnit(); - @JsonIgnore - abstract ChoiceOrOther getEntitlementMetric(); + @JsonIgnore + abstract float getThresholdValue(); - @JsonIgnore - abstract ChoiceOrOther getTime(); + @JsonIgnore + abstract ChoiceOrOther getEntitlementMetric(); - @JsonIgnore - abstract ChoiceOrOther getAggregationFunction(); + @JsonIgnore + abstract ChoiceOrOther getTime(); - @JsonIgnore - abstract String getEntityType(); + @JsonIgnore + abstract ChoiceOrOther getAggregationFunction(); - @JsonProperty(value = "operational-scope") - abstract OperationalScopeForXml getOperationalScopeForArtifact(); + @JsonIgnore + abstract String getEntityType(); - @JsonIgnore - abstract ChoiceOrOther getOperationalScope(); + @JsonProperty(value = "operational-scope") + abstract OperationalScopeForXml getOperationalScopeForArtifact(); - @JsonProperty(value = "entitlement-metric") - abstract EntitlementMetricForXml getEntitlementMetricForArtifact(); + @JsonIgnore + abstract ChoiceOrOther getOperationalScope(); - @JsonProperty(value = "time") - abstract EntitlementTimeForXml getTimeForArtifact(); + @JsonProperty(value = "entitlement-metric") + abstract EntitlementMetricForXml getEntitlementMetricForArtifact(); + @JsonProperty(value = "time") + abstract EntitlementTimeForXml getTimeForArtifact(); - @JsonProperty(value = "aggregation-function") - abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); + @JsonProperty(value = "aggregation-function") + abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); - @JsonProperty(value = "sp-limits") - abstract LimitForXml getSPLimits(); + @JsonProperty(value = "sp-limits") + abstract LimitForXml getSPLimits(); - @JsonProperty(value = "vendor-limits") - abstract LimitForXml getVendorLimits(); + @JsonProperty(value = "vendor-limits") + abstract LimitForXml getVendorLimits(); - @JsonIgnore - abstract Collection getLimits(); + @JsonIgnore + abstract Collection getLimits(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java index 32ac6fb532..95dd28ada2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,99 +17,105 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; -import org.openecomp.sdc.vendorlicense.dao.types.*; -import org.openecomp.sdc.vendorlicense.dao.types.xml.*; - import java.util.Collection; import java.util.Set; +import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; +import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementMetric; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementTime; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.xml.AggregationFunctionForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.EntitlementMetricForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.EntitlementTimeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; public abstract class MixinEntitlementPoolEntityForVnfArtifact { - @JsonProperty(value = "threshold-value") - abstract ThresholdForXml getThresholdForArtifact(); - - @JsonProperty(value = "entitlement-pool-invariant-uuid") - abstract String getId(); - - @JsonProperty(value = "manufacturer-reference-number") - abstract String getManufacturerReferenceNumber(); - @JsonIgnore - abstract Set getReferencingFeatureGroups(); + @JsonProperty(value = "threshold-value") + abstract ThresholdForXml getThresholdForArtifact(); - @JsonIgnore - abstract String getFirstClassCitizenId(); + @JsonProperty(value = "entitlement-pool-invariant-uuid") + abstract String getId(); - @JsonProperty(value = "entitlement-pool-uuid") - abstract String getVersionUuId(); + @JsonProperty(value = "manufacturer-reference-number") + abstract String getManufacturerReferenceNumber(); - @JsonIgnore - abstract String getVersion(); + @JsonIgnore + abstract Set getReferencingFeatureGroups(); - @JsonProperty(value = "version") - abstract String getVersionForArtifact(); + @JsonIgnore + abstract String getFirstClassCitizenId(); - @JsonIgnore - abstract String getVendorLicenseModelId(); + @JsonProperty(value = "entitlement-pool-uuid") + abstract String getVersionUuId(); - @JsonIgnore - abstract String getThresholdUnit(); + @JsonIgnore + abstract String getVersion(); - @JsonIgnore - abstract float getThresholdValue(); + @JsonProperty(value = "version") + abstract String getVersionForArtifact(); - @JsonIgnore - abstract String getStartDate(); + @JsonIgnore + abstract String getVendorLicenseModelId(); - @JsonIgnore - abstract String getExpiryDate(); + @JsonIgnore + abstract String getThresholdUnit(); - @JsonProperty(value = "start-date") - abstract String getIsoFormatStartDate(); + @JsonIgnore + abstract float getThresholdValue(); - @JsonProperty(value = "expiry-date") - abstract String getIsoFormatExpiryDate(); + @JsonIgnore + abstract String getStartDate(); - @JsonIgnore - abstract ChoiceOrOther getEntitlementMetric(); + @JsonIgnore + abstract String getExpiryDate(); - @JsonIgnore - abstract ChoiceOrOther getTime(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); - @JsonIgnore - abstract ChoiceOrOther getAggregationFunction(); + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); - @JsonIgnore - abstract String getEntityType(); + @JsonIgnore + abstract ChoiceOrOther getEntitlementMetric(); - @JsonProperty(value = "operational-scope") - abstract OperationalScopeForXml getOperationalScopeForArtifact(); + @JsonIgnore + abstract ChoiceOrOther getTime(); - @JsonIgnore - abstract ChoiceOrOther getOperationalScope(); + @JsonIgnore + abstract ChoiceOrOther getAggregationFunction(); + @JsonIgnore + abstract String getEntityType(); - @JsonProperty(value = "entitlement-metric") - abstract EntitlementMetricForXml getEntitlementMetricForArtifact(); + @JsonProperty(value = "operational-scope") + abstract OperationalScopeForXml getOperationalScopeForArtifact(); - @JsonProperty(value = "time") - abstract EntitlementTimeForXml getTimeForArtifact(); + @JsonIgnore + abstract ChoiceOrOther getOperationalScope(); + @JsonProperty(value = "entitlement-metric") + abstract EntitlementMetricForXml getEntitlementMetricForArtifact(); - @JsonProperty(value = "aggregation-function") - abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); + @JsonProperty(value = "time") + abstract EntitlementTimeForXml getTimeForArtifact(); - @JsonProperty(value = "sp-limits") - abstract LimitForXml getSPLimits(); + @JsonProperty(value = "aggregation-function") + abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); - @JsonProperty(value = "vendor-limits") - abstract LimitForXml getVendorLimits(); + @JsonProperty(value = "sp-limits") + abstract LimitForXml getSPLimits(); - @JsonIgnore - abstract Collection getLimits(); + @JsonProperty(value = "vendor-limits") + abstract LimitForXml getVendorLimits(); + @JsonIgnore + abstract Collection getLimits(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupEntity.java index 61751b111b..970290b25a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.util.Set; +import org.openecomp.sdc.versioning.dao.types.Version; public abstract class MixinFeatureGroupEntity { - @JsonIgnore - abstract String getVendorLicenseModelId(); - - @JsonIgnore - abstract String getEntityType(); - - - @JsonIgnore - abstract Version getVersion(); + @JsonIgnore + abstract String getVendorLicenseModelId(); - @JsonIgnore - abstract String getId(); + @JsonIgnore + abstract String getEntityType(); - @JsonIgnore - abstract String getName(); + @JsonIgnore + abstract Version getVersion(); - @JsonIgnore - abstract String getDescription(); + @JsonIgnore + abstract String getId(); - @JsonIgnore - abstract String getPartNumber(); + @JsonIgnore + abstract String getName(); - @JsonIgnore - abstract String getManufacturerReferenceNumber(); + @JsonIgnore + abstract String getDescription(); - @JsonIgnore - abstract Set getLicenseKeyGroupIds(); + @JsonIgnore + abstract String getPartNumber(); - @JsonIgnore - abstract Set getEntitlementPoolIds(); + @JsonIgnore + abstract String getManufacturerReferenceNumber(); + @JsonIgnore + abstract Set getLicenseKeyGroupIds(); - @JsonIgnore - abstract Set getReferencingLicenseAgreements(); + @JsonIgnore + abstract Set getEntitlementPoolIds(); + @JsonIgnore + abstract Set getReferencingLicenseAgreements(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupModel.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupModel.java index b8c45ba4c6..45feb365e5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupModel.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinFeatureGroupModel.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,48 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; +import java.util.Set; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import java.util.Set; - public abstract class MixinFeatureGroupModel { - @JacksonXmlProperty(isAttribute = false, localName = "entitlement-pool") - @JacksonXmlElementWrapper(localName = "entitlement-pool-list") - abstract Set getEntitlementPools(); - - @JacksonXmlProperty(isAttribute = false, localName = "license-key-group") - @JacksonXmlElementWrapper(localName = "license-key-group-list") - abstract Set getLicenseKeyGroups(); - - @JacksonXmlProperty(isAttribute = false, localName = "part-number") - abstract String getEntityPartNumber(); - @JacksonXmlProperty(isAttribute = false, localName = "feature-group-uuid") - abstract String getEntityId(); + @JacksonXmlProperty(isAttribute = false, localName = "entitlement-pool") + @JacksonXmlElementWrapper(localName = "entitlement-pool-list") + abstract Set getEntitlementPools(); - @JacksonXmlProperty(isAttribute = false, localName = "description") - abstract String getEntityDesc(); + @JacksonXmlProperty(isAttribute = false, localName = "license-key-group") + @JacksonXmlElementWrapper(localName = "license-key-group-list") + abstract Set getLicenseKeyGroups(); - @JacksonXmlProperty(isAttribute = false, localName = "name") - abstract String getEntityName(); + @JacksonXmlProperty(isAttribute = false, localName = "part-number") + abstract String getEntityPartNumber(); + @JacksonXmlProperty(isAttribute = false, localName = "feature-group-uuid") + abstract String getEntityId(); - @JsonIgnore - abstract FeatureGroupEntity getFeatureGroup(); + @JacksonXmlProperty(isAttribute = false, localName = "description") + abstract String getEntityDesc(); - @JsonIgnore - abstract String getEntityType(); + @JacksonXmlProperty(isAttribute = false, localName = "name") + abstract String getEntityName(); - @JsonIgnore - abstract String getEntityManufacturerReferenceNumber(); + @JsonIgnore + abstract FeatureGroupEntity getFeatureGroup(); + @JsonIgnore + abstract String getEntityType(); + @JsonIgnore + abstract String getEntityManufacturerReferenceNumber(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java index eeaa7c0a3a..03bc6c83ad 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import java.util.Set; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; @@ -30,74 +31,68 @@ import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; -import java.util.Collection; -import java.util.Set; - public abstract class MixinLicenseKeyGroupEntityForVendorLicenseArtifact { - @JsonProperty(value = "license-key-group-uuid") - abstract String getVersionUuId(); - - @JsonIgnore - abstract Set getReferencingFeatureGroups(); - - @JsonProperty(value = "version") - abstract String getVersionForArtifact(); - - @JsonIgnore - abstract String getVendorLicenseModelId(); + @JsonProperty(value = "license-key-group-uuid") + abstract String getVersionUuId(); - @JsonIgnore - abstract String getEntityType(); + @JsonIgnore + abstract Set getReferencingFeatureGroups(); - @JsonIgnore - abstract String getFirstClassCitizenId(); + @JsonProperty(value = "version") + abstract String getVersionForArtifact(); - @JsonProperty(value = "license-key-group-invariant-uuid") - abstract String getId(); + @JsonIgnore + abstract String getVendorLicenseModelId(); + @JsonIgnore + abstract String getEntityType(); - @JsonIgnore - abstract ChoiceOrOther getOperationalScope(); + @JsonIgnore + abstract String getFirstClassCitizenId(); - @JsonProperty(value = "operational-scope") - abstract OperationalScopeForXml getOperationalScopeForArtifact(); + @JsonProperty(value = "license-key-group-invariant-uuid") + abstract String getId(); + @JsonIgnore + abstract ChoiceOrOther getOperationalScope(); - @JsonIgnore - abstract LicenseKeyTypeForXml getTypeForArtifact(); + @JsonProperty(value = "operational-scope") + abstract OperationalScopeForXml getOperationalScopeForArtifact(); - @JsonIgnore - abstract String getVersionableId(); + @JsonIgnore + abstract LicenseKeyTypeForXml getTypeForArtifact(); - @JsonProperty(value = "sp-limits") - abstract LimitForXml getSPLimits(); + @JsonIgnore + abstract String getVersionableId(); - @JsonProperty(value = "vendor-limits") - abstract LimitForXml getVendorLimits(); + @JsonProperty(value = "sp-limits") + abstract LimitForXml getSPLimits(); - @JsonIgnore - abstract Collection getLimits(); + @JsonProperty(value = "vendor-limits") + abstract LimitForXml getVendorLimits(); - @JsonIgnore - abstract String getStartDate(); + @JsonIgnore + abstract Collection getLimits(); - @JsonIgnore - abstract String getExpiryDate(); + @JsonIgnore + abstract String getStartDate(); - @JsonProperty(value = "start-date") - abstract String getIsoFormatStartDate(); + @JsonIgnore + abstract String getExpiryDate(); - @JsonProperty(value = "expiry-date") - abstract String getIsoFormatExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); - @JsonProperty(value = "threshold-value") - abstract ThresholdForXml getThresholdForArtifact(); + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); - @JsonIgnore - abstract String getThresholdUnits(); + @JsonProperty(value = "threshold-value") + abstract ThresholdForXml getThresholdForArtifact(); - @JsonIgnore - abstract float getThresholdValue(); + @JsonIgnore + abstract String getThresholdUnits(); + @JsonIgnore + abstract float getThresholdValue(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java index f560f363a1..c9e21806ce 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Collection; +import java.util.Set; import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; @@ -30,78 +31,74 @@ import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; -import java.util.Collection; -import java.util.Set; - public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { - @JsonProperty(value = "license-key-group-invariant-uuid") - abstract String getId(); - - @JsonProperty(value = "manufacturer-reference-number") - abstract String getManufacturerReferenceNumber(); - @JsonIgnore - abstract Set getReferencingFeatureGroups(); + @JsonProperty(value = "license-key-group-invariant-uuid") + abstract String getId(); - @JsonIgnore - abstract String getVersion(); + @JsonProperty(value = "manufacturer-reference-number") + abstract String getManufacturerReferenceNumber(); - @JsonProperty(value = "version") - abstract String getVersionForArtifact(); + @JsonIgnore + abstract Set getReferencingFeatureGroups(); - @JsonIgnore - abstract String getVendorLicenseModelId(); + @JsonIgnore + abstract String getVersion(); + @JsonProperty(value = "version") + abstract String getVersionForArtifact(); - @JsonIgnore - abstract String getEntityType(); + @JsonIgnore + abstract String getVendorLicenseModelId(); - @JsonProperty(value = "license-key-group-uuid") - abstract String getVersionUuId(); + @JsonIgnore + abstract String getEntityType(); - @JsonIgnore - abstract String getFirstClassCitizenId(); + @JsonProperty(value = "license-key-group-uuid") + abstract String getVersionUuId(); + @JsonIgnore + abstract String getFirstClassCitizenId(); - @JsonIgnore - abstract ChoiceOrOther getOperationalScope(); + @JsonIgnore + abstract ChoiceOrOther getOperationalScope(); - @JsonProperty(value = "operational-scope") - abstract OperationalScopeForXml getOperationalScopeForArtifact(); + @JsonProperty(value = "operational-scope") + abstract OperationalScopeForXml getOperationalScopeForArtifact(); + @JsonIgnore + abstract LicenseKeyTypeForXml getTypeForArtifact(); - @JsonIgnore - abstract LicenseKeyTypeForXml getTypeForArtifact(); + @JsonIgnore + abstract String getVersionableId(); - @JsonIgnore - abstract String getVersionableId(); + @JsonProperty(value = "threshold-value") + abstract ThresholdForXml getThresholdForArtifact(); - @JsonProperty(value = "threshold-value") - abstract ThresholdForXml getThresholdForArtifact(); - @JsonProperty(value = "sp-limits") - abstract LimitForXml getSPLimits(); + @JsonProperty(value = "sp-limits") + abstract LimitForXml getSPLimits(); - @JsonProperty(value = "vendor-limits") - abstract LimitForXml getVendorLimits(); + @JsonProperty(value = "vendor-limits") + abstract LimitForXml getVendorLimits(); - @JsonIgnore - abstract Collection getLimits(); + @JsonIgnore + abstract Collection getLimits(); - @JsonIgnore - abstract String getStartDate(); + @JsonIgnore + abstract String getStartDate(); - @JsonIgnore - abstract String getExpiryDate(); + @JsonIgnore + abstract String getExpiryDate(); - @JsonProperty(value = "start-date") - abstract String getIsoFormatStartDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); - @JsonProperty(value = "expiry-date") - abstract String getIsoFormatExpiryDate(); + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); - @JsonIgnore - abstract String getThresholdUnits(); + @JsonIgnore + abstract String getThresholdUnits(); - @JsonIgnore - abstract float getThresholdValue(); + @JsonIgnore + abstract float getThresholdValue(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLimitArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLimitArtifact.java index 1a15a6e557..7627d5f243 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLimitArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLimitArtifact.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -27,16 +26,15 @@ import org.openecomp.sdc.vendorlicense.dao.types.xml.EntitlementTimeForXml; public abstract class MixinLimitArtifact { - @JsonIgnore - abstract String getTime(); - - @JsonIgnore - abstract String getAggregationFunction(); + @JsonIgnore + abstract String getTime(); - @JsonProperty(value = "aggregation-function") - abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); + @JsonIgnore + abstract String getAggregationFunction(); - @JsonProperty(value = "time") - abstract EntitlementTimeForXml getTimeForArtifact(); + @JsonProperty(value = "aggregation-function") + abstract AggregationFunctionForXml getAggregationFunctionForArtifact(); + @JsonProperty(value = "time") + abstract EntitlementTimeForXml getTimeForArtifact(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java index 7153f45d2f..7dbbad7b44 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java @@ -13,17 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util; - import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; - import org.apache.commons.collections4.MultiValuedMap; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; import org.openecomp.sdc.vendorlicense.HealingServiceFactory; @@ -38,148 +35,116 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - - /** * @author katyr * @since January 10, 2017 */ - public class VendorLicenseArtifactsServiceUtils { - private static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); - /** - * maps the entities by id - * - * @return a Map of id -> list of versionable entities with that id - */ - private static MultiValuedMap mapById( - Collection versionableEntities) { - MultiValuedMap mappedById = new ArrayListValuedHashMap<>(); - for (VersionableEntity ve : versionableEntities) { - mappedById.put(ve.getId(), ve); + private static final HealingService healingService = HealingServiceFactory.getInstance().createInterface(); + + /** + * maps the entities by id + * + * @return a Map of id -> list of versionable entities with that id + */ + private static MultiValuedMap mapById(Collection versionableEntities) { + MultiValuedMap mappedById = new ArrayListValuedHashMap<>(); + for (VersionableEntity ve : versionableEntities) { + mappedById.put(ve.getId(), ve); + } + return mappedById; } - return mappedById; - } - - /** - * For all entities with same id, only entities that differ from one another will be returned. - * If no change has occured, the entity with the earlier VLM version will be returned. - * If only one version of said entities exists it will be returned - * - * @return a list of entities that has been changed - */ - public static List filterChangedEntities( - Collection versionableEntities) { - MultiValuedMap entitiesById = mapById( - versionableEntities); - MultiValuedMap entitiesByVersionUuId = - new ArrayListValuedHashMap<>(); - List changedOnly = new ArrayList<>(); - for (String epId : entitiesById.keySet()) { - Collection versionableEntitiesForId = entitiesById.get(epId); - for (VersionableEntity ep : versionableEntitiesForId) { - entitiesByVersionUuId.put(ep.getVersionUuId(), ep); - } + /** + * For all entities with same id, only entities that differ from one another will be returned. If no change has occured, the entity with the + * earlier VLM version will be returned. If only one version of said entities exists it will be returned + * + * @return a list of entities that has been changed + */ + public static List filterChangedEntities(Collection versionableEntities) { + MultiValuedMap entitiesById = mapById(versionableEntities); + MultiValuedMap entitiesByVersionUuId = new ArrayListValuedHashMap<>(); + List changedOnly = new ArrayList<>(); + for (String epId : entitiesById.keySet()) { + Collection versionableEntitiesForId = entitiesById.get(epId); + for (VersionableEntity ep : versionableEntitiesForId) { + entitiesByVersionUuId.put(ep.getVersionUuId(), ep); + } + } + //for every list of eps which have the same uuid, get the one with the earliest vlm version. + for (String versionUid : entitiesByVersionUuId.keySet()) { + List versionableEntitiesForUuid = (List) entitiesByVersionUuId.get(versionUid); + versionableEntitiesForUuid.sort(new VersionableEntitySortByVlmMajorVersion()); + changedOnly.add(versionableEntitiesForUuid.get(0)); + } + return changedOnly; } - //for every list of eps which have the same uuid, get the one with the earliest vlm version. - for (String versionUid : entitiesByVersionUuId.keySet()) { - List versionableEntitiesForUuid = - (List) entitiesByVersionUuId.get(versionUid); - versionableEntitiesForUuid.sort(new VersionableEntitySortByVlmMajorVersion()); - changedOnly.add(versionableEntitiesForUuid.get(0)); + public static Set healLkgs(Collection licenseKeyGroupEntities) { + Set healed = new HashSet<>(); + for (VersionableEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { + healed.add((LicenseKeyGroupEntity) VendorLicenseArtifactsServiceImpl.healingService.heal(licenseKeyGroupEntity)); + } + return healed; } - return changedOnly; - } - - public static Set healLkgs( - Collection licenseKeyGroupEntities) { - Set healed = new HashSet<>(); - for (VersionableEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { - healed.add((LicenseKeyGroupEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(licenseKeyGroupEntity)); + public static Set healEPs(Collection entitlementPoolEntities) { + Set healed = new HashSet<>(); + for (VersionableEntity entitlementPoolEntity : entitlementPoolEntities) { + healed.add((EntitlementPoolEntity) VendorLicenseArtifactsServiceImpl.healingService.heal(entitlementPoolEntity)); + } + return healed; } - return healed; - } - - public static Set healEPs( - Collection entitlementPoolEntities) { - Set healed = new HashSet<>(); - for (VersionableEntity entitlementPoolEntity : entitlementPoolEntities) { - healed.add((EntitlementPoolEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(entitlementPoolEntity)); + public static List getFinalVersionsForVlm(String vlmId) { + VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); + return versioningManager.list(vlmId).stream().filter(version -> VersionStatus.Certified == version.getStatus()) + .map(certifiedVersion -> versioningManager.get(vlmId, certifiedVersion)) //sync to private + .collect(Collectors.toList()); } - return healed; - } - - public static List getFinalVersionsForVlm(String vlmId) { - VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); - return versioningManager.list(vlmId).stream() - .filter(version -> VersionStatus.Certified == version.getStatus()) - .map(certifiedVersion -> versioningManager.get(vlmId, certifiedVersion)) //sync to private - .collect(Collectors.toList()); - } - - public static String getVendorName(String vendorLicenseModelId) { - return AsdcItemManagerFactory.getInstance().createInterface().get(vendorLicenseModelId) - .getName(); - } - - - /** - * Written to handle the consequences of ATTASDC-4780 where version_uuid was not saved or - * retrieved correctly by DAO for EPs and LKGs. Performs a healing of sorts according to the - * following : 1. all versions of a specific entity (EP or LKG that have the same invariant_uuid) - * are ordered by their VLM version 2. first element is sent to healing (which will set a - * versionUUID for it IF it doesnt exist) 3. each subsequent element is compared to previous . If - * same, UUID is copied from the previous element , if they differ - the current element is sent - * to healing as before. For VLMs created post-bugfix this code should not update any element - */ - public static Collection prepareForFiltering(Collection versionableEntities, boolean isEP) { - MultiValuedMap entitiesById = mapById( - versionableEntities); - - for (String epId : entitiesById.keySet()) { - List versionableEntitiesForId = new ArrayList<>(); - versionableEntitiesForId.addAll(entitiesById.get(epId)); - versionableEntitiesForId.sort(new VersionableEntitySortByVlmMajorVersion()); - healingService.heal(versionableEntitiesForId.get(0)); - for (int i = 1; i < versionableEntitiesForId.size(); i++) { - if (isEP) { - EntitlementPoolEntity current = (EntitlementPoolEntity) versionableEntitiesForId.get(i); - EntitlementPoolEntity previous = (EntitlementPoolEntity) versionableEntitiesForId - .get(i - 1); - if (current.equals(previous) && current.getVersionUuId() == null) { - current.setVersionUuId(previous.getVersionUuId()); - healingService.persistNoHealing(current); - } else { - versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); - } - - } else { - LicenseKeyGroupEntity current = (LicenseKeyGroupEntity) versionableEntitiesForId.get(i); - LicenseKeyGroupEntity previous = (LicenseKeyGroupEntity) versionableEntitiesForId - .get(i - 1); - if (current.equals(previous) && current.getVersionUuId() == null) { - current.setVersionUuId(previous.getVersionUuId()); - healingService.persistNoHealing(current); - } else { - versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); - } - + public static String getVendorName(String vendorLicenseModelId) { + return AsdcItemManagerFactory.getInstance().createInterface().get(vendorLicenseModelId).getName(); + } + /** + * Written to handle the consequences of ATTASDC-4780 where version_uuid was not saved or retrieved correctly by DAO for EPs and LKGs. Performs a + * healing of sorts according to the following : 1. all versions of a specific entity (EP or LKG that have the same invariant_uuid) are ordered by + * their VLM version 2. first element is sent to healing (which will set a versionUUID for it IF it doesnt exist) 3. each subsequent element is + * compared to previous . If same, UUID is copied from the previous element , if they differ - the current element is sent to healing as before. + * For VLMs created post-bugfix this code should not update any element + */ + public static Collection prepareForFiltering(Collection versionableEntities, + boolean isEP) { + MultiValuedMap entitiesById = mapById(versionableEntities); + for (String epId : entitiesById.keySet()) { + List versionableEntitiesForId = new ArrayList<>(); + versionableEntitiesForId.addAll(entitiesById.get(epId)); + versionableEntitiesForId.sort(new VersionableEntitySortByVlmMajorVersion()); + healingService.heal(versionableEntitiesForId.get(0)); + for (int i = 1; i < versionableEntitiesForId.size(); i++) { + if (isEP) { + EntitlementPoolEntity current = (EntitlementPoolEntity) versionableEntitiesForId.get(i); + EntitlementPoolEntity previous = (EntitlementPoolEntity) versionableEntitiesForId.get(i - 1); + if (current.equals(previous) && current.getVersionUuId() == null) { + current.setVersionUuId(previous.getVersionUuId()); + healingService.persistNoHealing(current); + } else { + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); + } + } else { + LicenseKeyGroupEntity current = (LicenseKeyGroupEntity) versionableEntitiesForId.get(i); + LicenseKeyGroupEntity previous = (LicenseKeyGroupEntity) versionableEntitiesForId.get(i - 1); + if (current.equals(previous) && current.getVersionUuId() == null) { + current.setVersionUuId(previous.getVersionUuId()); + healingService.persistNoHealing(current); + } else { + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); + } + } + } } - } + return versionableEntities; } - return versionableEntities; - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VersionableEntitySortByVlmMajorVersion.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VersionableEntitySortByVlmMajorVersion.java index 1aee2dd97e..2626382479 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VersionableEntitySortByVlmMajorVersion.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VersionableEntitySortByVlmMajorVersion.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util; -import org.openecomp.sdc.versioning.dao.types.VersionableEntity; - import java.util.Comparator; +import org.openecomp.sdc.versioning.dao.types.VersionableEntity; /** * @author katyr * @since January 10, 2017 */ - public class VersionableEntitySortByVlmMajorVersion implements Comparator { - @Override - public int compare(VersionableEntity o1, VersionableEntity o2) { - return Integer.compare(o1.getVersion().getMajor(), o2.getVersion().getMajor()); - } + @Override + public int compare(VersionableEntity o1, VersionableEntity o2) { + return Integer.compare(o1.getVersion().getMajor(), o2.getVersion().getMajor()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java index 220d7f4d15..86c1bd1895 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java @@ -17,26 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct; public final class VendorSoftwareProductConstants { - public static final String VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE = "VendorSoftwareProduct"; - public static final String VSP_PACKAGE_ZIP = "VSPPackage.zip"; - public static final String CSAR = "CSAR"; - public static final String INFORMATION_ARTIFACT_NAME = "VSP_%s_Information.txt"; - public static final String NAME_PATTERN = "^[a-zA-Z0-9_]*$"; - public final class UniqueValues { - public static final String VENDOR_SOFTWARE_PRODUCT_NAME = "Vendor Software Product name"; - public static final String PROCESS_NAME = "Process name"; - public static final String NETWORK_NAME = "Network name"; - public static final String COMPONENT_NAME = "ComponentData name"; - public static final String NIC_NAME = "NIC name"; - public static final String COMPUTE_NAME = "Compute name"; - public static final String ORCHESTRATION_CANDIDATE_NAME = "Orchestration Candidate name"; - //public static final String COMPONENT_ARTIFACT_NAME = "ComponentArtifact name"; - public static final String DEPLOYMENT_FLAVOR_NAME = "Deployment Flavor name"; - public static final String IMAGE_NAME = "Image name"; - } + public static final String VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE = "VendorSoftwareProduct"; + public static final String VSP_PACKAGE_ZIP = "VSPPackage.zip"; + public static final String CSAR = "CSAR"; + public static final String INFORMATION_ARTIFACT_NAME = "VSP_%s_Information.txt"; + public static final String NAME_PATTERN = "^[a-zA-Z0-9_]*$"; + + public final class UniqueValues { + + public static final String VENDOR_SOFTWARE_PRODUCT_NAME = "Vendor Software Product name"; + public static final String PROCESS_NAME = "Process name"; + public static final String NETWORK_NAME = "Network name"; + public static final String COMPONENT_NAME = "ComponentData name"; + public static final String NIC_NAME = "NIC name"; + public static final String COMPUTE_NAME = "Compute name"; + public static final String ORCHESTRATION_CANDIDATE_NAME = "Orchestration Candidate name"; + //public static final String COMPONENT_ARTIFACT_NAME = "ComponentArtifact name"; + public static final String DEPLOYMENT_FLAVOR_NAME = "Deployment Flavor name"; + public static final String IMAGE_NAME = "Image name"; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentArtifactDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentArtifactDao.java index 88b5964114..55df02e29a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentArtifactDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentArtifactDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,28 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; -import org.openecomp.sdc.versioning.dao.VersionableDao; - import java.util.Collection; import java.util.Optional; - +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; +import org.openecomp.sdc.versioning.dao.VersionableDao; public interface ComponentArtifactDao extends VersionableDao { - Optional getByType(ComponentMonitoringUploadEntity entity); + Optional getByType(ComponentMonitoringUploadEntity entity); - void create(ComponentMonitoringUploadEntity entity); + void create(ComponentMonitoringUploadEntity entity); - void delete(ComponentMonitoringUploadEntity entity); + void delete(ComponentMonitoringUploadEntity entity); - Collection list(ComponentMonitoringUploadEntity entity); + Collection list(ComponentMonitoringUploadEntity entity); - void deleteAll(ComponentMonitoringUploadEntity entity); + void deleteAll(ComponentMonitoringUploadEntity entity); - Collection listArtifacts( - ComponentMonitoringUploadEntity entity); + Collection listArtifacts(ComponentMonitoringUploadEntity entity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDao.java index ef3f2f131d..acc2dbf46d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ComponentDao extends VersionableDao, BaseDao { - ComponentEntity getQuestionnaireData(String vspId, Version version, String componentId); + ComponentEntity getQuestionnaireData(String vspId, Version version, String componentId); - void updateQuestionnaireData(String vspId, Version version, String componentId, - String questionnaireData); + void updateQuestionnaireData(String vspId, Version version, String componentId, String questionnaireData); - Collection listQuestionnaires(String vspId, Version version); + Collection listQuestionnaires(String vspId, Version version); - Collection listCompositionAndQuestionnaire(String vspId, Version version); + Collection listCompositionAndQuestionnaire(String vspId, Version version); - void deleteAll(String vspId, Version version); + void deleteAll(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDaoFactory.java index e1cf30bfb1..81fc4724eb 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ComponentDaoFactory extends AbstractComponentFactory { - public static ComponentDaoFactory getInstance() { - return AbstractFactory.getInstance(ComponentDaoFactory.class); - } + public static ComponentDaoFactory getInstance() { + return AbstractFactory.getInstance(ComponentDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java index a35c8b0000..4d0de55b90 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -public interface ComponentDependencyModelDao extends VersionableDao, - BaseDao { +public interface ComponentDependencyModelDao extends VersionableDao, BaseDao { + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDaoFactory.java index d347426c86..09c5db22b6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; - import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class ComponentDependencyModelDaoFactory extends - AbstractComponentFactory { +public abstract class ComponentDependencyModelDaoFactory extends AbstractComponentFactory { - public static ComponentDependencyModelDaoFactory getInstance() { - return AbstractFactory.getInstance(ComponentDependencyModelDaoFactory.class); - } + public static ComponentDependencyModelDaoFactory getInstance() { + return AbstractFactory.getInstance(ComponentDependencyModelDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDao.java index 1ddb0129d2..4f7f5fdde7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,25 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ComputeDao extends VersionableDao, BaseDao { - Collection listByVsp(String vspId, Version version); + Collection listByVsp(String vspId, Version version); + void updateQuestionnaireData(String vspId, Version version, String componentId, String computeId, String questionnaireData); - void updateQuestionnaireData(String vspId, Version version, String componentId, String computeId, - String questionnaireData); - void deleteAll(String vspId, Version version); + void deleteAll(String vspId, Version version); - ComputeEntity getQuestionnaireData(String vspId, Version version, String componentId, - String computeId); + ComputeEntity getQuestionnaireData(String vspId, Version version, String componentId, String computeId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDaoFactory.java index 951ae00c95..78a5cddcf0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComputeDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,8 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ComputeDaoFactory extends AbstractComponentFactory { - - public static ComputeDaoFactory getInstance() { - return AbstractFactory.getInstance(ComputeDaoFactory.class); - } + public static ComputeDaoFactory getInstance() { + return AbstractFactory.getInstance(ComputeDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDao.java index 1a3313ae60..ef96dc98e6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; - import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; public interface DeploymentFlavorDao extends VersionableDao, BaseDao { - void deleteAll(String vspId, Version version); -} + void deleteAll(String vspId, Version version); +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDaoFactory.java index a94afa2eae..9d70e594b1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/DeploymentFlavorDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; - import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class DeploymentFlavorDaoFactory extends AbstractComponentFactory { + public static DeploymentFlavorDaoFactory getInstance() { return AbstractFactory.getInstance(DeploymentFlavorDaoFactory.class); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDao.java index ab1efd3b66..d707cecae7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; - +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface ImageDao extends VersionableDao, BaseDao { - void updateQuestionnaireData(String vspId, Version version, String componentId, String imageId, - String questionnaireData); - + void updateQuestionnaireData(String vspId, Version version, String componentId, String imageId, String questionnaireData); - void deleteByVspId(String vspId, Version version); + void deleteByVspId(String vspId, Version version); - Collection listByVsp(String vspId, Version version); + Collection listByVsp(String vspId, Version version); - ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, - String imageId); + ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, String imageId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDaoFactory.java index e6eda24450..f49169b785 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ImageDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ImageDaoFactory extends AbstractComponentFactory { - public static ImageDaoFactory getInstance() { - return AbstractFactory.getInstance(ImageDaoFactory.class); - } + public static ImageDaoFactory getInstance() { + return AbstractFactory.getInstance(ImageDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MonitoringUploadDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MonitoringUploadDaoFactory.java index b70b1a5245..9493295333 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MonitoringUploadDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/MonitoringUploadDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class MonitoringUploadDaoFactory - extends AbstractComponentFactory { +public abstract class MonitoringUploadDaoFactory extends AbstractComponentFactory { - public static MonitoringUploadDaoFactory getInstance() { - return AbstractFactory.getInstance(MonitoringUploadDaoFactory.class); - } + public static MonitoringUploadDaoFactory getInstance() { + return AbstractFactory.getInstance(MonitoringUploadDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDao.java index da57b0a2b4..1736727ed3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; @@ -27,15 +26,5 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface NetworkDao extends VersionableDao, BaseDao { - - - void deleteAll(String vspId, Version version); - - - - - - - - + void deleteAll(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDaoFactory.java index 8db3d605e4..547cf037fc 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NetworkDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class NetworkDaoFactory extends AbstractComponentFactory { - public static NetworkDaoFactory getInstance() { - return AbstractFactory.getInstance(NetworkDaoFactory.class); - } + public static NetworkDaoFactory getInstance() { + return AbstractFactory.getInstance(NetworkDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDao.java index 3205fcdb1f..83f6f3954e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.Collection; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; - public interface NicDao extends VersionableDao, BaseDao { - NicEntity getQuestionnaireData(String vspId, Version version, String componentId, - String nicId); + NicEntity getQuestionnaireData(String vspId, Version version, String componentId, String nicId); - void updateQuestionnaireData(String vspId, Version version, String componentId, String nicId, - String questionnaireData); + void updateQuestionnaireData(String vspId, Version version, String componentId, String nicId, String questionnaireData); - Collection listByVsp(String vspId, Version version); + Collection listByVsp(String vspId, Version version); - void deleteByComponentId(String vspId, Version version, String componentId); + void deleteByComponentId(String vspId, Version version, String componentId); - void deleteByVspId(String vspId, Version version); + void deleteByVspId(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDaoFactory.java index b61ad6a3ca..24ebc22d12 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/NicDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class NicDaoFactory extends AbstractComponentFactory { - public static NicDaoFactory getInstance() { - return AbstractFactory.getInstance(NicDaoFactory.class); - } + public static NicDaoFactory getInstance() { + return AbstractFactory.getInstance(NicDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java index c44ee307b4..8049717cd5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java @@ -13,32 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.Optional; import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Optional; - public interface OrchestrationTemplateCandidateDao extends VersionableDao { - Optional get(String vspId, Version version); + Optional get(String vspId, Version version); - Optional getInfo(String vspId, Version version); + Optional getInfo(String vspId, Version version); - void delete(String vspId, Version version); + void delete(String vspId, Version version); - void update(String vspId, Version version, OrchestrationTemplateCandidateData candidateData); + void update(String vspId, Version version, OrchestrationTemplateCandidateData candidateData); - void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure); + void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure); - Optional getStructure(String vspId, Version version); + Optional getStructure(String vspId, Version version); - void updateValidationData(String vspId, Version version, ValidationStructureList - validationData); + void updateValidationData(String vspId, Version version, ValidationStructureList validationData); } - diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDaoFactory.java index 5624da018a..f8c91a9652 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class OrchestrationTemplateCandidateDaoFactory - extends AbstractComponentFactory { +public abstract class OrchestrationTemplateCandidateDaoFactory extends AbstractComponentFactory { - public static OrchestrationTemplateCandidateDaoFactory getInstance() { - return AbstractFactory.getInstance(OrchestrationTemplateCandidateDaoFactory.class); - } + public static OrchestrationTemplateCandidateDaoFactory getInstance() { + return AbstractFactory.getInstance(OrchestrationTemplateCandidateDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java index ddee436331..22eae51af7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java @@ -13,23 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.Optional; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Optional; - public interface OrchestrationTemplateDao extends VersionableDao { - OrchestrationTemplateEntity getInfo(String vspId, Version version); + OrchestrationTemplateEntity getInfo(String vspId, Version version); - OrchestrationTemplateEntity get(String vspId, Version version); + OrchestrationTemplateEntity get(String vspId, Version version); - void update(String vspId, Version version, OrchestrationTemplateEntity uploadData); + void update(String vspId, Version version, OrchestrationTemplateEntity uploadData); - Optional getOrchestrationTemplateStructure(String vspId, Version version); + Optional getOrchestrationTemplateStructure(String vspId, Version version); } - diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDaoFactory.java index be3c849a20..a73355bebe 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class OrchestrationTemplateDaoFactory - extends AbstractComponentFactory { +public abstract class OrchestrationTemplateDaoFactory extends AbstractComponentFactory { - public static OrchestrationTemplateDaoFactory getInstance() { - return AbstractFactory.getInstance(OrchestrationTemplateDaoFactory.class); - } + public static OrchestrationTemplateDaoFactory getInstance() { + return AbstractFactory.getInstance(OrchestrationTemplateDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java index 36fff1e534..a2b1c9c8ae 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; +import java.util.List; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import java.util.List; - public interface PackageInfoDao extends BaseDao { - List listByCategory(String category, String subCategory); + + List listByCategory(String category, String subCategory); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDaoFactory.java index a8e3d6563d..6f617ddd0c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class PackageInfoDaoFactory extends AbstractComponentFactory { - public static PackageInfoDaoFactory getInstance() { - return AbstractFactory.getInstance(PackageInfoDaoFactory.class); - } + public static PackageInfoDaoFactory getInstance() { + return AbstractFactory.getInstance(PackageInfoDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java index 83eab91ea6..8e1a826d8b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; @@ -30,13 +29,14 @@ import org.openecomp.sdc.versioning.dao.types.Version; * @since March 23, 2017 */ public interface ProcessDao extends VersionableDao, BaseDao { - void deleteAll(ProcessEntity entity); - void deleteVspAll(String vspId, Version version); + void deleteAll(ProcessEntity entity); + + void deleteVspAll(String vspId, Version version); - ProcessEntity getArtifact(ProcessEntity entity); + ProcessEntity getArtifact(ProcessEntity entity); - void uploadArtifact(ProcessEntity entity); + void uploadArtifact(ProcessEntity entity); - void deleteArtifact(ProcessEntity entity); + void deleteArtifact(ProcessEntity entity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDaoFactory.java index f661a0ccda..59105981f5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ProcessDaoFactory extends AbstractComponentFactory { - public static ProcessDaoFactory getInstance() { - return AbstractFactory.getInstance(ProcessDaoFactory.class); - } + public static ProcessDaoFactory getInstance() { + return AbstractFactory.getInstance(ProcessDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java index c44a9cd89e..442b6043d5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; @@ -28,9 +27,9 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface VendorSoftwareProductInfoDao extends VersionableDao, BaseDao { - void updateQuestionnaireData(String vspId, Version version, String questionnaireData); + void updateQuestionnaireData(String vspId, Version version, String questionnaireData); - VspQuestionnaireEntity getQuestionnaire(String vspId, Version version); + VspQuestionnaireEntity getQuestionnaire(String vspId, Version version); - boolean isManual(String vspId, Version version); + boolean isManual(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDaoFactory.java index 570ddc496e..0c10698f0b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class VendorSoftwareProductInfoDaoFactory - extends AbstractComponentFactory { +public abstract class VendorSoftwareProductInfoDaoFactory extends AbstractComponentFactory { - public static VendorSoftwareProductInfoDaoFactory getInstance() { - return AbstractFactory.getInstance(VendorSoftwareProductInfoDaoFactory.class); - } + public static VendorSoftwareProductInfoDaoFactory getInstance() { + return AbstractFactory.getInstance(VendorSoftwareProductInfoDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java index fbe99b7a79..4c7b1340e6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import com.amdocs.zusammen.datatypes.item.Resolution; @@ -25,14 +24,14 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface VspMergeDao { - boolean isConflicted(String vspId, Version version); + boolean isConflicted(String vspId, Version version); - void updateHint(String vspId, Version version); + void updateHint(String vspId, Version version); - void deleteHint(String vspId, Version version); + void deleteHint(String vspId, Version version); - // TODO: 11/7/2017 change to sdc Resolution - void updateConflictResolution(String vspId, Version version, Resolution resolution); + // TODO: 11/7/2017 change to sdc Resolution + void updateConflictResolution(String vspId, Version version, Resolution resolution); - void applyConflictResolution(String vspId, Version version); + void applyConflictResolution(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java index 84f021c9e3..92ddee756b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class VspMergeDaoFactory extends AbstractComponentFactory { - public static VspMergeDaoFactory getInstance() { - return AbstractFactory.getInstance(VspMergeDaoFactory.class); - } + public static VspMergeDaoFactory getInstance() { + return AbstractFactory.getInstance(VspMergeDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDao.java index 4658f71d2a..dbac6f398c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; @@ -26,7 +25,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface VspQuestionnaireDao extends VersionableDao { - VspQuestionnaireEntity get(VspQuestionnaireEntity entity); + VspQuestionnaireEntity get(VspQuestionnaireEntity entity); - void updateQuestionnaireData(String id, Version version, String questionnaireData); + void updateQuestionnaireData(String id, Version version, String questionnaireData); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDaoFactory.java index afc3dc9649..90d0d448b1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspQuestionnaireDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class VspQuestionnaireDaoFactory - extends AbstractComponentFactory { +public abstract class VspQuestionnaireDaoFactory extends AbstractComponentFactory { - public static VspQuestionnaireDaoFactory getInstance() { - return AbstractFactory.getInstance(VspQuestionnaireDaoFactory.class); - } + public static VspQuestionnaireDaoFactory getInstance() { + return AbstractFactory.getInstance(VspQuestionnaireDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/Action.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/Action.java index be78e78f5a..905c094c72 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/Action.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/Action.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; - -public enum Action { - CREATE_PACKAGE, - CHECK_IN, - CHECK_OUT -} +public enum Action {CREATE_PACKAGE, CHECK_IN, CHECK_OUT} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentDependencyModelEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentDependencyModelEntity.java index dfdc0bc0c6..ce08ce6e14 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentDependencyModelEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentDependencyModelEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -35,44 +38,43 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; @Table(keyspace = "dox", name = "vsp_component_dependency_model") public class ComponentDependencyModelEntity implements VersionableEntity { - public static final String ENTITY_TYPE = "Vendor Software Product Component Dependency Model"; - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "dependency_id") - private String id; - @Column(name = "sourcecomponent_id") - private String sourceComponentId; - @Column(name = "targetcomponent_id") - private String targetComponentId; - @Column(name = "relation") - private String relation; - + public static final String ENTITY_TYPE = "Vendor Software Product Component Dependency Model"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "dependency_id") + private String id; + @Column(name = "sourcecomponent_id") + private String sourceComponentId; + @Column(name = "targetcomponent_id") + private String targetComponentId; + @Column(name = "relation") + private String relation; - /** - * Instantiates a new ComponentDependencyModelEntity entity. - * - * @param vspId the vsp id - * @param version the version - * @param dependencyId the dependencyId - */ - public ComponentDependencyModelEntity(String vspId, Version version, String dependencyId) { - this.vspId = vspId; - this.version = version; - this.id = dependencyId; - } + /** + * Instantiates a new ComponentDependencyModelEntity entity. + * + * @param vspId the vsp id + * @param version the version + * @param dependencyId the dependencyId + */ + public ComponentDependencyModelEntity(String vspId, Version version, String dependencyId) { + this.vspId = vspId; + this.version = version; + this.id = dependencyId; + } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentEntity.java index 18c4d949ab..7a69cff27d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentEntity.java @@ -17,10 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; +import com.datastax.driver.mapping.annotations.Transient; +import java.util.ArrayList; +import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -31,72 +37,68 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEnti import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.ArrayList; -import java.util.List; - @EqualsAndHashCode @Getter @Setter @NoArgsConstructor @Table(keyspace = "dox", name = "vsp_component") public class ComponentEntity implements CompositionEntity { - public static final String ENTITY_TYPE = "Vendor Software Product Component"; - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String id; - @Column(name = "composition_data") - private String compositionData; - @Column(name = "questionnaire_data") - private String questionnaireData; - @Transient - private List nics = new ArrayList<>(); + public static final String ENTITY_TYPE = "Vendor Software Product Component"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String id; + @Column(name = "composition_data") + private String compositionData; + @Column(name = "questionnaire_data") + private String questionnaireData; + @Transient + private List nics = new ArrayList<>(); - /** - * Instantiates a new Component entity. - * - * @param vspId the vsp id - * @param version the version - * @param id the id - */ - public ComponentEntity(String vspId, Version version, String id) { - this.vspId = vspId; - this.version = version; - this.id = id; - } + /** + * Instantiates a new Component entity. + * + * @param vspId the vsp id + * @param version the version + * @param id the id + */ + public ComponentEntity(String vspId, Version version, String id) { + this.vspId = vspId; + this.version = version; + this.id = id; + } - @Override - public CompositionEntityType getType() { - return CompositionEntityType.component; - } + @Override + public CompositionEntityType getType() { + return CompositionEntityType.component; + } - @Override - public CompositionEntityId getCompositionEntityId() { - return new CompositionEntityId(getId(), new CompositionEntityId(getVspId(), null)); - } + @Override + public CompositionEntityId getCompositionEntityId() { + return new CompositionEntityId(getId(), new CompositionEntityId(getVspId(), null)); + } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } - public ComponentData getComponentCompositionData() { - return compositionData == null ? null - : JsonUtil.json2Object(compositionData, ComponentData.class); - } + public ComponentData getComponentCompositionData() { + return compositionData == null ? null : JsonUtil.json2Object(compositionData, ComponentData.class); + } - public void setComponentCompositionData(ComponentData component) { - this.compositionData = component == null ? null : JsonUtil.object2Json(component); - } + public void setComponentCompositionData(ComponentData component) { + this.compositionData = component == null ? null : JsonUtil.object2Json(component); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentMonitoringUploadEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentMonitoringUploadEntity.java index b8329a850b..69de3fb7ed 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentMonitoringUploadEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComponentMonitoringUploadEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,138 +17,134 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.nio.ByteBuffer; - @Table(keyspace = "dox", name = "vsp_component_artifact") public class ComponentMonitoringUploadEntity implements VersionableEntity { - public static final String ENTITY_TYPE = "Vendor Software Product Component Artifact"; - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String componentId; - @ClusteringColumn(value = 1) - @Column(name = "artifact_type") - private MonitoringUploadType type; - @ClusteringColumn(value = 2) - @Column(name = "artifact_id") - private String id; - @Column(name = "name") - private String artifactName; - private ByteBuffer artifact; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public ComponentMonitoringUploadEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new Component artifact entity. - * - * @param vspId the vsp id - * @param version the version - * @param componentId the component id - * @param id the id - */ - public ComponentMonitoringUploadEntity(String vspId, Version version, String componentId, - String id) { - this.vspId = vspId; - this.version = version; - this.componentId = componentId; - this.id = id; - } - - public String getVspId() { - return vspId; - } - - public void setVspId(String vspId) { - this.vspId = vspId; - } - - public String getComponentId() { - return componentId; - } - - public void setComponentId(String componentId) { - this.componentId = componentId; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public ByteBuffer getArtifact() { - return artifact; - } - - public void setArtifact(ByteBuffer artifact) { - this.artifact = artifact; - } - - public MonitoringUploadType getType() { - return type; - } - - public void setType(MonitoringUploadType type) { - this.type = type; - } - - @Override - public String toString() { - return "ComponentMonitoringUploadEntity{" + - "vspId='" + vspId + '\'' + - ", version=" + version + - ", componentId='" + componentId + '\'' + - ", type=" + type + - ", id='" + id + '\'' + - ", artifactName='" + artifactName + '\'' + - '}'; - } + + public static final String ENTITY_TYPE = "Vendor Software Product Component Artifact"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String componentId; + @ClusteringColumn(value = 1) + @Column(name = "artifact_type") + private MonitoringUploadType type; + @ClusteringColumn(value = 2) + @Column(name = "artifact_id") + private String id; + @Column(name = "name") + private String artifactName; + private ByteBuffer artifact; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public ComponentMonitoringUploadEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new Component artifact entity. + * + * @param vspId the vsp id + * @param version the version + * @param componentId the component id + * @param id the id + */ + public ComponentMonitoringUploadEntity(String vspId, Version version, String componentId, String id) { + this.vspId = vspId; + this.version = version; + this.componentId = componentId; + this.id = id; + } + + public String getVspId() { + return vspId; + } + + public void setVspId(String vspId) { + this.vspId = vspId; + } + + public String getComponentId() { + return componentId; + } + + public void setComponentId(String componentId) { + this.componentId = componentId; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Version getVersion() { + return version; + } + + public void setVersion(Version version) { + this.version = version; + } + + public String getArtifactName() { + return artifactName; + } + + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public ByteBuffer getArtifact() { + return artifact; + } + + public void setArtifact(ByteBuffer artifact) { + this.artifact = artifact; + } + + public MonitoringUploadType getType() { + return type; + } + + public void setType(MonitoringUploadType type) { + this.type = type; + } + + @Override + public String toString() { + return "ComponentMonitoringUploadEntity{" + "vspId='" + vspId + '\'' + ", version=" + version + ", componentId='" + componentId + '\'' + + ", type=" + type + ", id='" + id + '\'' + ", artifactName='" + artifactName + '\'' + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/CompositionEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/CompositionEntity.java index b3e8eef3f2..46283a06e0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/CompositionEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/CompositionEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId; @@ -26,15 +25,15 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public interface CompositionEntity extends VersionableEntity { - CompositionEntityType getType(); + CompositionEntityType getType(); - CompositionEntityId getCompositionEntityId(); + CompositionEntityId getCompositionEntityId(); - String getCompositionData(); + String getCompositionData(); - void setCompositionData(String compositionData); + void setCompositionData(String compositionData); - String getQuestionnaireData(); + String getQuestionnaireData(); - void setQuestionnaireData(String questionnaireData); + void setQuestionnaireData(String questionnaireData); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComputeEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComputeEntity.java index 590fca602e..d73258f036 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComputeEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ComputeEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -35,61 +38,57 @@ import org.openecomp.sdc.versioning.dao.types.Version; @NoArgsConstructor @Table(keyspace = "dox", name = "vsp_component_compute") public class ComputeEntity implements CompositionEntity { - public static final String ENTITY_TYPE = "Vendor Software Product Component Compute Flavor"; - - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String componentId; - @ClusteringColumn(value = 1) - @Column(name = "compute_id") - private String id; - @Column(name = "composition_data") - private String compositionData; - @Column(name = "questionnaire_data") - private String questionnaireData; - - public ComputeEntity(String vspId, Version version, String componentId, String id) { - this.vspId = vspId; - this.version = version; - this.componentId = componentId; - this.id = id; - } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + public static final String ENTITY_TYPE = "Vendor Software Product Component Compute Flavor"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String componentId; + @ClusteringColumn(value = 1) + @Column(name = "compute_id") + private String id; + @Column(name = "composition_data") + private String compositionData; + @Column(name = "questionnaire_data") + private String questionnaireData; - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + public ComputeEntity(String vspId, Version version, String componentId, String id) { + this.vspId = vspId; + this.version = version; + this.componentId = componentId; + this.id = id; + } - @Override - public CompositionEntityType getType() { - return CompositionEntityType.compute; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public CompositionEntityId getCompositionEntityId() { - return new CompositionEntityId(getId(), - new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } - public ComputeData getComputeCompositionData() { - return compositionData == null ? null - : JsonUtil.json2Object(compositionData, ComputeData.class); - } + @Override + public CompositionEntityType getType() { + return CompositionEntityType.compute; + } - public void setComputeCompositionData(ComputeData computeData){ - this.compositionData = computeData == null ? null : JsonUtil.object2Json(computeData); - } + @Override + public CompositionEntityId getCompositionEntityId() { + return new CompositionEntityId(getId(), new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); + } + public ComputeData getComputeCompositionData() { + return compositionData == null ? null : JsonUtil.json2Object(compositionData, ComputeData.class); + } + public void setComputeCompositionData(ComputeData computeData) { + this.compositionData = computeData == null ? null : JsonUtil.object2Json(computeData); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java index dd145b1f54..03f464b564 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -36,9 +39,9 @@ import org.openecomp.sdc.versioning.dao.types.Version; @Setter @NoArgsConstructor @Table(keyspace = "dox", name = "vsp_deployment_flavor") -public class DeploymentFlavorEntity implements CompositionEntity{ - private static final String ENTITY_TYPE = "Vendor Software Product Deployment Flavor"; +public class DeploymentFlavorEntity implements CompositionEntity { + private static final String ENTITY_TYPE = "Vendor Software Product Deployment Flavor"; @PartitionKey @Column(name = "vsp_id") private String vspId; @@ -65,6 +68,7 @@ public class DeploymentFlavorEntity implements CompositionEntity{ this.version = version; this.id = id; } + @Override public CompositionEntityType getType() { return CompositionEntityType.deployment; @@ -85,7 +89,7 @@ public class DeploymentFlavorEntity implements CompositionEntity{ return getVspId(); } - public DeploymentFlavor getDeploymentFlavorCompositionData() { + public DeploymentFlavor getDeploymentFlavorCompositionData() { return compositionData == null ? null : JsonUtil.json2Object(compositionData, DeploymentFlavor.class); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ImageEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ImageEntity.java index b85fd6c76c..55252cde8a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ImageEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ImageEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -38,65 +41,63 @@ import org.openecomp.sdc.versioning.dao.types.Version; @Table(keyspace = "dox", name = "vsp_component_image") public class ImageEntity implements CompositionEntity { - private static final String ENTITY_TYPE = "Vendor Software Product Component Image"; - - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String componentId; - @ClusteringColumn(value = 1) - @Column(name = "image_id") - private String id; - @Column(name = "composition_data") - private String compositionData; - @Column(name = "questionnaire_data") - private String questionnaireData; + private static final String ENTITY_TYPE = "Vendor Software Product Component Image"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String componentId; + @ClusteringColumn(value = 1) + @Column(name = "image_id") + private String id; + @Column(name = "composition_data") + private String compositionData; + @Column(name = "questionnaire_data") + private String questionnaireData; - /** - * Instantiates a new Image entity. - * - * @param vspId the vsp id - * @param version the version - * @param id the id - */ - public ImageEntity(String vspId, Version version, String componentId, String id) { - this.vspId = vspId; - this.version = version; - this.componentId = componentId; - this.id = id; - } + /** + * Instantiates a new Image entity. + * + * @param vspId the vsp id + * @param version the version + * @param id the id + */ + public ImageEntity(String vspId, Version version, String componentId, String id) { + this.vspId = vspId; + this.version = version; + this.componentId = componentId; + this.id = id; + } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } - @Override - public CompositionEntityType getType() { - return CompositionEntityType.image; - } + @Override + public CompositionEntityType getType() { + return CompositionEntityType.image; + } - @Override - public CompositionEntityId getCompositionEntityId() { - return new CompositionEntityId(getId(), - new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); - } + @Override + public CompositionEntityId getCompositionEntityId() { + return new CompositionEntityId(getId(), new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); + } - public Image getImageCompositionData() { - return compositionData == null ? null : JsonUtil.json2Object(compositionData, Image.class); - } + public Image getImageCompositionData() { + return compositionData == null ? null : JsonUtil.json2Object(compositionData, Image.class); + } - public void setImageCompositionData(Image image) { - this.compositionData = image == null ? null : JsonUtil.object2Json(image); - } + public void setImageCompositionData(Image image) { + this.compositionData = image == null ? null : JsonUtil.object2Json(image); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/LicenseType.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/LicenseType.java index 35dfda4568..2cd7b05f1e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/LicenseType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/LicenseType.java @@ -17,11 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -public enum LicenseType { - EXTERNAL, - INTERNAL -} +public enum LicenseType {EXTERNAL, INTERNAL} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NetworkEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NetworkEntity.java index 4c02fd4723..0b6fae46ea 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NetworkEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NetworkEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -37,61 +40,60 @@ import org.openecomp.sdc.versioning.dao.types.Version; @NoArgsConstructor @Table(keyspace = "dox", name = "vsp_network") public class NetworkEntity implements CompositionEntity { - private static final String ENTITY_TYPE = "Vendor Software Product Network"; - - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "network_id") - private String id; - @Column(name = "composition_data") - private String compositionData; - @Column(name = "questionnaire_data") - private String questionnaireData; + private static final String ENTITY_TYPE = "Vendor Software Product Network"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "network_id") + private String id; + @Column(name = "composition_data") + private String compositionData; + @Column(name = "questionnaire_data") + private String questionnaireData; - /** - * Instantiates a new Network entity. - * - * @param vspId the vsp id - * @param version the version - * @param id the id - */ - public NetworkEntity(String vspId, Version version, String id) { - this.vspId = vspId; - this.version = version; - this.id = id; - } + /** + * Instantiates a new Network entity. + * + * @param vspId the vsp id + * @param version the version + * @param id the id + */ + public NetworkEntity(String vspId, Version version, String id) { + this.vspId = vspId; + this.version = version; + this.id = id; + } - @Override - public CompositionEntityType getType() { - return CompositionEntityType.network; - } + @Override + public CompositionEntityType getType() { + return CompositionEntityType.network; + } - @Override - public CompositionEntityId getCompositionEntityId() { - return new CompositionEntityId(getId(), new CompositionEntityId(getVspId(), null)); - } + @Override + public CompositionEntityId getCompositionEntityId() { + return new CompositionEntityId(getId(), new CompositionEntityId(getVspId(), null)); + } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } - public Network getNetworkCompositionData() { - return compositionData == null ? null : JsonUtil.json2Object(compositionData, Network.class); - } + public Network getNetworkCompositionData() { + return compositionData == null ? null : JsonUtil.json2Object(compositionData, Network.class); + } - public void setNetworkCompositionData(Network network) { - this.compositionData = network == null ? null : JsonUtil.object2Json(network); - } + public void setNetworkCompositionData(Network network) { + this.compositionData = network == null ? null : JsonUtil.object2Json(network); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NicEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NicEntity.java index 59e94ce62a..0a3cc41000 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NicEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/NicEntity.java @@ -17,10 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -37,66 +40,65 @@ import org.openecomp.sdc.versioning.dao.types.Version; @NoArgsConstructor @Table(keyspace = "dox", name = "vsp_component_nic") public class NicEntity implements CompositionEntity { - private static final String ENTITY_TYPE = "Vendor Software Product NIC"; - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String componentId; - @ClusteringColumn(value = 1) - @Column(name = "nic_id") - private String id; - @Column(name = "composition_data") - private String compositionData; - @Column(name = "questionnaire_data") - private String questionnaireData; + private static final String ENTITY_TYPE = "Vendor Software Product NIC"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String componentId; + @ClusteringColumn(value = 1) + @Column(name = "nic_id") + private String id; + @Column(name = "composition_data") + private String compositionData; + @Column(name = "questionnaire_data") + private String questionnaireData; - /** - * Instantiates a new Nic entity. - * - * @param vspId the vsp id - * @param version the version - * @param componentId the component id - * @param id the id - */ - public NicEntity(String vspId, Version version, String componentId, String id) { - this.vspId = vspId; - this.version = version; - this.componentId = componentId; - this.id = id; - } + /** + * Instantiates a new Nic entity. + * + * @param vspId the vsp id + * @param version the version + * @param componentId the component id + * @param id the id + */ + public NicEntity(String vspId, Version version, String componentId, String id) { + this.vspId = vspId; + this.version = version; + this.componentId = componentId; + this.id = id; + } - @Override - public CompositionEntityType getType() { - return CompositionEntityType.nic; - } + @Override + public CompositionEntityType getType() { + return CompositionEntityType.nic; + } - @Override - public CompositionEntityId getCompositionEntityId() { - return new CompositionEntityId(getId(), - new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); - } + @Override + public CompositionEntityId getCompositionEntityId() { + return new CompositionEntityId(getId(), new CompositionEntityId(getComponentId(), new CompositionEntityId(getVspId(), null))); + } - @Override - public String getEntityType() { - return ENTITY_TYPE; - } + @Override + public String getEntityType() { + return ENTITY_TYPE; + } - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } - public Nic getNicCompositionData() { - return compositionData == null ? null : JsonUtil.json2Object(compositionData, Nic.class); - } + public Nic getNicCompositionData() { + return compositionData == null ? null : JsonUtil.json2Object(compositionData, Nic.class); + } - public void setNicCompositionData(Nic nic) { - this.compositionData = nic == null ? null : JsonUtil.object2Json(nic); - } + public void setNicCompositionData(Nic nic) { + this.compositionData = nic == null ? null : JsonUtil.object2Json(nic); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java index 137ada4838..33d58b93ad 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -public enum OnboardingMethod { - NetworkPackage, - Manual; -} +public enum OnboardingMethod {NetworkPackage, Manual;} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java index c5e470e9c6..fdd143d1d2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import java.nio.ByteBuffer; @@ -37,11 +36,8 @@ public class OrchestrationTemplateCandidateData { private String originalFileName; private String originalFileSuffix; - public OrchestrationTemplateCandidateData(final ByteBuffer contentData, - final String dataStructureJson, - final String fileSuffix, final String fileName, - final String originalFileName, - final String originalFileSuffix, + public OrchestrationTemplateCandidateData(final ByteBuffer contentData, final String dataStructureJson, final String fileSuffix, + final String fileName, final String originalFileName, final String originalFileSuffix, final ByteBuffer originalFileContentData) { this.contentData = contentData; this.filesDataStructure = dataStructureJson; @@ -53,8 +49,6 @@ public class OrchestrationTemplateCandidateData { } public ValidationStructureList getValidationDataStructure() { - return validationData == null ? null - : JsonUtil.json2Object(validationData, ValidationStructureList.class); + return validationData == null ? null : JsonUtil.json2Object(validationData, ValidationStructureList.class); } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateDataEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateDataEntity.java index e342e0b3bf..571c3ae914 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateDataEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateDataEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,116 +17,107 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.nio.ByteBuffer; - @Table(keyspace = "dox", name = "vsp_orchestration_template_candidate") public class OrchestrationTemplateCandidateDataEntity implements VersionableEntity { - private static final String ENTITY_TYPE = - "Vendor Software Product Upload Orchestration_candidate data"; - - @PartitionKey - @Column(name = "vsp_id") - private String id; - - @PartitionKey(value = 1) - @Frozen - private Version version; - - @Column(name = "content_data") - private ByteBuffer contentData; - - @Column(name = "files_data_structure") - private String filesDataStructure; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public OrchestrationTemplateCandidateDataEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new OrchestrationTemplateCandidateDataEntity. - * - * @param id the id - * @param version the Version - - */ - public OrchestrationTemplateCandidateDataEntity(String id, Version version) { - this.id = id; - this.version = version; - } - - /** - * Instantiates a new OrchestrationTemplateCandidateDataEntity. - * - * @param filesDataStructure the files data Structure - * @param version the version - * @param contentData the contentData - * @param id the id - */ - public OrchestrationTemplateCandidateDataEntity(String id, Version version, - ByteBuffer contentData, - String filesDataStructure) { - this.id = id; - this.contentData = contentData; - this.filesDataStructure = filesDataStructure; - this.version = version; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return null; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public ByteBuffer getContentData() { - return contentData; - } - - public void setContentData(ByteBuffer contentData) { - this.contentData = contentData; - } - - public String getFilesDataStructure() { - return filesDataStructure; - } - - public void setFilesDataStructure(String filesDataStructure) { - this.filesDataStructure = filesDataStructure; - } + + private static final String ENTITY_TYPE = "Vendor Software Product Upload Orchestration_candidate data"; + @PartitionKey + @Column(name = "vsp_id") + private String id; + @PartitionKey(value = 1) + @Frozen + private Version version; + @Column(name = "content_data") + private ByteBuffer contentData; + @Column(name = "files_data_structure") + private String filesDataStructure; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public OrchestrationTemplateCandidateDataEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new OrchestrationTemplateCandidateDataEntity. + * + * @param id the id + * @param version the Version + */ + public OrchestrationTemplateCandidateDataEntity(String id, Version version) { + this.id = id; + this.version = version; + } + + /** + * Instantiates a new OrchestrationTemplateCandidateDataEntity. + * + * @param filesDataStructure the files data Structure + * @param version the version + * @param contentData the contentData + * @param id the id + */ + public OrchestrationTemplateCandidateDataEntity(String id, Version version, ByteBuffer contentData, String filesDataStructure) { + this.id = id; + this.contentData = contentData; + this.filesDataStructure = filesDataStructure; + this.version = version; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return null; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public ByteBuffer getContentData() { + return contentData; + } + + public void setContentData(ByteBuffer contentData) { + this.contentData = contentData; + } + + public String getFilesDataStructure() { + return filesDataStructure; + } + + public void setFilesDataStructure(String filesDataStructure) { + this.filesDataStructure = filesDataStructure; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java index 1bbe1b0ddf..105fb743e8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java @@ -13,131 +13,127 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; +import java.nio.ByteBuffer; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.nio.ByteBuffer; - public class OrchestrationTemplateEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Vendor Software Product Orchestration Template"; - - private String id; - private Version version; - private String fileSuffix; - private String fileName; - private String packageName; - private String packageVersion; - private String validationData; - private ByteBuffer contentData; - private String filesDataStructure; - - public OrchestrationTemplateEntity() { - //default constructor implementation is not provided for OrchestrationTemplateEntity - } - - public OrchestrationTemplateEntity(String id, Version version) { - this.id = id; - this.version = version; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getId(); - } - - @Override - public String getId() { - return id; - } - - @Override - public void setId(String id) { - this.id = id; - } - - @Override - public Version getVersion() { - return version; - } - - @Override - public void setVersion(Version version) { - this.version = version; - } - - public String getFileSuffix() { - return fileSuffix; - } - - public void setFileSuffix(String fileSuffix) { - this.fileSuffix = fileSuffix; - } - - public String getFileName() { - return fileName; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public String getPackageVersion() { - return packageVersion; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - public String getValidationData() { - return validationData; - } - - public void setValidationData(String validationData) { - this.validationData = validationData; - } - - public ValidationStructureList getValidationDataStructure() { - return validationData == null ? null - : JsonUtil.json2Object(validationData, ValidationStructureList.class); - } - - public void setValidationDataStructure(ValidationStructureList validationData) { - this.validationData = validationData == null ? null - : JsonUtil.object2Json(validationData); - } - - public ByteBuffer getContentData() { - return contentData; - } - - public void setContentData(ByteBuffer contentData) { - this.contentData = contentData; - } - - public String getFilesDataStructure() { - return filesDataStructure; - } - - public void setFilesDataStructure(String filesDataStructure) { - this.filesDataStructure = filesDataStructure; - } + + private static final String ENTITY_TYPE = "Vendor Software Product Orchestration Template"; + private String id; + private Version version; + private String fileSuffix; + private String fileName; + private String packageName; + private String packageVersion; + private String validationData; + private ByteBuffer contentData; + private String filesDataStructure; + + public OrchestrationTemplateEntity() { + //default constructor implementation is not provided for OrchestrationTemplateEntity + } + + public OrchestrationTemplateEntity(String id, Version version) { + this.id = id; + this.version = version; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getId(); + } + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + + @Override + public Version getVersion() { + return version; + } + + @Override + public void setVersion(Version version) { + this.version = version; + } + + public String getFileSuffix() { + return fileSuffix; + } + + public void setFileSuffix(String fileSuffix) { + this.fileSuffix = fileSuffix; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public String getPackageName() { + return packageName; + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public String getPackageVersion() { + return packageVersion; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public String getValidationData() { + return validationData; + } + + public void setValidationData(String validationData) { + this.validationData = validationData; + } + + public ValidationStructureList getValidationDataStructure() { + return validationData == null ? null : JsonUtil.json2Object(validationData, ValidationStructureList.class); + } + + public void setValidationDataStructure(ValidationStructureList validationData) { + this.validationData = validationData == null ? null : JsonUtil.object2Json(validationData); + } + + public ByteBuffer getContentData() { + return contentData; + } + + public void setContentData(ByteBuffer contentData) { + this.contentData = contentData; + } + + public String getFilesDataStructure() { + return filesDataStructure; + } + + public void setFilesDataStructure(String filesDataStructure) { + this.filesDataStructure = filesDataStructure; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java index 6aac77acfa..9c751a239d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,67 +17,51 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; -import lombok.NoArgsConstructor; +import java.nio.ByteBuffer; import lombok.Data; +import lombok.NoArgsConstructor; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.versioning.dao.types.Version; -import java.nio.ByteBuffer; - - @Data @NoArgsConstructor @Table(keyspace = "dox", name = "package_details") public class PackageInfo { - - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - - @PartitionKey(value = 1) - private String version; - - @Column(name = "display_name") - private String displayName; - - @Column(name = "vsp_name") - private String vspName; - - @Column(name = "vsp_description") - private String vspDescription; - - @Column(name = "vendor_name") - private String vendorName; - - private String category; - - @Column(name = "sub_category") - private String subCategory; - - @Column(name = "vendor_release") - private String vendorRelease; - - @Column(name = "package_checksum") - private String packageChecksum; - - @Column(name = "package_type") - private String packageType; - - @Column(name = "translate_content") - private ByteBuffer translatedFile; - - @Column(name = "resource_type") - private String resourceType = ResourceTypeEnum.VF.name(); - - public PackageInfo(String packageId, Version version) { - this.vspId = packageId; - this.version = version.getName(); - } + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + private String version; + @Column(name = "display_name") + private String displayName; + @Column(name = "vsp_name") + private String vspName; + @Column(name = "vsp_description") + private String vspDescription; + @Column(name = "vendor_name") + private String vendorName; + private String category; + @Column(name = "sub_category") + private String subCategory; + @Column(name = "vendor_release") + private String vendorRelease; + @Column(name = "package_checksum") + private String packageChecksum; + @Column(name = "package_type") + private String packageType; + @Column(name = "translate_content") + private ByteBuffer translatedFile; + @Column(name = "resource_type") + private String resourceType = ResourceTypeEnum.VF.name(); + + public PackageInfo(String packageId, Version version) { + this.vspId = packageId; + this.version = version.getName(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessEntity.java index 6e2c371adb..2ed8a535a3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,213 +17,203 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; +import java.nio.ByteBuffer; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import java.nio.ByteBuffer; - @Table(keyspace = "dox", name = "vsp_process") public class ProcessEntity implements VersionableEntity { - public static final String ENTITY_TYPE = "Vendor Software Product Process"; - @PartitionKey - @Column(name = "vsp_id") - private String vspId; - @PartitionKey(value = 1) - @Frozen - private Version version; - @ClusteringColumn - @Column(name = "component_id") - private String componentId; - @ClusteringColumn(value = 1) - @Column(name = "process_id") - private String id; - private String name; - private String description; - @Column(name = "type") - private ProcessType type; - @Column(name = "artifact_name") - private String artifactName; - private ByteBuffer artifact; - - /** - * Every entity class must have a default constructor according to - * - * Definition of mapped classes. - */ - public ProcessEntity() { - // Don't delete! Default constructor is required by DataStax driver - } - - /** - * Instantiates a new Process entity. - * - * @param vspId the vsp id - * @param version the version - * @param componentId the component id - * @param id the id - */ - public ProcessEntity(String vspId, Version version, String componentId, String id) { - this.vspId = vspId; - this.version = version; - this.componentId = componentId; - this.id = id; - } - - public String getVspId() { - return vspId; - } - - public void setVspId(String vspId) { - this.vspId = vspId; - } - - public String getComponentId() { - return componentId; - } - - public void setComponentId(String componentId) { - this.componentId = componentId; - } - - @Override - public String getEntityType() { - return ENTITY_TYPE; - } - - @Override - public String getFirstClassCitizenId() { - return getVspId(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - public String getName() { - return name == null ? "" : name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public ProcessType getType() { - return type; - } - - public void setType(ProcessType type) { - this.type = type; - } - - public String getArtifactName() { - return artifactName; - } - - public void setArtifactName(String artifactName) { - this.artifactName = artifactName; - } - - public ByteBuffer getArtifact() { - return artifact; - } - - public void setArtifact(ByteBuffer artifact) { - this.artifact = artifact; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || getClass() != other.getClass()) { - return false; - } - - ProcessEntity that = (ProcessEntity) other; - - if (vspId != null ? !vspId.equals(that.vspId) : that.vspId != null) { - return false; - } - if (version != null ? !version.equals(that.version) : that.version != null) { - return false; + + public static final String ENTITY_TYPE = "Vendor Software Product Process"; + @PartitionKey + @Column(name = "vsp_id") + private String vspId; + @PartitionKey(value = 1) + @Frozen + private Version version; + @ClusteringColumn + @Column(name = "component_id") + private String componentId; + @ClusteringColumn(value = 1) + @Column(name = "process_id") + private String id; + private String name; + private String description; + @Column(name = "type") + private ProcessType type; + @Column(name = "artifact_name") + private String artifactName; + private ByteBuffer artifact; + + /** + * Every entity class must have a default constructor according to + * + * Definition of mapped classes. + */ + public ProcessEntity() { + // Don't delete! Default constructor is required by DataStax driver + } + + /** + * Instantiates a new Process entity. + * + * @param vspId the vsp id + * @param version the version + * @param componentId the component id + * @param id the id + */ + public ProcessEntity(String vspId, Version version, String componentId, String id) { + this.vspId = vspId; + this.version = version; + this.componentId = componentId; + this.id = id; + } + + public String getVspId() { + return vspId; + } + + public void setVspId(String vspId) { + this.vspId = vspId; + } + + public String getComponentId() { + return componentId; + } + + public void setComponentId(String componentId) { + this.componentId = componentId; + } + + @Override + public String getEntityType() { + return ENTITY_TYPE; + } + + @Override + public String getFirstClassCitizenId() { + return getVspId(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } - if (componentId != null ? !componentId.equals(that.componentId) : that.componentId != null) { - return false; - } - if (id != null ? !id.equals(that.id) : that.id != null) { - return false; - } - if (name != null ? !name.equals(that.name) : that.name != null) { - return false; + + public Version getVersion() { + return version; + } + + public void setVersion(Version version) { + this.version = version; + } + + public String getName() { + return name == null ? "" : name; + } + + public void setName(String name) { + this.name = name; } - if (description != null ? !description.equals(that.description) : that.description != null) { - return false; + + public String getDescription() { + return description; } - if (artifactName != null ? !artifactName.equals(that.artifactName) - : that.artifactName != null) { - return false; - } - if (artifact != null ? !artifact.equals(that.artifact) : that.artifact != null) { - return false; + + public void setDescription(String description) { + this.description = description; } - if (type != null ? !type.equals(that.type) : that.type != null) { - return false; - } + public ProcessType getType() { + return type; + } - return true; - } + public void setType(ProcessType type) { + this.type = type; + } - @Override - public int hashCode() { - int result = vspId != null ? vspId.hashCode() : 0; - result = 31 * result + (version != null ? version.hashCode() : 0); - result = 31 * result + (componentId != null ? componentId.hashCode() : 0); - result = 31 * result + (id != null ? id.hashCode() : 0); - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (description != null ? description.hashCode() : 0); - result = 31 * result + (type != null ? type.hashCode() : 0); - result = 31 * result + (artifactName != null ? artifactName.hashCode() : 0); - result = 31 * result + (artifact != null ? artifact.hashCode() : 0); - return result; - } + public String getArtifactName() { + return artifactName; + } - @Override - public String toString() { - return "ProcessEntity{" + - "vspId='" + vspId + '\'' + - ", version=" + version + - ", componentId='" + componentId + '\'' + - ", id='" + id + '\'' + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - ", type=" + type + - ", artifactName='" + artifactName + '\'' + - '}'; - } + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public ByteBuffer getArtifact() { + return artifact; + } + + public void setArtifact(ByteBuffer artifact) { + this.artifact = artifact; + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (other == null || getClass() != other.getClass()) { + return false; + } + ProcessEntity that = (ProcessEntity) other; + if (vspId != null ? !vspId.equals(that.vspId) : that.vspId != null) { + return false; + } + if (version != null ? !version.equals(that.version) : that.version != null) { + return false; + } + if (componentId != null ? !componentId.equals(that.componentId) : that.componentId != null) { + return false; + } + if (id != null ? !id.equals(that.id) : that.id != null) { + return false; + } + if (name != null ? !name.equals(that.name) : that.name != null) { + return false; + } + if (description != null ? !description.equals(that.description) : that.description != null) { + return false; + } + if (artifactName != null ? !artifactName.equals(that.artifactName) : that.artifactName != null) { + return false; + } + if (artifact != null ? !artifact.equals(that.artifact) : that.artifact != null) { + return false; + } + if (type != null ? !type.equals(that.type) : that.type != null) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int result = vspId != null ? vspId.hashCode() : 0; + result = 31 * result + (version != null ? version.hashCode() : 0); + result = 31 * result + (componentId != null ? componentId.hashCode() : 0); + result = 31 * result + (id != null ? id.hashCode() : 0); + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (description != null ? description.hashCode() : 0); + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (artifactName != null ? artifactName.hashCode() : 0); + result = 31 * result + (artifact != null ? artifact.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "ProcessEntity{" + "vspId='" + vspId + '\'' + ", version=" + version + ", componentId='" + componentId + '\'' + ", id='" + id + '\'' + + ", name='" + name + '\'' + ", description='" + description + '\'' + ", type=" + type + ", artifactName='" + artifactName + '\'' + '}'; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessType.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessType.java index d49386c3bf..09cdc95a29 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/ProcessType.java @@ -17,11 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -public enum ProcessType { - Lifecycle_Operations, - Other -} +public enum ProcessType {Lifecycle_Operations, Other} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/TranslatedFileData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/TranslatedFileData.java index 0dc3ac25a6..6a392cd44f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/TranslatedFileData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/TranslatedFileData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import lombok.Getter; @@ -37,5 +36,4 @@ public class TranslatedFileData { private String vendorRelease; private String packageChecksum; private String packageType; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java index 8f4aed8c71..88b020b673 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import java.util.List; @@ -33,7 +32,6 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public class VspDetails implements VersionableEntity { public static final String ENTITY_TYPE = "Vendor Software Product"; - private String id; private Version version; private String name; @@ -66,8 +64,8 @@ public class VspDetails implements VersionableEntity { @Override public String toString() { - return String.format( - "Vsp id = '%s', Version = %s', Name = %s', Category = %s', Description = %s', Vendor = %s'", - this.id, this.version, this.name, this.category, this.description, this.vendorName); + return String + .format("Vsp id = '%s', Version = %s', Name = %s', Category = %s', Description = %s', Vendor = %s'", this.id, this.version, this.name, + this.category, this.description, this.vendorName); } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspQuestionnaireEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspQuestionnaireEntity.java index e463605d39..1b3dec0a59 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspQuestionnaireEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspQuestionnaireEntity.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import lombok.Getter; @@ -33,7 +32,6 @@ import org.openecomp.sdc.versioning.dao.types.Version; public class VspQuestionnaireEntity implements CompositionEntity { private static final String ENTITY_TYPE = "Vendor Software Product"; - private String id; private Version version; private String questionnaireData; @@ -72,5 +70,4 @@ public class VspQuestionnaireEntity implements CompositionEntity { public void setCompositionData(String compositionData) { //none } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/utils/ErrorsUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/utils/ErrorsUtil.java index fc23a77bef..cce965b874 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/utils/ErrorsUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/utils/ErrorsUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.errors.utils; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.openecomp.sdc.datatypes.error.ErrorMessage; /** * Created by Talio on 11/30/2016. diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CandidateServiceFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CandidateServiceFactory.java index f16d8d4ebe..d728ff3bad 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CandidateServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CandidateServiceFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -29,7 +28,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule. */ public abstract class CandidateServiceFactory extends AbstractComponentFactory { - public static CandidateServiceFactory getInstance(){ - return AbstractFactory.getInstance(CandidateServiceFactory.class); - } + public static CandidateServiceFactory getInstance() { + return AbstractFactory.getInstance(CandidateServiceFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CompositionDataExtractorFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CompositionDataExtractorFactory.java index d10b8b715d..e811df829a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CompositionDataExtractorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/CompositionDataExtractorFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; -public abstract class CompositionDataExtractorFactory extends - AbstractComponentFactory { +public abstract class CompositionDataExtractorFactory extends AbstractComponentFactory { - public static CompositionDataExtractorFactory getInstance() { - return AbstractFactory.getInstance(CompositionDataExtractorFactory.class); - } + public static CompositionDataExtractorFactory getInstance() { + return AbstractFactory.getInstance(CompositionDataExtractorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactory.java index 7e6e7db5dc..f9fb58a20c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator; - public abstract class InformationArtifactGeneratorFactory extends AbstractComponentFactory { - public static InformationArtifactGeneratorFactory getInstance() { - return AbstractFactory.getInstance(InformationArtifactGeneratorFactory.class); - } + public static InformationArtifactGeneratorFactory getInstance() { + return AbstractFactory.getInstance(InformationArtifactGeneratorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/ManifestCreatorFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/ManifestCreatorFactory.java index 9189ffce6d..6c1ec911b0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/ManifestCreatorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/ManifestCreatorFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -27,9 +26,9 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule. /** * Created by Talio on 12/15/2016. */ -public abstract class ManifestCreatorFactory extends AbstractComponentFactory{ +public abstract class ManifestCreatorFactory extends AbstractComponentFactory { - public static ManifestCreatorFactory getInstance(){ - return AbstractFactory.getInstance(ManifestCreatorFactory.class); - } + public static ManifestCreatorFactory getInstance() { + return AbstractFactory.getInstance(ManifestCreatorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnnaireDataServiceFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnnaireDataServiceFactory.java index a45eb3db6f..2a46aabe11 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnnaireDataServiceFactory.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnnaireDataServiceFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; - public abstract class QuestionnnaireDataServiceFactory extends AbstractComponentFactory { - public static QuestionnnaireDataServiceFactory getInstance() { - return AbstractFactory.getInstance(QuestionnnaireDataServiceFactory.class); - } + public static QuestionnnaireDataServiceFactory getInstance() { + return AbstractFactory.getInstance(QuestionnnaireDataServiceFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactData.java index 8f68f1088b..f3db4d3a88 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact; import java.util.List; @@ -40,5 +39,4 @@ public class InformationArtifactData { private VspQuestionnaire vspQuestionnaire; private List componentQuestionnaires; private List nicQuestionnaires; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactGenerator.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactGenerator.java index 5813a18bd7..abc3f5ca19 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/InformationArtifactGenerator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact; -import org.openecomp.sdc.versioning.dao.types.Version; - import java.io.IOException; +import org.openecomp.sdc.versioning.dao.types.Version; /** * @author katyr * @since November 29, 2016 */ - public interface InformationArtifactGenerator { + String generate(String vspId, Version version) throws IOException; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/questionnaire/QuestionnaireDataService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/questionnaire/QuestionnaireDataService.java index 0bf10c09e8..e339f49f7f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/questionnaire/QuestionnaireDataService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/questionnaire/QuestionnaireDataService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.questionnaire; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; @@ -27,7 +26,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; * @author katyr * @since November 29, 2016 */ - public interface QuestionnaireDataService { + InformationArtifactData generateQuestionnaireDataForInformationArtifact(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/HeatFileAnalyzer.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/HeatFileAnalyzer.java index 533f041621..a1b85daa8c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/HeatFileAnalyzer.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/HeatFileAnalyzer.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services; -import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; - import java.io.IOException; import java.util.Map; +import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; /** * @author Avrahamg @@ -31,17 +29,17 @@ import java.util.Map; */ public interface HeatFileAnalyzer { - static boolean isEnvFile(String fileName) { - return fileName.endsWith(".env"); - } + static boolean isEnvFile(String fileName) { + return fileName.endsWith(".env"); + } - static boolean isYamlFile(String fileName) { - return fileName.endsWith(".yml") || fileName.endsWith(".yaml"); - } + static boolean isYamlFile(String fileName) { + return fileName.endsWith(".yml") || fileName.endsWith(".yaml"); + } - static boolean isYamlOrEnvFile(String fileName) { - return isYamlFile(fileName) || isEnvFile(fileName); - } + static boolean isYamlOrEnvFile(String fileName) { + return isYamlFile(fileName) || isEnvFile(fileName); + } - AnalyzedZipHeatFiles analyzeFilesNotEligibleForModulesFromFileAnalyzer(Map files) throws IOException; + AnalyzedZipHeatFiles analyzeFilesNotEligibleForModulesFromFileAnalyzer(Map files) throws IOException; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionDataExtractor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionDataExtractor.java index 0b82638277..3696bd33fd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionDataExtractor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionDataExtractor.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.composition; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -25,7 +24,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionData public interface CompositionDataExtractor { - CompositionData extractServiceCompositionData(ToscaServiceModel toscaServiceModel); + CompositionData extractServiceCompositionData(ToscaServiceModel toscaServiceModel); - String getComponentDisplayName(String componentName); + String getComponentDisplayName(String componentName); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java index d33533a7d0..7467d59c04 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java @@ -15,9 +15,15 @@ * * Modifications copyright (c) 2021 Nokia */ - package org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; +import java.util.Optional; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -30,61 +36,42 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHe import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.util.List; -import java.util.Map; -import java.util.Optional; - public interface CandidateService { - Optional validateNonEmptyFileToUpload(InputStream heatFileToUpload, - String fileSuffix); - Optional validateRawZipData(String fileSuffix, byte[] uploadedFileData); + Optional validateNonEmptyFileToUpload(InputStream heatFileToUpload, String fileSuffix); + + Optional validateRawZipData(String fileSuffix, byte[] uploadedFileData); - OrchestrationTemplateCandidateData createCandidateDataEntity( - CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, - AnalyzedZipHeatFiles analyzedZipHeatFiles); + OrchestrationTemplateCandidateData createCandidateDataEntity(CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles); - void updateCandidateUploadData(String vspId, Version version, - OrchestrationTemplateCandidateData uploadData); + void updateCandidateUploadData(String vspId, Version version, OrchestrationTemplateCandidateData uploadData); - Optional getOrchestrationTemplateCandidateFileDataStructure(String vspId, - Version version); + Optional getOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version); - void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure); + void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure); - Optional getOrchestrationTemplateCandidate(String vspId, - Version version); + Optional getOrchestrationTemplateCandidate(String vspId, Version version); - Optional getOrchestrationTemplateCandidateInfo(String vspId, - Version version); + Optional getOrchestrationTemplateCandidateInfo(String vspId, Version version); - byte[] getZipData(ByteBuffer contentData) throws IOException; + byte[] getZipData(ByteBuffer contentData) throws IOException; - void deleteOrchestrationTemplateCandidate(String vspId, Version version); + void deleteOrchestrationTemplateCandidate(String vspId, Version version); - Optional fetchZipFileByteArrayInputStream(String vspId, - OrchestrationTemplateCandidateData candidateDataEntity, - String manifest, - OnboardingTypesEnum type, - Map> uploadErrors); + Optional fetchZipFileByteArrayInputStream(String vspId, OrchestrationTemplateCandidateData candidateDataEntity, + String manifest, OnboardingTypesEnum type, + Map> uploadErrors); - byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, - OnboardingTypesEnum type) throws IOException; + byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, OnboardingTypesEnum type) throws IOException; - Optional createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles); + Optional createManifest(VspDetails vspDetails, FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles); - String createManifest(VspDetails vspDetails, FilesDataStructure structure); + String createManifest(VspDetails vspDetails, FilesDataStructure structure); - String createManifestFromExisting(VspDetails vspDetails, FilesDataStructure structure, ManifestContent existingManifest); + String createManifestFromExisting(VspDetails vspDetails, FilesDataStructure structure, ManifestContent existingManifest); - Optional> validateFileDataStructure(FilesDataStructure filesDataStructure); + Optional> validateFileDataStructure(FilesDataStructure filesDataStructure); - void updateValidationData(String vspId, Version version, ValidationStructureList validationData); + void updateValidationData(String vspId, Version version, ValidationStructureList validationData); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/ManifestCreator.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/ManifestCreator.java index 90490e7153..22ec1c3f79 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/ManifestCreator.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/ManifestCreator.java @@ -8,9 +8,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,24 +18,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule; +import java.util.Optional; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; -import java.util.Optional; - public interface ManifestCreator { - Optional createManifest(VspDetails vspDetails, FilesDataStructure filesDataStructure); - Optional createManifestFromExisting(VspDetails vspDetails, FilesDataStructure filesDataStructure, ManifestContent existingManifest); + Optional createManifest(VspDetails vspDetails, FilesDataStructure filesDataStructure); + + Optional createManifestFromExisting(VspDetails vspDetails, FilesDataStructure filesDataStructure, + ManifestContent existingManifest); - Optional createManifest(VspDetails vspDetails, FileContentHandler - fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles); + Optional createManifest(VspDetails vspDetails, FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles); - boolean isFileBaseFile(String fileName); + boolean isFileBaseFile(String fileName); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java index 04d240a8e6..fffdaef75a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,134 +17,126 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; import org.openecomp.sdc.vendorsoftwareproduct.services.HeatFileAnalyzer; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; -import java.io.*; -import java.util.*; -import java.util.regex.Pattern; - public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { - private static final String HEAT_IDENTIFIER_REGEX = "^heat_template_version:.*"; - private static final String HEAT_RESOURCES_REGEX = "^resources:\\s*$"; - private static final String HEAT_PARAMETERS_REGEX = "^parameters:\\s*$"; - private static final String HEAT_CONDITIONS_REGEX = "^conditions:\\s*$"; - private static final String HEAT_OUTPUTS_REGEX = "^outputs:\\s*$"; - private static final String HEAT_PARAMETER_GROUP_REGEX = "^parameter_groups:\\s*$"; - private static final String HEAT_DESCRIPTION_REGEX = "^description:\\s*$"; - //allowing spaces at start followed by 'type:' + spaces + any characters + ('.yml' or '.yaml')+ - // spaces - private static final String HEAT_NESTED_RESOURCE_REGEX = "\\s*type:\\s*\\S*.(yml|yaml)\\s*$"; - - - private static final String IDENTIFIER = "IDENTIFIER"; - private static final String RESOURCES = "RESOURCES"; - private static final String PARAMETERS = "PARAMETERS"; - private static final String CONDITIONS = "CONDITIONS"; - private static final String OUTPUTS = "OUTPUTS"; - private static final String PARAMETER_GROUP = "PARAMETER_GROUP"; - private static final String DESCRIPTION = "DESCRIPTION"; - private static final String NESTED_PATTERN = "NESTED_PATTERN"; - - private final Map patterns; - - public HeatFileAnalyzerRowDataImpl() { - patterns = new HashMap<>(); - patterns.put(IDENTIFIER, Pattern.compile(HEAT_IDENTIFIER_REGEX)); - patterns.put(RESOURCES, Pattern.compile(HEAT_RESOURCES_REGEX)); - patterns.put(PARAMETERS, Pattern.compile(HEAT_PARAMETERS_REGEX)); - patterns.put(CONDITIONS, Pattern.compile(HEAT_CONDITIONS_REGEX)); - patterns.put(OUTPUTS, Pattern.compile(HEAT_OUTPUTS_REGEX)); - patterns.put(PARAMETER_GROUP, Pattern.compile(HEAT_PARAMETER_GROUP_REGEX)); - patterns.put(DESCRIPTION, Pattern.compile(HEAT_DESCRIPTION_REGEX)); - patterns.put(NESTED_PATTERN, Pattern.compile(HEAT_NESTED_RESOURCE_REGEX)); - } - - @Override - public AnalyzedZipHeatFiles analyzeFilesNotEligibleForModulesFromFileAnalyzer(Map files) - throws IOException { - AnalyzedZipHeatFiles analyzedZipHeatFiles = new AnalyzedZipHeatFiles(); - for (Map.Entry fileData : files.entrySet()) { - String fileName = fileData.getKey(); - if (!HeatFileAnalyzer.isYamlFile(fileName)) { - analyzedZipHeatFiles.addOtherNonModuleFile(fileName); - continue; - } - - boolean foundHeatIdentifier = false; - try (InputStream is = new ByteArrayInputStream(fileData.getValue()); - BufferedReader bfReader = new BufferedReader(new InputStreamReader(is))) { + private static final String HEAT_IDENTIFIER_REGEX = "^heat_template_version:.*"; + private static final String HEAT_RESOURCES_REGEX = "^resources:\\s*$"; + private static final String HEAT_PARAMETERS_REGEX = "^parameters:\\s*$"; + private static final String HEAT_CONDITIONS_REGEX = "^conditions:\\s*$"; + private static final String HEAT_OUTPUTS_REGEX = "^outputs:\\s*$"; + private static final String HEAT_PARAMETER_GROUP_REGEX = "^parameter_groups:\\s*$"; + private static final String HEAT_DESCRIPTION_REGEX = "^description:\\s*$"; + //allowing spaces at start followed by 'type:' + spaces + any characters + ('.yml' or '.yaml')+ + + // spaces + private static final String HEAT_NESTED_RESOURCE_REGEX = "\\s*type:\\s*\\S*.(yml|yaml)\\s*$"; + private static final String IDENTIFIER = "IDENTIFIER"; + private static final String RESOURCES = "RESOURCES"; + private static final String PARAMETERS = "PARAMETERS"; + private static final String CONDITIONS = "CONDITIONS"; + private static final String OUTPUTS = "OUTPUTS"; + private static final String PARAMETER_GROUP = "PARAMETER_GROUP"; + private static final String DESCRIPTION = "DESCRIPTION"; + private static final String NESTED_PATTERN = "NESTED_PATTERN"; + private final Map patterns; + + public HeatFileAnalyzerRowDataImpl() { + patterns = new HashMap<>(); + patterns.put(IDENTIFIER, Pattern.compile(HEAT_IDENTIFIER_REGEX)); + patterns.put(RESOURCES, Pattern.compile(HEAT_RESOURCES_REGEX)); + patterns.put(PARAMETERS, Pattern.compile(HEAT_PARAMETERS_REGEX)); + patterns.put(CONDITIONS, Pattern.compile(HEAT_CONDITIONS_REGEX)); + patterns.put(OUTPUTS, Pattern.compile(HEAT_OUTPUTS_REGEX)); + patterns.put(PARAMETER_GROUP, Pattern.compile(HEAT_PARAMETER_GROUP_REGEX)); + patterns.put(DESCRIPTION, Pattern.compile(HEAT_DESCRIPTION_REGEX)); + patterns.put(NESTED_PATTERN, Pattern.compile(HEAT_NESTED_RESOURCE_REGEX)); + } - String line; - boolean isResourcesSection = false; - Set nestedFilesNames = new HashSet<>(); - while ((line = bfReader.readLine()) != null) { - if (!foundHeatIdentifier && isMatch(patterns.get(IDENTIFIER), line)) { - foundHeatIdentifier = true; - analyzedZipHeatFiles.addModuleFile(fileName); - if (isResourcesSection) // it means the identifier is located after the resources - // section - { - break; + @Override + public AnalyzedZipHeatFiles analyzeFilesNotEligibleForModulesFromFileAnalyzer(Map files) throws IOException { + AnalyzedZipHeatFiles analyzedZipHeatFiles = new AnalyzedZipHeatFiles(); + for (Map.Entry fileData : files.entrySet()) { + String fileName = fileData.getKey(); + if (!HeatFileAnalyzer.isYamlFile(fileName)) { + analyzedZipHeatFiles.addOtherNonModuleFile(fileName); + continue; } - } else if (isMatch(patterns.get(RESOURCES), line)) { - isResourcesSection = true; - } else if (isResourceSectionEnd(line, isResourcesSection)) { - if (foundHeatIdentifier) { - break; + boolean foundHeatIdentifier = false; + try (InputStream is = new ByteArrayInputStream(fileData.getValue()); BufferedReader bfReader = new BufferedReader( + new InputStreamReader(is))) { + String line; + boolean isResourcesSection = false; + Set nestedFilesNames = new HashSet<>(); + while ((line = bfReader.readLine()) != null) { + if (!foundHeatIdentifier && isMatch(patterns.get(IDENTIFIER), line)) { + foundHeatIdentifier = true; + analyzedZipHeatFiles.addModuleFile(fileName); + if (isResourcesSection) // it means the identifier is located after the resources + + // section + { + break; + } + } else if (isMatch(patterns.get(RESOURCES), line)) { + isResourcesSection = true; + } else if (isResourceSectionEnd(line, isResourcesSection)) { + if (foundHeatIdentifier) { + break; + } + } else if (isResourcesSection) { + Optional optionalNestedFileName = fetchNestedFileName(line); + optionalNestedFileName.ifPresent(nestedFilesNames::add); + } + } + analyzedZipHeatFiles.addNestedFiles(fetchFileNamesToReturn(nestedFilesNames, foundHeatIdentifier)); } - } else if (isResourcesSection) { - Optional optionalNestedFileName = fetchNestedFileName(line); - optionalNestedFileName - .ifPresent(nestedFilesNames::add); - } } - analyzedZipHeatFiles.addNestedFiles(fetchFileNamesToReturn(nestedFilesNames, - foundHeatIdentifier)); - } + return analyzedZipHeatFiles; } - return analyzedZipHeatFiles; - } - - private Optional fetchNestedFileName(String line) { - if (isMatch(patterns.get(NESTED_PATTERN), line)) { - String trimmedLine = line.trim(); - String nestedFileName = trimmedLine - .substring(trimmedLine.indexOf("type:") + "type:".length(), trimmedLine.length()) - .trim(); - return Optional.of(nestedFileName); + private Optional fetchNestedFileName(String line) { + if (isMatch(patterns.get(NESTED_PATTERN), line)) { + String trimmedLine = line.trim(); + String nestedFileName = trimmedLine.substring(trimmedLine.indexOf("type:") + "type:".length(), trimmedLine.length()).trim(); + return Optional.of(nestedFileName); + } + return Optional.empty(); } - return Optional.empty(); - } - private Set fetchFileNamesToReturn(Set filesNamesToReturn, - boolean foundHeatIdentifier) { - if (!foundHeatIdentifier) { - return new HashSet<>(); - } else { - return filesNamesToReturn; + private Set fetchFileNamesToReturn(Set filesNamesToReturn, boolean foundHeatIdentifier) { + if (!foundHeatIdentifier) { + return new HashSet<>(); + } else { + return filesNamesToReturn; + } } - } - private boolean isResourceSectionEnd(String line, boolean isResourcesSection) { - return isResourcesSection && isStartOfNonResourcesHeatSection(line); - } - - private boolean isStartOfNonResourcesHeatSection(String line) { - return isMatch(patterns.get(PARAMETERS), line) || - isMatch(patterns.get(CONDITIONS), line) || - isMatch(patterns.get(OUTPUTS), line) || - isMatch(patterns.get(PARAMETER_GROUP), line) || - isMatch(patterns.get(DESCRIPTION), line); - } + private boolean isResourceSectionEnd(String line, boolean isResourcesSection) { + return isResourcesSection && isStartOfNonResourcesHeatSection(line); + } - private boolean isMatch(Pattern pattern, String line) { - return pattern.matcher(line).matches(); - } + private boolean isStartOfNonResourcesHeatSection(String line) { + return isMatch(patterns.get(PARAMETERS), line) || isMatch(patterns.get(CONDITIONS), line) || isMatch(patterns.get(OUTPUTS), line) || isMatch( + patterns.get(PARAMETER_GROUP), line) || isMatch(patterns.get(DESCRIPTION), line); + } + private boolean isMatch(Pattern pattern, String line) { + return pattern.matcher(line).matches(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIService.java index 8b56b3fbc0..dad05b64f2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIService.java @@ -17,27 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi; +import com.vdurmont.semver4j.Semver; import java.io.IOException; import java.nio.file.Path; import java.util.Map; import java.util.Optional; - import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.tosca.csar.Manifest; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import com.vdurmont.semver4j.Semver; - - public interface ETSIService { /** - * Checks package structure is CSAR with TOSCA-Metadata directory according to SOL004 v2.5.1 - * and contains mandatory Entries in Tosca.meta + * Checks package structure is CSAR with TOSCA-Metadata directory according to SOL004 v2.5.1 and contains mandatory Entries in Tosca.meta + * * @param handler contains csar artifacts * @return true if all condition matched, false otherwise * @throws IOException when TOSCA.meta file is invalid @@ -50,20 +46,19 @@ public interface ETSIService { * @param handler The file handler containing the artifacts to move. * @return A Map with pairs of from and to path of the moved artifacts. */ - Optional> moveNonManoFileToArtifactFolder(final FileContentHandler handler) - throws IOException; + Optional> moveNonManoFileToArtifactFolder(final FileContentHandler handler) throws IOException; /** * Updates the main descriptor paths referring the artifacts that were moved. * - * @param toscaServiceModel The tosca service model containing the main descriptor. + * @param toscaServiceModel The tosca service model containing the main descriptor. * @param fromToMovedArtifactMap A Map representing the from and to artifacts path changes. */ - void updateMainDescriptorPaths(final ToscaServiceModel toscaServiceModel, - final Map fromToMovedArtifactMap); + void updateMainDescriptorPaths(final ToscaServiceModel toscaServiceModel, final Map fromToMovedArtifactMap); /** * Retrieves the manifest file from the CSAR + * * @param handler contains csar artifacts * @throws IOException when TOSCA.meta file or manifest file is invalid */ @@ -71,6 +66,7 @@ public interface ETSIService { /** * Determines the type of resource that the CSAR represents + * * @param handler contains csar artifacts * @throws IOException when TOSCA.meta file or manifest file is invalid */ @@ -78,6 +74,7 @@ public interface ETSIService { /** * Determines the type of resource that the CSAR represents + * * @param manifest contains manifest content * @throws IOException when TOSCA.meta file or manifest file is invalid */ @@ -85,9 +82,9 @@ public interface ETSIService { Path getOriginalManifestPath(final FileContentHandler handler) throws IOException; - /** * Determines the highest compatible specification version based on ETSI manifest file + * * @param handler contains csar artifacts * @return Semver representing highest compatible specification version */ @@ -95,6 +92,7 @@ public interface ETSIService { /** * Verifies if SOL004 3.3.1 manifest file has onap_cnf_helm non mano entry + * * @return true if manifest files has onap_cnf_helm non mano entry */ boolean hasCnfEnhancements(final FileContentHandler fileContentHandler) throws IOException; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGenerator.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGenerator.java index 4aaa9a8a03..35bed3852b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGenerator.java @@ -12,12 +12,14 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator; import freemarker.template.Template; import freemarker.template.TemplateException; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -25,39 +27,34 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEnti import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateInput; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - public class SchemaGenerator { - public static final String SCHEMA_GENERATION_ERROR = "SCHEMA_GENERATION_ERROR"; - private SchemaGenerator() { - // Utility classes, which are a collection of static members, are not meant to be instantiated - } - /** - * Generate string. - * - * @param schemaTemplateContext the schema template context - * @param entityType the entity type - * @param input the input - * @return the string - */ - public static String generate(SchemaTemplateContext schemaTemplateContext, - CompositionEntityType entityType, SchemaTemplateInput input) { - Template schemaTemplate = - SchemaGeneratorConfig.getSchemaTemplate(schemaTemplateContext, entityType); - return processTemplate(input, schemaTemplate); - } + public static final String SCHEMA_GENERATION_ERROR = "SCHEMA_GENERATION_ERROR"; + + private SchemaGenerator() { + // Utility classes, which are a collection of static members, are not meant to be instantiated + } + + /** + * Generate string. + * + * @param schemaTemplateContext the schema template context + * @param entityType the entity type + * @param input the input + * @return the string + */ + public static String generate(SchemaTemplateContext schemaTemplateContext, CompositionEntityType entityType, SchemaTemplateInput input) { + Template schemaTemplate = SchemaGeneratorConfig.getSchemaTemplate(schemaTemplateContext, entityType); + return processTemplate(input, schemaTemplate); + } - private static String processTemplate(SchemaTemplateInput input, Template schemaTemplate) { - try (Writer writer = new StringWriter(1024)) { - schemaTemplate.process(input, writer); - return writer.toString(); - } catch (IOException | TemplateException exception) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(SCHEMA_GENERATION_ERROR).withMessage(exception.getMessage()).build(), exception); + private static String processTemplate(SchemaTemplateInput input, Template schemaTemplate) { + try (Writer writer = new StringWriter(1024)) { + schemaTemplate.process(input, writer); + return writer.toString(); + } catch (IOException | TemplateException exception) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(SCHEMA_GENERATION_ERROR) + .withMessage(exception.getMessage()).build(), exception); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorConfig.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorConfig.java index 3937ca2f2e..9d00e45bc5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorConfig.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/schemagenerator/SchemaGeneratorConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.schemagenerator; import freemarker.cache.StringTemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateExceptionHandler; +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; @@ -33,122 +36,106 @@ import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTemplateContext; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - public class SchemaGeneratorConfig { - public static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR = - "SCHEMA_GENERATOR_INITIALIZATION_ERROR"; - public static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG = - "Error occurred while loading questionnaire schema schemaTemplates"; - private static final String CONFIGURATION_NAMESPACE = "vsp.schemaTemplates"; - private static Map schemaTemplates = new HashMap<>(); - private static ApplicationConfig applicationConfig = - ApplicationConfigFactory.getInstance().createInterface(); - private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); - private static StringTemplateLoader stringLoader = new StringTemplateLoader(); - - static { - configuration.setClassLoaderForTemplateLoading(SchemaGenerator.class.getClassLoader(), - File.pathSeparator); - configuration.setDefaultEncoding("UTF-8"); - configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); - configuration.setLogTemplateExceptions(true); - configuration.setTemplateLoader(stringLoader); - } - - public static void insertSchemaTemplate(SchemaTemplateContext schemaTemplateContext, - CompositionEntityType entityType, - String schemaTemplateString) { - applicationConfig.insertValue(CONFIGURATION_NAMESPACE, - new SchemaTemplateId(schemaTemplateContext, entityType).toString(), schemaTemplateString); - } - - /** - * Gets schema template. - * - * @param schemaTemplateContext the schema template context - * @param entityType the entity type - * @return the schema template - */ - public static Template getSchemaTemplate(SchemaTemplateContext schemaTemplateContext, - CompositionEntityType entityType) { - SchemaTemplateId id = new SchemaTemplateId(schemaTemplateContext, entityType); - ConfigurationData configurationData = - applicationConfig.getConfigurationData(CONFIGURATION_NAMESPACE, id.toString()); - - SchemaTemplate schemaTemplate = schemaTemplates.get(id); - if (schemaTemplate == null || schemaTemplate.timestamp != configurationData.getTimeStamp()) { - stringLoader.putTemplate(id.toString(), configurationData.getValue()); - Template template; - try { - template = configuration.getTemplate(id.toString()); - } catch (IOException exception) { - throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(SCHEMA_GENERATOR_INITIALIZATION_ERROR) - .withMessage(SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG).build(), exception); - } - schemaTemplate = new SchemaTemplate(template, configurationData.getTimeStamp()); - schemaTemplates.put(id, schemaTemplate); + public static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR = "SCHEMA_GENERATOR_INITIALIZATION_ERROR"; + public static final String SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG = "Error occurred while loading questionnaire schema schemaTemplates"; + private static final String CONFIGURATION_NAMESPACE = "vsp.schemaTemplates"; + private static Map schemaTemplates = new HashMap<>(); + private static ApplicationConfig applicationConfig = ApplicationConfigFactory.getInstance().createInterface(); + private static Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); + private static StringTemplateLoader stringLoader = new StringTemplateLoader(); + + static { + configuration.setClassLoaderForTemplateLoading(SchemaGenerator.class.getClassLoader(), File.pathSeparator); + configuration.setDefaultEncoding("UTF-8"); + configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); + configuration.setLogTemplateExceptions(true); + configuration.setTemplateLoader(stringLoader); } - return schemaTemplate.template; - } - - private static class SchemaTemplateId { - private SchemaTemplateContext context; - private CompositionEntityType entityType; - public SchemaTemplateId(SchemaTemplateContext context, CompositionEntityType entityType) { - this.context = context; - this.entityType = entityType; + public static void insertSchemaTemplate(SchemaTemplateContext schemaTemplateContext, CompositionEntityType entityType, + String schemaTemplateString) { + applicationConfig + .insertValue(CONFIGURATION_NAMESPACE, new SchemaTemplateId(schemaTemplateContext, entityType).toString(), schemaTemplateString); } - @Override - public String toString() { - return context + "." + entityType; + /** + * Gets schema template. + * + * @param schemaTemplateContext the schema template context + * @param entityType the entity type + * @return the schema template + */ + public static Template getSchemaTemplate(SchemaTemplateContext schemaTemplateContext, CompositionEntityType entityType) { + SchemaTemplateId id = new SchemaTemplateId(schemaTemplateContext, entityType); + ConfigurationData configurationData = applicationConfig.getConfigurationData(CONFIGURATION_NAMESPACE, id.toString()); + SchemaTemplate schemaTemplate = schemaTemplates.get(id); + if (schemaTemplate == null || schemaTemplate.timestamp != configurationData.getTimeStamp()) { + stringLoader.putTemplate(id.toString(), configurationData.getValue()); + Template template; + try { + template = configuration.getTemplate(id.toString()); + } catch (IOException exception) { + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId(SCHEMA_GENERATOR_INITIALIZATION_ERROR) + .withMessage(SCHEMA_GENERATOR_INITIALIZATION_ERROR_MSG).build(), exception); + } + schemaTemplate = new SchemaTemplate(template, configurationData.getTimeStamp()); + schemaTemplates.put(id, schemaTemplate); + } + return schemaTemplate.template; } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - - SchemaTemplateId that = (SchemaTemplateId) obj; - - if (entityType != that.entityType) { - return false; - } - if (context != that.context) { - return false; - } - - return true; + private static class SchemaTemplateId { + + private SchemaTemplateContext context; + private CompositionEntityType entityType; + + public SchemaTemplateId(SchemaTemplateContext context, CompositionEntityType entityType) { + this.context = context; + this.entityType = entityType; + } + + @Override + public String toString() { + return context + "." + entityType; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + SchemaTemplateId that = (SchemaTemplateId) obj; + if (entityType != that.entityType) { + return false; + } + if (context != that.context) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int result = entityType != null ? entityType.hashCode() : 0; + result = 31 * result + (context != null ? context.hashCode() : 0); + return result; + } } - @Override - public int hashCode() { - int result = entityType != null ? entityType.hashCode() : 0; - result = 31 * result + (context != null ? context.hashCode() : 0); - return result; - } - } + private static class SchemaTemplate { - private static class SchemaTemplate { - private Template template; - private long timestamp; + private Template template; + private long timestamp; - public SchemaTemplate(Template template, long timestamp) { - this.template = template; - this.timestamp = timestamp; + public SchemaTemplate(Template template, long timestamp) { + this.template = template; + this.timestamp = timestamp; + } } - } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java index eb4b29d742..726fcbf21f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.utils; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.common.errors.Messages; @@ -37,70 +42,52 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.impl.HeatFileAnalyzerRow import org.openecomp.sdc.vendorsoftwareproduct.types.CandidateDataEntityTo; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.AnalyzedZipHeatFiles; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - public class CandidateEntityBuilder { - private final CandidateService candidateService; - - public CandidateEntityBuilder(CandidateService candidateService) { - this.candidateService = candidateService; - } - public OrchestrationTemplateCandidateData buildCandidateEntityFromZip( - VspDetails vspDetails, byte[] uploadedFileData, FileContentHandler contentMap, - Map> uploadErrors) throws Exception { - //mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); + private final CandidateService candidateService; - try (InputStream zipFileManifest = contentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { - HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); - AnalyzedZipHeatFiles analyzedZipHeatFiles = - heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); - HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); - - CandidateDataEntityTo candidateDataEntityTo = - new CandidateDataEntityTo(vspDetails.getId(), vspDetails.getVersion(), uploadedFileData, - tree, contentMap); - candidateDataEntityTo.setErrors(uploadErrors); - OrchestrationTemplateCandidateData candidateDataEntity = - candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, - analyzedZipHeatFiles); - return candidateDataEntity; + public CandidateEntityBuilder(CandidateService candidateService) { + this.candidateService = candidateService; } - } - private HeatStructureTree getHeatStructureTree(VspDetails vspDetails, - FileContentHandler contentMap, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws IOException { - addManifestToFileContentMapIfNotExist(vspDetails, contentMap, analyzedZipHeatFiles); - HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(contentMap); - heatTreeManager.createTree(); - return heatTreeManager.getTree(); - } + public OrchestrationTemplateCandidateData buildCandidateEntityFromZip(VspDetails vspDetails, byte[] uploadedFileData, + FileContentHandler contentMap, Map> uploadErrors) + throws Exception { + //mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); + try (InputStream zipFileManifest = contentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); + AnalyzedZipHeatFiles analyzedZipHeatFiles = heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); + HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); + CandidateDataEntityTo candidateDataEntityTo = new CandidateDataEntityTo(vspDetails.getId(), vspDetails.getVersion(), uploadedFileData, + tree, contentMap); + candidateDataEntityTo.setErrors(uploadErrors); + OrchestrationTemplateCandidateData candidateDataEntity = candidateService + .createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, analyzedZipHeatFiles); + return candidateDataEntity; + } + } - private void addManifestToFileContentMapIfNotExist(VspDetails vspDetails, - FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws IOException { - try (InputStream manifest = fileContentHandler.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + private HeatStructureTree getHeatStructureTree(VspDetails vspDetails, FileContentHandler contentMap, AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws IOException { + addManifestToFileContentMapIfNotExist(vspDetails, contentMap, analyzedZipHeatFiles); + HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(contentMap); + heatTreeManager.createTree(); + return heatTreeManager.getTree(); + } - if (Objects.isNull(manifest)) { - Optional manifestContentOptional = - candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); - if (!manifestContentOptional.isPresent()) { - throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); + private void addManifestToFileContentMapIfNotExist(VspDetails vspDetails, FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + try (InputStream manifest = fileContentHandler.getFileContentAsStream(SdcCommon.MANIFEST_NAME)) { + if (Objects.isNull(manifest)) { + Optional manifestContentOptional = candidateService + .createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + if (!manifestContentOptional.isPresent()) { + throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); + } + ManifestContent manifestContent = manifestContentOptional.get(); + fileContentHandler.addFile(SdcCommon.MANIFEST_NAME, String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); + } + } finally { } - ManifestContent manifestContent = manifestContentOptional.get(); - fileContentHandler.addFile( - SdcCommon.MANIFEST_NAME, - String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); - } - } finally { } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java index 3a535e125e..89090aaeb4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types; import java.util.HashMap; @@ -49,13 +48,11 @@ public class CandidateDataEntityTo { * @param tree the tree * @param contentMap the content map */ - public CandidateDataEntityTo(String vspId, Version version, byte[] uploadedFileData, - HeatStructureTree tree, FileContentHandler contentMap) { + public CandidateDataEntityTo(String vspId, Version version, byte[] uploadedFileData, HeatStructureTree tree, FileContentHandler contentMap) { this.vspId = vspId; this.version = version; this.uploadedFileData = uploadedFileData; this.tree = tree; this.contentMap = contentMap; } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/AnalyzedZipHeatFiles.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/AnalyzedZipHeatFiles.java index 63067e3ede..d4d658b67e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/AnalyzedZipHeatFiles.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/AnalyzedZipHeatFiles.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat; import java.util.Collection; @@ -62,5 +61,4 @@ public class AnalyzedZipHeatFiles { public Collection getFilesNotEligbleForModules() { return CollectionUtils.union(this.getNestedFiles(), this.getOtherNonModuleFiles()); } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Constants.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Constants.java index 4e19dd67e9..c834fccae5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Constants.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Constants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat; public class Constants { - public static final String BASE_HEAT_REGEX = "(^base_.*\\.|.*_base\\.|.*_base_.*\\.|^base\\.)(yaml|yml)$"; - public static final String VOL_FILE_NAME_SUFFIX = "_volume"; - public static final String ENV_FILE_EXTENSION = ".env"; + + public static final String BASE_HEAT_REGEX = "(^base_.*\\.|.*_base\\.|.*_base_.*\\.|^base\\.)(yaml|yml)$"; + public static final String VOL_FILE_NAME_SUFFIX = "_volume"; + public static final String ENV_FILE_EXTENSION = ".env"; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/FilesDataStructure.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/FilesDataStructure.java index 22c4534b6c..3c0bf8eb3e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/FilesDataStructure.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/FilesDataStructure.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat; import java.util.ArrayList; @@ -35,5 +34,4 @@ public class FilesDataStructure { private List unassigned = new ArrayList<>(); private List artifacts = new ArrayList<>(); private List nested = new ArrayList<>(); - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Module.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Module.java index 25a004e890..30c8e0796a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Module.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/candidateheat/Module.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat; import lombok.Getter; @@ -37,5 +36,4 @@ public class Module { private String vol; private String volEnv; private FileData.Type type; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Component.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Component.java index de15c64433..7ae20c6975 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Component.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Component.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import java.util.List; @@ -34,5 +33,4 @@ public class Component { private List nics; private List images; private List compute; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentComputeAssociation.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentComputeAssociation.java index c58a1df163..0130b708bd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentComputeAssociation.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentComputeAssociation.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.Getter; @@ -31,5 +30,4 @@ public class ComponentComputeAssociation { private String componentId; private String computeFlavorId; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentData.java index 8e0d1874c2..cfc97bdf74 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComponentData.java @@ -17,7 +17,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.EqualsAndHashCode; @@ -34,5 +33,4 @@ public class ComponentData implements CompositionDataEntity { private String name; private String description; private String displayName; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionData.java index 7809cf5949..c0b239533e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import java.util.List; @@ -32,5 +31,4 @@ public class CompositionData { private List networks; private List components; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionDataEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionDataEntity.java index 9c09b0ded4..0194c57477 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionDataEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionDataEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,8 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; public interface CompositionDataEntity { + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityId.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityId.java index c361179a50..ec026436f8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityId.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityId.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.EqualsAndHashCode; @@ -36,9 +35,6 @@ public class CompositionEntityId { @Override public String toString() { - return parentId == null - ? id - : parentId + "/" + id; + return parentId == null ? id : parentId + "/" + id; } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityType.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityType.java index 2b1ea16889..3c92977040 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; - -public enum CompositionEntityType { - vsp, - network, - component, - deployment, - image, - nic, - compute -} +public enum CompositionEntityType {vsp, network, component, deployment, image, nic, compute} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityValidationData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityValidationData.java index 8bb0881fa7..b3116ce0a5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityValidationData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/CompositionEntityValidationData.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import java.util.ArrayList; @@ -57,5 +56,4 @@ public class CompositionEntityValidationData { } subEntitiesValidationData.add(subEntityValidationData); } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComputeData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComputeData.java index bff5df6b08..a78d62ca4d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComputeData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ComputeData.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.EqualsAndHashCode; @@ -39,5 +38,4 @@ public class ComputeData implements CompositionDataEntity { public ComputeData(String name) { this.name = name; } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/DeploymentFlavor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/DeploymentFlavor.java index 6357799e65..6d802a3ef4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/DeploymentFlavor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/DeploymentFlavor.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; - import java.util.List; import lombok.Getter; import lombok.NoArgsConstructor; @@ -35,5 +33,4 @@ public class DeploymentFlavor implements CompositionDataEntity { private String description; private String featureGroupId; private List componentComputeAssociations; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ExtractCompositionDataContext.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ExtractCompositionDataContext.java index ef202d013d..b5ac61fc36 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ExtractCompositionDataContext.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ExtractCompositionDataContext.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import java.util.ArrayList; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Image.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Image.java index 2c624721cb..e3e19bea49 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Image.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Image.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.Getter; @@ -35,5 +34,4 @@ public class Image implements CompositionDataEntity { public Image(String fileName) { this.fileName = fileName; } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageData.java index 191a454091..0c4346bcd5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.AllArgsConstructor; @@ -33,5 +32,4 @@ public class ImageData implements CompositionDataEntity { private String fileName; private String description; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageFormat.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageFormat.java index a9de3483ef..d12ca6739d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageFormat.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/ImageFormat.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; -public enum ImageFormat { - aki, - ami, - ari, - iso, - qcow2, - raw, - vdi, - vhd, - vmdk -} +public enum ImageFormat {aki, ami, ari, iso, qcow2, raw, vdi, vhd, vmdk} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Network.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Network.java index cc5a5afbae..b0cf064d9b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Network.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Network.java @@ -19,7 +19,6 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.EqualsAndHashCode; @@ -35,5 +34,4 @@ public class Network implements CompositionDataEntity { private String name; private boolean dhcp; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/NetworkType.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/NetworkType.java index d90135a205..c8c60c861a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/NetworkType.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/NetworkType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; -public enum NetworkType { - Internal, - External -} +public enum NetworkType {Internal, External} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Nic.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Nic.java index cc23d24407..96beed2c3e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Nic.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/composition/Nic.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.composition; import lombok.EqualsAndHashCode; @@ -37,5 +36,4 @@ public class Nic implements CompositionDataEntity { private String networkName; private NetworkType networkType; private String networkDescription; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/ComponentQuestionnaire.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/ComponentQuestionnaire.java index 6699671d61..5c61b8f787 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/ComponentQuestionnaire.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/ComponentQuestionnaire.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -40,5 +38,4 @@ public class ComponentQuestionnaire { private HighAvailabilityAndLoadBalancing highAvailabilityAndLoadBalancing; private Network network; private Storage storage; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/Compute.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/Compute.java index dd5fb9057c..60fe72ada6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/Compute.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/Compute.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute; import lombok.Getter; @@ -32,5 +31,4 @@ public class Compute { private GuestOS guestOS; private NumOfVMs numOfVMs; private VmSizing vmSizing; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java index 54de06b1c4..16aef5866d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute; import lombok.Getter; @@ -32,5 +31,4 @@ public class GuestOS { private String name; private String tools; private Number bitSize; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/NumOfVMs.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/NumOfVMs.java index f135ba78ff..37bb2573b8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/NumOfVMs.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/NumOfVMs.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute; import lombok.Getter; @@ -33,6 +32,4 @@ public class NumOfVMs { private int maximum; private String CpuOverSubscriptionRatio; private String MemoryRAM; - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java index 0f72d03d10..9bf3ff4c6b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute; import lombok.Getter; @@ -35,5 +34,4 @@ public class VmSizing { private Number IOOperationsPerSec; private String cpuOverSubscriptionRatio; private String memoryRAM; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/General.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/General.java index 328715b90e..6482faff8a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/General.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/General.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general; import lombok.Getter; @@ -25,12 +24,11 @@ import lombok.Setter; @NoArgsConstructor public class General { + protected Recovery recovery; private Hypervisor hypervisor; private Image image; - protected Recovery recovery; private String dnsConfiguration; private String vmCloneUsage; private String nfcNamingCode; private String nfcFunction; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Hypervisor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Hypervisor.java index d2ef0456a9..7ae9cb3ccd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Hypervisor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Hypervisor.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general; import lombok.Getter; @@ -32,5 +31,4 @@ public class Hypervisor { private String hypervisor; private String drivers; private String containerFeaturesDescription; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java index e00d022532..989914a1df 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general; import lombok.Getter; @@ -33,5 +32,4 @@ public class Image { private String providedBy; private Number bootDiskSizePerVM; private Number ephemeralDiskSizePerVM; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java index 255e9f9235..84d253999d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general; import lombok.Getter; @@ -32,5 +31,4 @@ public class Recovery { private Number pointObjective; private Number timeObjective; private String vmProcessFailuresHandling; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/highAvailability/HighAvailabilityAndLoadBalancing.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/highAvailability/HighAvailabilityAndLoadBalancing.java index 75c4e31b15..61ba8b1e00 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/highAvailability/HighAvailabilityAndLoadBalancing.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/highAvailability/HighAvailabilityAndLoadBalancing.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.highAvailability; import lombok.Getter; @@ -37,5 +36,4 @@ public class HighAvailabilityAndLoadBalancing { private String loadDistributionMechanism; private String isComponentMandatory; private String highAvailabilityMode; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/image/ImageDetails.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/image/ImageDetails.java index 9d136a167f..25aa9abe37 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/image/ImageDetails.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/image/ImageDetails.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.image; import lombok.Getter; @@ -32,5 +31,4 @@ public class ImageDetails { private String version; private String format; private String md5; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/Network.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/Network.java index 197df1c277..665d69ed56 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/Network.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/Network.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.network; import lombok.Getter; @@ -30,5 +29,4 @@ import lombok.Setter; public class Network { private NetworkCapacity networkCapacity; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/NetworkCapacity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/NetworkCapacity.java index 8976d8298e..2175000040 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/NetworkCapacity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/network/NetworkCapacity.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.network; import lombok.Getter; @@ -31,5 +30,4 @@ public class NetworkCapacity { private String protocolWithHighestTrafficProfileAcrossAllNICs; private int networkTransactionsPerSecond; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java index 01b6f7fe1f..bd280bc868 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.storage; import lombok.Getter; @@ -33,5 +32,4 @@ public class Backup { private String backupSolution; private String backupNIC; private Number backupStorageSize; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java index ff46e6f095..a266ab9939 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.storage; import lombok.Getter; @@ -33,5 +32,4 @@ public class LogBackup { private Number logBackupFrequency; private int logRetentionPeriod; private String logFileLocation; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/SnapshotBackup.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/SnapshotBackup.java index 4266ffbdf8..a9d49ccbc4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/SnapshotBackup.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/SnapshotBackup.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.storage; import lombok.Getter; @@ -30,5 +29,4 @@ import lombok.Setter; public class SnapshotBackup { private int snapshotFrequency; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Storage.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Storage.java index b41536b720..80fd9c76ff 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Storage.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Storage.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.storage; import lombok.Getter; @@ -32,5 +31,4 @@ public class Storage { private Backup backup; private LogBackup logBackup; private SnapshotBackup snapshotBackup; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/AcceptableJitter.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/AcceptableJitter.java index 0a6b993bde..0fc4c64a15 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/AcceptableJitter.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/AcceptableJitter.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -32,5 +31,4 @@ public class AcceptableJitter { private int mean; private int max; private int variable; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/IpConfiguration.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/IpConfiguration.java index 355fafbc6e..f031f29331 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/IpConfiguration.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/IpConfiguration.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -31,5 +30,4 @@ public class IpConfiguration { private boolean ipv4Required; private boolean ipv6Required; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Network.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Network.java index af0ad1f7f6..3892fcb635 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Network.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Network.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -32,5 +31,4 @@ import lombok.ToString; public class Network { private String networkDescription; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/NicQuestionnaire.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/NicQuestionnaire.java index d41c85506e..9b5dd396d5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/NicQuestionnaire.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/NicQuestionnaire.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -33,5 +32,4 @@ public class NicQuestionnaire { private IpConfiguration ipConfiguration; private Network network; private Sizing sizing; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PacketsAndBytes.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PacketsAndBytes.java index 9eddf3bf6c..2f8788646b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PacketsAndBytes.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PacketsAndBytes.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -31,5 +30,4 @@ public class PacketsAndBytes { private PeakAndAvg packets; private PeakAndAvg bytes; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java index 6e50f3b29b..811c35b89f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -31,5 +30,4 @@ public class PeakAndAvg { private int peak; private Number avg; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Protocols.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Protocols.java index f50d909fbb..2e9c923227 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Protocols.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Protocols.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import java.util.ArrayList; @@ -35,5 +34,4 @@ public class Protocols { private List protocols = new ArrayList<>(); private String protocolWithHighestTrafficProfile; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java index c77d25903d..45797b8d70 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; import lombok.Getter; @@ -35,5 +34,4 @@ public class Sizing { private PacketsAndBytes outflowTrafficPerSecond; private PacketsAndBytes flowLength; private AcceptableJitter acceptableJitter; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/VspQuestionnaire.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/VspQuestionnaire.java index ab416d47d3..1919fb0fe5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/VspQuestionnaire.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/VspQuestionnaire.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @@ -32,5 +30,4 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.G public class VspQuestionnaire { private General general; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/Availability.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/Availability.java index 1c457c546c..5130342bba 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/Availability.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/Availability.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; import lombok.Getter; @@ -30,5 +29,4 @@ import lombok.Setter; public class Availability { private boolean useAvailabilityZonesForHighAvailability; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/General.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/General.java index 1aaba93f8e..eb38ce14d4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/General.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/General.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; import lombok.Getter; @@ -33,5 +32,4 @@ public class General { private Availability availability; private RegionsData regionsData; private StorageDataReplication storageDataReplication; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/RegionsData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/RegionsData.java index 093abcd652..bacbff4799 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/RegionsData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/RegionsData.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; import java.util.ArrayList; @@ -33,5 +32,4 @@ public class RegionsData { private boolean multiRegion; private List regions = new ArrayList<>(); - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java index 766b3bb1f9..bea4cf3ab8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; import lombok.Getter; @@ -34,5 +33,4 @@ public class StorageDataReplication { private Number storageReplicationFrequency; private String storageReplicationSource; private String storageReplicationDestination; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentCompositionSchemaInput.java index d20d3efb93..fab11e7d8b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentCompositionSchemaInput.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import lombok.Getter; @@ -32,5 +31,4 @@ public class ComponentCompositionSchemaInput implements SchemaTemplateInput { private boolean manual; private ComponentData component; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentQuestionnaireSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentQuestionnaireSchemaInput.java index b0c2b89536..c2e6478389 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentQuestionnaireSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComponentQuestionnaireSchemaInput.java @@ -14,7 +14,6 @@ * limitations under the License. * Modifications copyright (c) 2019 Nokia */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import java.util.List; @@ -30,5 +29,4 @@ public class ComponentQuestionnaireSchemaInput implements SchemaTemplateInput { private Map componentQuestionnaireData; private String componentDisplayName; private boolean manual; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComputeCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComputeCompositionSchemaInput.java index 5d87dd82c1..2410838b5e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComputeCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ComputeCompositionSchemaInput.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import lombok.Getter; @@ -32,5 +31,4 @@ public class ComputeCompositionSchemaInput implements SchemaTemplateInput { private boolean manual; private ComputeData compute; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/DeploymentFlavorCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/DeploymentFlavorCompositionSchemaInput.java index ce8d51cac2..81f3922a5e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/DeploymentFlavorCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/DeploymentFlavorCompositionSchemaInput.java @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; - import java.util.Collection; import lombok.Getter; import lombok.NoArgsConstructor; @@ -35,5 +33,4 @@ public class DeploymentFlavorCompositionSchemaInput implements SchemaTemplateInp private boolean manual; private DeploymentFlavor deploymentFlavor; private Collection featureGroupIds; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ImageCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ImageCompositionSchemaInput.java index a9ab142cc1..f603a981ec 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ImageCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/ImageCompositionSchemaInput.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import lombok.Getter; @@ -32,5 +31,4 @@ public class ImageCompositionSchemaInput implements SchemaTemplateInput { private boolean manual; private Image image; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NetworkCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NetworkCompositionSchemaInput.java index d652e0af44..c6970a3a01 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NetworkCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NetworkCompositionSchemaInput.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import lombok.Getter; @@ -32,5 +31,4 @@ public class NetworkCompositionSchemaInput implements SchemaTemplateInput { private boolean manual; private Network network; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NicCompositionSchemaInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NicCompositionSchemaInput.java index 3cf729bec7..e5b9392f51 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NicCompositionSchemaInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/NicCompositionSchemaInput.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; import java.util.Collection; @@ -34,5 +33,4 @@ public class NicCompositionSchemaInput implements SchemaTemplateInput { private boolean manual; private Nic nic; private Collection networkIds; - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateContext.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateContext.java index 3ee3e4a5e6..511cfb2f27 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateContext.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateContext.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; -public enum SchemaTemplateContext { - composition, - questionnaire -} +public enum SchemaTemplateContext {composition, questionnaire} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateInput.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateInput.java index 93e614f98b..fd13f2daeb 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateInput.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/schemagenerator/SchemaTemplateInput.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator; public interface SchemaTemplateInput { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java index 58faa41872..caf4f0486d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/OrchestrationTemplateFileExtensionErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,25 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_EXTENSION; + import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.INVALID_EXTENSION; - public class OrchestrationTemplateFileExtensionErrorBuilder { - private static final String INVALID_EXTENSION_MSG = "Invalid file extension. Valid extensions " + - "are : zip, csar."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public OrchestrationTemplateFileExtensionErrorBuilder(){ - builder.withId(INVALID_EXTENSION); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_EXTENSION_MSG)); - } + private static final String INVALID_EXTENSION_MSG = "Invalid file extension. Valid extensions " + "are : zip, csar."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public OrchestrationTemplateFileExtensionErrorBuilder() { + builder.withId(INVALID_EXTENSION); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_EXTENSION_MSG)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductCreationFailedBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductCreationFailedBuilder.java index a7abbe0dd9..1dc1c40ca9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductCreationFailedBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductCreationFailedBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,21 +24,20 @@ import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes; public class VendorSoftwareProductCreationFailedBuilder { - private static final String VSP_CREATION_FAILED = "Failed to create VSP; %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Vendor software product creation failed error builder. - * - */ - public VendorSoftwareProductCreationFailedBuilder(String reason) { - builder.withId(VendorSoftwareProductErrorCodes.FAILED_TO_CREATE_VSP); - builder.withCategory(ErrorCategory.APPLICATION); - builder - .withMessage(String.format(VSP_CREATION_FAILED, reason)); - } + private static final String VSP_CREATION_FAILED = "Failed to create VSP; %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Vendor software product creation failed error builder. + */ + public VendorSoftwareProductCreationFailedBuilder(String reason) { + builder.withId(VendorSoftwareProductErrorCodes.FAILED_TO_CREATE_VSP); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VSP_CREATION_FAILED, reason)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductNotFoundErrorBuilder.java index ef5b43fad4..8cb2d72d25 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/errors/VendorSoftwareProductNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,31 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.errors; +import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.VSP_NOT_FOUND; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; -import static org.openecomp.sdc.vendorsoftwareproduct.errors.VendorSoftwareProductErrorCodes.VSP_NOT_FOUND; - public class VendorSoftwareProductNotFoundErrorBuilder { - private static final String VSP_FOUND_MSG = "Vendor software product with Id %s not found."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Vendor software product not found error builder. - * - * @param vendorSoftwareProductId the vendor software product id - */ - public VendorSoftwareProductNotFoundErrorBuilder(String vendorSoftwareProductId) { - builder.withId(VSP_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(VSP_FOUND_MSG, vendorSoftwareProductId)); - } + private static final String VSP_FOUND_MSG = "Vendor software product with Id %s not found."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Vendor software product not found error builder. + * + * @param vendorSoftwareProductId the vendor software product id + */ + public VendorSoftwareProductNotFoundErrorBuilder(String vendorSoftwareProductId) { + builder.withId(VSP_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(VSP_FOUND_MSG, vendorSoftwareProductId)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDaoFactoryImpl.java index 1ef0caac0c..bcf4cf1dcd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComponentDaoZusammenImpl; public class ComponentDaoFactoryImpl extends ComponentDaoFactory { - private static final ComponentDao INSTANCE = new ComponentDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ComponentDao createInterface() { - return INSTANCE; - } + private static final ComponentDao INSTANCE = new ComponentDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ComponentDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoFactoryImpl.java index f4f36c3355..180f11917a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; - import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; @@ -28,11 +26,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComponentDepend public class ComponentDependencyModelDaoFactoryImpl extends ComponentDependencyModelDaoFactory { - private static final ComponentDependencyModelDao INSTANCE = new - ComponentDependencyModelDaoZusammenImpl( ZusammenAdaptorFactory.getInstance().createInterface()); + private static final ComponentDependencyModelDao INSTANCE = new ComponentDependencyModelDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ComponentDependencyModelDao createInterface() { - return INSTANCE; - } + @Override + public ComponentDependencyModelDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComputeDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComputeDaoFactoryImpl.java index 3032d523c4..1a9127c95a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComputeDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComputeDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComputeDaoZusammenImpl; public class ComputeDaoFactoryImpl extends ComputeDaoFactory { - private static final ComputeDao INSTANCE = new ComputeDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ComputeDao createInterface() { - return INSTANCE; - } + private static final ComputeDao INSTANCE = new ComputeDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ComputeDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/DeploymentFlavorDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/DeploymentFlavorDaoFactoryImpl.java index 93ce6b122c..b4ad183539 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/DeploymentFlavorDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/DeploymentFlavorDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -25,10 +24,9 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.DeploymentFlavorDaoZusammenImpl; +public class DeploymentFlavorDaoFactoryImpl extends DeploymentFlavorDaoFactory { -public class DeploymentFlavorDaoFactoryImpl extends DeploymentFlavorDaoFactory{ - private static final DeploymentFlavorDao INSTANCE = new DeploymentFlavorDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); + private static final DeploymentFlavorDao INSTANCE = new DeploymentFlavorDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); @Override public DeploymentFlavorDao createInterface() { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ImageDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ImageDaoFactoryImpl.java index 21abcae517..2d01ecf96a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ImageDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ImageDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -27,11 +26,10 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ImageDaoZusamme public class ImageDaoFactoryImpl extends ImageDaoFactory { - private static final ImageDao INSTANCE = new ImageDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); + private static final ImageDao INSTANCE = new ImageDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ImageDao createInterface() { - return INSTANCE; - } + @Override + public ImageDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/MonitoringUploadDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/MonitoringUploadDaoFactoryImpl.java index fa6a0cbfc2..bcee3a2789 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/MonitoringUploadDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/MonitoringUploadDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.MonitoringUploadDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComponentArtifactDaoZusammenImpl; public class MonitoringUploadDaoFactoryImpl extends MonitoringUploadDaoFactory { - private static final ComponentArtifactDao INSTANCE = new ComponentArtifactDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ComponentArtifactDao createInterface() { - return INSTANCE; - } + private static final ComponentArtifactDao INSTANCE = new ComponentArtifactDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ComponentArtifactDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NetworkDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NetworkDaoFactoryImpl.java index 5bccc5ced2..cc555b4a6c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NetworkDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NetworkDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.NetworkDaoZusammenImpl; public class NetworkDaoFactoryImpl extends NetworkDaoFactory { - private static final NetworkDao INSTANCE = new NetworkDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public NetworkDao createInterface() { - return INSTANCE; - } + private static final NetworkDao INSTANCE = new NetworkDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public NetworkDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NicDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NicDaoFactoryImpl.java index 76e5d443f2..956d84e2d4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NicDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/NicDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.NicDaoZusammenImpl; public class NicDaoFactoryImpl extends NicDaoFactory { - private static final NicDao INSTANCE = new NicDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public NicDao createInterface() { - return INSTANCE; - } + private static final NicDao INSTANCE = new NicDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public NicDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateCandidateDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateCandidateDaoFactoryImpl.java index 8cc2c6f61f..d0e838ff19 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateCandidateDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateCandidateDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -25,14 +24,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidat import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.OrchestrationTemplateCandidateDaoZusammenImpl; -public class OrchestrationTemplateCandidateDaoFactoryImpl - extends OrchestrationTemplateCandidateDaoFactory { - private static final OrchestrationTemplateCandidateDao INSTANCE = - new OrchestrationTemplateCandidateDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); +public class OrchestrationTemplateCandidateDaoFactoryImpl extends OrchestrationTemplateCandidateDaoFactory { + + private static final OrchestrationTemplateCandidateDao INSTANCE = new OrchestrationTemplateCandidateDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public OrchestrationTemplateCandidateDao createInterface() { - return INSTANCE; - } + @Override + public OrchestrationTemplateCandidateDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateDaoFactoryImpl.java index 8b90462131..57f37beb24 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/OrchestrationTemplateDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -25,15 +24,13 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.OrchestrationTemplateDaoZusammenImpl; +public class OrchestrationTemplateDaoFactoryImpl extends OrchestrationTemplateDaoFactory { -public class OrchestrationTemplateDaoFactoryImpl - extends OrchestrationTemplateDaoFactory { - private static final OrchestrationTemplateDao INSTANCE = - new OrchestrationTemplateDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); + private static final OrchestrationTemplateDao INSTANCE = new OrchestrationTemplateDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public OrchestrationTemplateDao createInterface() { - return INSTANCE; - } + @Override + public OrchestrationTemplateDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoFactoryImpl.java index 8b9bedcd3a..2982e07d2f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory; public class PackageInfoDaoFactoryImpl extends PackageInfoDaoFactory { - private static final PackageInfoDao INSTANCE = new PackageInfoDaoImpl(); - @Override - public PackageInfoDao createInterface() { - return INSTANCE; - } + private static final PackageInfoDao INSTANCE = new PackageInfoDaoImpl(); + + @Override + public PackageInfoDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java index ff4fd45420..591af3c8b9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,72 +17,67 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - public class PackageInfoDaoImpl extends CassandraBaseDao implements PackageInfoDao { - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper mapper = - noSqlDb.getMappingManager().mapper(PackageInfo.class); - private static final PackageInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(PackageInfoAccessor.class); - @Override - protected Mapper getMapper() { - return mapper; - } + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper mapper = noSqlDb.getMappingManager().mapper(PackageInfo.class); + private static final PackageInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(PackageInfoAccessor.class); - @Override - protected Object[] getKeys(PackageInfo entity) { - return new Object[]{entity.getVspId(), entity.getVersion()}; - } + @Override + protected Mapper getMapper() { + return mapper; + } - @Override - public Collection list(PackageInfo entity) { - return accessor.listInfo().all(); - } + @Override + protected Object[] getKeys(PackageInfo entity) { + return new Object[]{entity.getVspId(), entity.getVersion()}; + } - @Override - public List listByCategory(String category, String subCategory) { - Result packages = accessor.listInfo(); + @Override + public Collection list(PackageInfo entity) { + return accessor.listInfo().all(); + } - List filteredPackages = new ArrayList<>(); - for (PackageInfo packageInfo : packages) { - if (category != null) { - if (category.equals(packageInfo.getCategory())) { - filteredPackages.add(packageInfo); - } - } else if (subCategory != null) { - if (subCategory.equals(packageInfo.getSubCategory())) { - filteredPackages.add(packageInfo); + @Override + public List listByCategory(String category, String subCategory) { + Result packages = accessor.listInfo(); + List filteredPackages = new ArrayList<>(); + for (PackageInfo packageInfo : packages) { + if (category != null) { + if (category.equals(packageInfo.getCategory())) { + filteredPackages.add(packageInfo); + } + } else if (subCategory != null) { + if (subCategory.equals(packageInfo.getSubCategory())) { + filteredPackages.add(packageInfo); + } + } else { + filteredPackages.add(packageInfo); + } } - } else { - filteredPackages.add(packageInfo); - } + return filteredPackages; } - return filteredPackages; - } - @Accessor - interface PackageInfoAccessor { + @Accessor + interface PackageInfoAccessor { - @Query( - "SELECT vsp_id,version,display_name,vsp_name,vsp_description,vendor_name,category" + @Query("SELECT vsp_id,version,display_name,vsp_name,vsp_description,vendor_name,category" + " ,sub_category, vendor_release,package_checksum,package_type, resource_type FROM package_details") - Result listInfo(); - } + Result listInfo(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java index 0205446ae8..72b9c76615 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ProcessDaoZusammenImpl; public class ProcessDaoFactoryImpl extends ProcessDaoFactory { - private static final ProcessDao INSTANCE = new ProcessDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ProcessDao createInterface() { - return INSTANCE; - } + private static final ProcessDao INSTANCE = new ProcessDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ProcessDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoFactoryImpl.java index a5f9d17431..978d11cd3b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,12 +25,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoF import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.VendorSoftwareProductInfoDaoZusammenImpl; public class VendorSoftwareProductInfoDaoFactoryImpl extends VendorSoftwareProductInfoDaoFactory { - private static final VendorSoftwareProductInfoDao INSTANCE = - new VendorSoftwareProductInfoDaoZusammenImpl( - ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public VendorSoftwareProductInfoDao createInterface() { - return INSTANCE; - } + private static final VendorSoftwareProductInfoDao INSTANCE = new VendorSoftwareProductInfoDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public VendorSoftwareProductInfoDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java index f6f3c84303..0c7c552489 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,21 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; - import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory; public class VspMergeDaoFactoryImpl extends VspMergeDaoFactory { - private static final VspMergeDao INSTANCE = new - VspMergeDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + private static final VspMergeDao INSTANCE = new VspMergeDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public VspMergeDao createInterface() { - return INSTANCE; - } + @Override + public VspMergeDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java index 86045ab20a..e7579c6ce6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -32,6 +34,8 @@ import com.datastax.driver.extras.codecs.enums.EnumNameCodec; import com.datastax.driver.mapping.MappingManager; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.List; +import java.util.stream.Collectors; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.common.session.SessionContextProviderFactory; @@ -39,155 +43,120 @@ import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; -import java.util.stream.Collectors; +public class VspMergeDaoImpl implements VspMergeDao { -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; -import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + private static final String VSP_MODEL_NOT_EXIST = "Vsp model does not exist for Vsp %s, version %s."; + private static final VspMergeHintAccessor accessor; -public class VspMergeDaoImpl implements VspMergeDao { - private static final String VSP_MODEL_NOT_EXIST = - "Vsp model does not exist for Vsp %s, version %s."; - - private static final VspMergeHintAccessor accessor; - - static { - MappingManager mappingManager = NoSqlDbFactory.getInstance().createInterface().getMappingManager(); - mappingManager.getSession().getCluster().getConfiguration().getCodecRegistry() - .register(new EnumNameCodec<>(Resolution.class)); - accessor = mappingManager.createAccessor(VspMergeHintAccessor.class); - } - - private ZusammenAdaptor zusammenAdaptor; - - public VspMergeDaoImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public boolean isConflicted(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); - - return listVspModels(context, elementContext).size() > 1; - } - - @Override - public void updateHint(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); - - String vspModelId = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()) - .orElseThrow(() -> new IllegalStateException( - String.format(VSP_MODEL_NOT_EXIST, vspId, version.getId()))) - .getId().getValue(); - - updateVspModelId(vspId, version, vspModelId); - } - - @Override - public void deleteHint(String vspId, Version version) { - accessor.delete(getUser(),vspId,version.getId()); - } - - @Override - public void updateConflictResolution(String vspId, Version version, - Resolution resolution) { - accessor.updateModelResolution(resolution, getUser(), vspId, version.getId()); - } - - @Override - public void applyConflictResolution(String vspId, Version version) { - //called only when no conflicts - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); - - List vspModels = listVspModels(context, elementContext); - if (vspModels.size() == 1) { - updateVspModelId(vspId, version, vspModels.iterator().next().getId().getValue()); - return; + static { + MappingManager mappingManager = NoSqlDbFactory.getInstance().createInterface().getMappingManager(); + mappingManager.getSession().getCluster().getConfiguration().getCodecRegistry().register(new EnumNameCodec<>(Resolution.class)); + accessor = mappingManager.createAccessor(VspMergeHintAccessor.class); + } + + private ZusammenAdaptor zusammenAdaptor; + + public VspMergeDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public boolean isConflicted(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + return listVspModels(context, elementContext).size() > 1; } - if (vspModels.size() != 2) { - return; + @Override + public void updateHint(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + String vspModelId = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()) + .orElseThrow(() -> new IllegalStateException(String.format(VSP_MODEL_NOT_EXIST, vspId, version.getId()))).getId().getValue(); + updateVspModelId(vspId, version, vspModelId); } - String user = getUser(); - Row row = accessor.get(user, vspId, version.getId()).one(); - if (row == null) { - throw new IllegalStateException( - "Vsp model id must exists if its conflict is being resolved"); + @Override + public void deleteHint(String vspId, Version version) { + accessor.delete(getUser(), vspId, version.getId()); } - String resolutionValue = row.getString("model_resolution"); - if (resolutionValue == null) { - return; // model conflict is not resolved yet + + @Override + public void updateConflictResolution(String vspId, Version version, Resolution resolution) { + accessor.updateModelResolution(resolution, getUser(), vspId, version.getId()); + } + + @Override + public void applyConflictResolution(String vspId, Version version) { + //called only when no conflicts + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + List vspModels = listVspModels(context, elementContext); + if (vspModels.size() == 1) { + updateVspModelId(vspId, version, vspModels.iterator().next().getId().getValue()); + return; + } + if (vspModels.size() != 2) { + return; + } + String user = getUser(); + Row row = accessor.get(user, vspId, version.getId()).one(); + if (row == null) { + throw new IllegalStateException("Vsp model id must exists if its conflict is being resolved"); + } + String resolutionValue = row.getString("model_resolution"); + if (resolutionValue == null) { + return; // model conflict is not resolved yet + } + Resolution resolution = Resolution.valueOf(resolutionValue); + String localModelId = row.getString("model_id"); + String chosenModelId = keepOnlyChosenVspModel(context, elementContext, vspModels, resolution, localModelId); + accessor.update(chosenModelId, null, user, vspId, version.getId()); + } + + private String keepOnlyChosenVspModel(SessionContext context, ElementContext elementContext, List vspModels, Resolution resolution, + String localModelId) { + String newLocalModelId = null; + for (ElementInfo vspModel : vspModels) { + if (isRedundantModel(vspModel.getId().getValue(), localModelId, resolution)) { + zusammenAdaptor.saveElement(context, elementContext, buildElement(vspModel.getId(), Action.DELETE), "Delete Redundant Vsp Model"); + } else { + newLocalModelId = vspModel.getId().getValue(); + } + } + return newLocalModelId; + } + + private boolean isRedundantModel(String modelId, String localModelId, Resolution resolution) { + return resolution == Resolution.THEIRS && modelId.equals(localModelId) || resolution == Resolution.YOURS && !modelId.equals(localModelId); + } + + private List listVspModels(SessionContext context, ElementContext elementContext) { + return zusammenAdaptor.listElements(context, elementContext, null).stream() + .filter(elementInfo -> ElementType.VspModel.name().equals(elementInfo.getInfo().getName())).collect(Collectors.toList()); } - Resolution resolution = Resolution.valueOf(resolutionValue); - String localModelId = row.getString("model_id"); - - String chosenModelId = - keepOnlyChosenVspModel(context, elementContext, vspModels, resolution, localModelId); - - accessor.update(chosenModelId, null, user, vspId, version.getId()); - } - - private String keepOnlyChosenVspModel(SessionContext context, ElementContext elementContext, - List vspModels, Resolution resolution, - String localModelId) { - String newLocalModelId = null; - for (ElementInfo vspModel : vspModels) { - if (isRedundantModel(vspModel.getId().getValue(), localModelId, resolution)) { - zusammenAdaptor - .saveElement(context, elementContext, buildElement(vspModel.getId(), Action.DELETE), - "Delete Redundant Vsp Model"); - } else { - newLocalModelId = vspModel.getId().getValue(); - } + private void updateVspModelId(String vspId, Version version, String vspModelId) { + accessor.update(vspModelId, null, getUser(), vspId, version.getId()); + } + + private String getUser() { + return SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId(); + } + + @Accessor + interface VspMergeHintAccessor { + + @Query("SELECT model_id, model_resolution FROM vsp_merge_hint " + "WHERE space=? AND item_id=? AND version_id=?") + ResultSet get(String space, String itemId, String versionId); + + @Query("UPDATE vsp_merge_hint SET model_id=?, model_resolution=? " + "WHERE space=? AND item_id=? AND version_id=?") + void update(String vspModelId, Resolution modelResolution, String space, String itemId, String versionId); + + @Query("UPDATE vsp_merge_hint SET model_resolution=? WHERE space=? AND item_id=? AND version_id=?") + void updateModelResolution(Resolution modelResolution, String space, String itemId, String versionId); + + @Query("DELETE from vsp_merge_hint WHERE space=? AND item_id=? AND version_id=?") + void delete(String space, String itemId, String versionId); } - return newLocalModelId; - } - - private boolean isRedundantModel(String modelId, String localModelId, Resolution resolution) { - return resolution == Resolution.THEIRS && modelId.equals(localModelId) || - resolution == Resolution.YOURS && !modelId.equals(localModelId); - } - - private List listVspModels(SessionContext context, ElementContext elementContext) { - return zusammenAdaptor.listElements(context, elementContext, null).stream() - .filter(elementInfo -> ElementType.VspModel.name().equals(elementInfo.getInfo().getName())) - .collect(Collectors.toList()); - } - - private void updateVspModelId(String vspId, Version version, String vspModelId) { - accessor.update(vspModelId, null, getUser(), vspId, version.getId()); - } - - private String getUser() { - return SessionContextProviderFactory.getInstance().createInterface() - .get().getUser().getUserId(); - } - - @Accessor - interface VspMergeHintAccessor { - - @Query("SELECT model_id, model_resolution FROM vsp_merge_hint " + - "WHERE space=? AND item_id=? AND version_id=?") - ResultSet get(String space, String itemId, String versionId); - - @Query("UPDATE vsp_merge_hint SET model_id=?, model_resolution=? " + - "WHERE space=? AND item_id=? AND version_id=?") - void update(String vspModelId, Resolution modelResolution, String space, - String itemId, String versionId); - - @Query( - "UPDATE vsp_merge_hint SET model_resolution=? WHERE space=? AND item_id=? AND version_id=?") - void updateModelResolution(Resolution modelResolution, String space, String itemId, - String versionId); - - @Query("DELETE from vsp_merge_hint WHERE space=? AND item_id=? AND version_id=?") - void delete(String space, String itemId, String versionId); - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java index e80e7d5d66..dbfee03219 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,15 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; +import java.io.ByteArrayInputStream; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; @@ -34,202 +43,145 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentMonitoringUploadConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; -import java.io.ByteArrayInputStream; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - /** * @author Avrahamg. * @since March 21, 2017 */ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { - private static final String ARTIFACT_NAME = "artifactName"; + private static final String ARTIFACT_NAME = "artifactName"; + private ZusammenAdaptor zusammenAdaptor; - private ZusammenAdaptor zusammenAdaptor; - - public ComponentArtifactDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } + public ComponentArtifactDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning is not implemented for ComponentArtifactDaoZusammenImpl - } + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning is not implemented for ComponentArtifactDaoZusammenImpl + } - @Override - public Optional getByType( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(componentMonitoringUploadEntity.getVspId(), + @Override + public Optional getByType(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(componentMonitoringUploadEntity.getVspId(), componentMonitoringUploadEntity.getVersion().getId()); - - Optional mibsElement = - zusammenAdaptor.getElementByName(context, elementContext, - new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs.toString()); - if (mibsElement.isPresent()) { - Optional monitoringElement = zusammenAdaptor - .getElementByName(context, elementContext, mibsElement.get().getElementId(), - getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()).toString()); - if (monitoringElement.isPresent()) { - ComponentMonitoringUploadEntity entity = - new ElementToComponentMonitoringUploadConvertor().convert(monitoringElement.get()); - entity.setVspId(componentMonitoringUploadEntity.getVspId()); - entity.setVersion(componentMonitoringUploadEntity.getVersion()); - entity.setComponentId(componentMonitoringUploadEntity.getComponentId()); - return Optional.of(entity); - } + Optional mibsElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs.toString()); + if (mibsElement.isPresent()) { + Optional monitoringElement = zusammenAdaptor.getElementByName(context, elementContext, mibsElement.get().getElementId(), + getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()).toString()); + if (monitoringElement.isPresent()) { + ComponentMonitoringUploadEntity entity = new ElementToComponentMonitoringUploadConvertor().convert(monitoringElement.get()); + entity.setVspId(componentMonitoringUploadEntity.getVspId()); + entity.setVersion(componentMonitoringUploadEntity.getVersion()); + entity.setComponentId(componentMonitoringUploadEntity.getComponentId()); + return Optional.of(entity); + } + } + return Optional.empty(); } - return Optional.empty(); - } - - @Override - public void create(ComponentMonitoringUploadEntity entity) { - ZusammenElement mibElement = buildMibElement(entity); - - ZusammenElement mibsElement = buildStructuralElement(ElementType.Mibs, null); - - ZusammenElement componentElement = buildElement(new Id(entity.getComponentId()), Action.IGNORE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(entity.getVspId(), entity.getVersion().getId()); - - Element savedElement = zusammenAdaptor.saveElement(context, elementContext, - VspZusammenUtil.aggregateElements(componentElement, mibsElement, mibElement), - "Create monitoring upload"); - entity.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void delete(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + @Override + public void create(ComponentMonitoringUploadEntity entity) { + ZusammenElement mibElement = buildMibElement(entity); + ZusammenElement mibsElement = buildStructuralElement(ElementType.Mibs, null); + ZusammenElement componentElement = buildElement(new Id(entity.getComponentId()), Action.IGNORE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(entity.getVspId(), entity.getVersion().getId()); + Element savedElement = zusammenAdaptor + .saveElement(context, elementContext, VspZusammenUtil.aggregateElements(componentElement, mibsElement, mibElement), + "Create monitoring upload"); + entity.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - ZusammenElement mibElement = buildMibElementStructure(componentMonitoringUploadEntity); - mibElement.setElementId(new Id(componentMonitoringUploadEntity.getId())); - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(componentMonitoringUploadEntity.getVspId(), + @Override + public void delete(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + ZusammenElement mibElement = buildMibElementStructure(componentMonitoringUploadEntity); + mibElement.setElementId(new Id(componentMonitoringUploadEntity.getId())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(componentMonitoringUploadEntity.getVspId(), componentMonitoringUploadEntity.getVersion().getId()); + zusammenAdaptor + .saveElement(context, elementContext, mibElement, String.format("Delete mib with id %s", componentMonitoringUploadEntity.getId())); + } + + @Override + public Collection list(ComponentMonitoringUploadEntity mibEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(mibEntity.getVspId(), mibEntity.getVersion().getId()); + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(mibEntity.getComponentId()), ElementType.Mibs.toString()).stream() + .map(new ElementToComponentMonitoringUploadConvertor()::convert).map(mib -> { + mib.setVspId(mibEntity.getVspId()); + mib.setVersion(mibEntity.getVersion()); + mib.setComponentId(mibEntity.getComponentId()); + return mib; + }).collect(Collectors.toList()); + } - zusammenAdaptor.saveElement(context, elementContext, mibElement, - String.format("Delete mib with id %s", componentMonitoringUploadEntity.getId())); - } - - - - @Override - public Collection list( - ComponentMonitoringUploadEntity mibEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(mibEntity.getVspId(), mibEntity.getVersion().getId()); - return zusammenAdaptor - .listElementsByName(context, elementContext, new Id(mibEntity.getComponentId()), - ElementType.Mibs.toString()) - .stream() - .map(new ElementToComponentMonitoringUploadConvertor()::convert) - .map(mib -> { - mib.setVspId(mibEntity.getVspId()); - mib.setVersion(mibEntity.getVersion()); - mib.setComponentId(mibEntity.getComponentId()); - return mib; - }) - .collect(Collectors.toList()); - } - - @Override - public void deleteAll(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(componentMonitoringUploadEntity.getVspId(), + @Override + public void deleteAll(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(componentMonitoringUploadEntity.getVspId(), componentMonitoringUploadEntity.getVersion().getId()); + Optional optionalElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs.name()); + if (optionalElement.isPresent()) { + Element mibsElement = optionalElement.get(); + Collection mibs = mibsElement.getSubElements(); + mibs.forEach(mib -> { + ZusammenElement mibZusammenElement = buildElement(mib.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, mibZusammenElement, "Delete mib with id " + mib.getElementId()); + }); + } + } - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs - .name()); + @Override + public Collection listArtifacts(ComponentMonitoringUploadEntity monitoringUploadEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(monitoringUploadEntity.getVspId(), monitoringUploadEntity.getVersion().getId()); + final Optional elementByName = zusammenAdaptor + .getElementByName(context, elementContext, new Id(monitoringUploadEntity.getComponentId()), ElementType.Mibs.name()); + if (!elementByName.isPresent()) { + return Collections.emptyList(); + } else { + final Id elementId = elementByName.get().getElementId(); + return zusammenAdaptor.listElementData(context, elementContext, elementId).stream() + .map(element -> buildMibEntity(element, monitoringUploadEntity)).collect(Collectors.toList()); + } + } - if (optionalElement.isPresent()) { - Element mibsElement = optionalElement.get(); - Collection mibs = mibsElement.getSubElements(); + private ComponentMonitoringUploadEntity buildMibEntity(Element element, ComponentMonitoringUploadEntity monitoringUploadEntity) { + final String componentId = monitoringUploadEntity.getComponentId(); + ComponentMonitoringUploadEntity createdMib = new ComponentMonitoringUploadEntity(monitoringUploadEntity.getVspId(), + monitoringUploadEntity.getVersion(), componentId, null); + createdMib.setArtifactName((String) element.getInfo().getProperties().get(ARTIFACT_NAME)); + createdMib.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + createdMib.setType(MonitoringUploadType.valueOf(element.getInfo().getName())); + return createdMib; + } - mibs.forEach(mib -> { - ZusammenElement mibZusammenElement = buildElement(mib.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, mibZusammenElement, - "Delete mib with id " + mib.getElementId()); - }); + private ZusammenElement buildMibElement(ComponentMonitoringUploadEntity monitoringUploadEntity) { + ZusammenElement monitoringElement = buildMibElementStructure(monitoringUploadEntity); + monitoringElement.getInfo().getProperties().put(ARTIFACT_NAME, monitoringUploadEntity.getArtifactName()); + monitoringElement.setData(new ByteArrayInputStream(monitoringUploadEntity.getArtifact().array())); + return monitoringElement; } - } - - @Override - public Collection listArtifacts( - ComponentMonitoringUploadEntity monitoringUploadEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(monitoringUploadEntity.getVspId(), - monitoringUploadEntity.getVersion().getId()); - - final Optional elementByName = - zusammenAdaptor.getElementByName(context, elementContext, - new Id(monitoringUploadEntity.getComponentId()), ElementType.Mibs.name()); - - if (!elementByName.isPresent()) { - return Collections.emptyList(); - } else { - final Id elementId = elementByName.get().getElementId(); - return zusammenAdaptor.listElementData(context, elementContext, elementId).stream() - .map(element -> buildMibEntity(element, monitoringUploadEntity)) - .collect(Collectors.toList()); + + private ZusammenElement buildMibElementStructure(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + return buildStructuralElement(getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()), Action.UPDATE); } - } - - private ComponentMonitoringUploadEntity buildMibEntity(Element element, - ComponentMonitoringUploadEntity monitoringUploadEntity) { - final String componentId = monitoringUploadEntity.getComponentId(); - ComponentMonitoringUploadEntity - createdMib = new ComponentMonitoringUploadEntity(monitoringUploadEntity.getVspId(), - monitoringUploadEntity.getVersion(), - componentId, - null); - createdMib.setArtifactName((String) element.getInfo().getProperties().get(ARTIFACT_NAME)); - createdMib.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); - createdMib.setType(MonitoringUploadType.valueOf(element.getInfo().getName())); - return createdMib; - } - - private ZusammenElement buildMibElement( - ComponentMonitoringUploadEntity monitoringUploadEntity) { - - ZusammenElement monitoringElement = buildMibElementStructure(monitoringUploadEntity); - monitoringElement.getInfo().getProperties() - .put(ARTIFACT_NAME, monitoringUploadEntity.getArtifactName()); - monitoringElement - .setData(new ByteArrayInputStream(monitoringUploadEntity.getArtifact().array())); - return monitoringElement; - } - - private ZusammenElement buildMibElementStructure( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - return buildStructuralElement(getMonitoringStructuralElement(componentMonitoringUploadEntity - .getType()), Action.UPDATE); - } - - private ElementType getMonitoringStructuralElement(MonitoringUploadType type){ - switch (type) { - case SNMP_POLL: - return ElementType.SNMP_POLL; - case SNMP_TRAP: - return ElementType.SNMP_TRAP; - case VES_EVENTS: - return ElementType.VES_EVENTS; - default: - throw new IllegalArgumentException(); + + private ElementType getMonitoringStructuralElement(MonitoringUploadType type) { + switch (type) { + case SNMP_POLL: + return ElementType.SNMP_POLL; + case SNMP_TRAP: + return ElementType.SNMP_TRAP; + case VES_EVENTS: + return ElementType.VES_EVENTS; + default: + throw new IllegalArgumentException(); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java index d38db0b0da..8c2fb92f17 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +31,12 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -37,233 +46,170 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class ComponentDaoZusammenImpl implements ComponentDao { - private ZusammenAdaptor zusammenAdaptor; - - public ComponentDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning is not implemented for ComponentDaoZusammenImpl - } - - @Override - public Collection list(ComponentEntity component) { - SessionContext context = createSessionContext(); - - return listComponents(zusammenAdaptor, context, component.getVspId(), component.getVersion()); - } - - static Collection listComponents(ZusammenAdaptor zusammenAdaptor, - SessionContext context, - String vspId, Version version) { - ElementContext elementContext = new ElementContext(vspId, version.getId()); + private ZusammenAdaptor zusammenAdaptor; - Optional vspModel = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return new ArrayList<>(); + public ComponentDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - ElementToComponentConvertor convertor = new ElementToComponentConvertor(); - return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), - ElementType.Components.name()).stream() - .map(elementInfo -> { - ComponentEntity entity = convertor.convert(elementInfo); - entity.setVspId(vspId); - entity.setVersion(version); - return entity; - }) - .collect(Collectors.toList()); - } - - - @Override - public void create(ComponentEntity component) { - ZusammenElement componentElement = componentToZusammen(component, Action.CREATE); - - ZusammenElement componentsElement = - buildStructuralElement(ElementType.Components, Action.IGNORE); - componentsElement.getSubElements().add(componentElement); - - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(componentsElement); - - SessionContext context = createSessionContext(); - Element savedVspModel = zusammenAdaptor.saveElement(context, - new ElementContext(component.getVspId(), component.getVersion().getId()), - vspModel, "Create component"); - component.setId(savedVspModel.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(ComponentEntity component) { - ZusammenElement componentElement = componentToZusammen(component, Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(component.getVspId(), component.getVersion().getId()), - componentElement, String.format("Update component with id %s", component.getId())); - } - - @Override - public ComponentEntity get(ComponentEntity component) { - SessionContext context = createSessionContext(); - - Optional element = - zusammenAdaptor.getElement(context, - new ElementContext(component.getVspId(), component.getVersion().getId()), - component.getId()); - - if (element.isPresent()) { - ComponentEntity entity = new ElementToComponentConvertor().convert(element.get()); - entity.setVspId(component.getVspId()); - entity.setVersion(component.getVersion()); - return entity; + static Collection listComponents(ZusammenAdaptor zusammenAdaptor, SessionContext context, String vspId, Version version) { + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } + ElementToComponentConvertor convertor = new ElementToComponentConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), ElementType.Components.name()).stream() + .map(elementInfo -> { + ComponentEntity entity = convertor.convert(elementInfo); + entity.setVspId(vspId); + entity.setVersion(version); + return entity; + }).collect(Collectors.toList()); } - return null; - } - - @Override - public void delete(ComponentEntity component) { - ZusammenElement componentElement = buildElement(new Id(component.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(component.getVspId(), component.getVersion().getId()), - componentElement, String.format("Delete component with id %s", component.getId())); - } - - @Override - public ComponentEntity getQuestionnaireData(String vspId, Version version, String componentId) { - SessionContext context = createSessionContext(); - - return getQuestionnaire(context, new ElementContext(vspId, version.getId()), - new ComponentEntity(vspId, version, componentId)); - } - - private ComponentEntity getQuestionnaire(SessionContext context, ElementContext elementContext, - ComponentEntity component) { - Optional questionnaireElement = zusammenAdaptor - .getElementByName(context, elementContext, new Id(component.getId()), - ElementType.ComponentQuestionnaire.name()); - return questionnaireElement.map(new ElementToComponentQuestionnnaireConvertor()::convert) - .map(entity -> { - entity.setVspId(component.getVspId()); - entity.setVersion(component.getVersion()); - return entity; - }) - .orElse(null); - } - - @Override - public void updateQuestionnaireData(String vspId, Version version, String componentId, - String questionnaireData) { - ZusammenElement questionnaireElement = - componentQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - - ZusammenElement componentElement = buildElement(new Id(componentId), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList(questionnaireElement)); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), - componentElement, "Update component questionnaire"); - } - - @Override - public Collection listQuestionnaires(String vspId, Version version) { - return listCompositionAndQuestionnaire(vspId, version); - } - @Override - public Collection listCompositionAndQuestionnaire(String vspId, - Version version) { - SessionContext context = createSessionContext(); + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning is not implemented for ComponentDaoZusammenImpl + } - Collection components = - listComponents(zusammenAdaptor, context, vspId, version); + @Override + public Collection list(ComponentEntity component) { + SessionContext context = createSessionContext(); + return listComponents(zusammenAdaptor, context, component.getVspId(), component.getVersion()); + } - ElementContext elementContext = new ElementContext(vspId, version.getId()); - components.forEach(component -> component.setQuestionnaireData( - getQuestionnaire(context, elementContext, component).getQuestionnaireData())); - return components; - } + @Override + public void create(ComponentEntity component) { + ZusammenElement componentElement = componentToZusammen(component, Action.CREATE); + ZusammenElement componentsElement = buildStructuralElement(ElementType.Components, Action.IGNORE); + componentsElement.getSubElements().add(componentElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(componentsElement); + SessionContext context = createSessionContext(); + Element savedVspModel = zusammenAdaptor + .saveElement(context, new ElementContext(component.getVspId(), component.getVersion().getId()), vspModel, "Create component"); + component.setId(savedVspModel.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - @Override - public void deleteAll(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + @Override + public void update(ComponentEntity component) { + ZusammenElement componentElement = componentToZusammen(component, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(component.getVspId(), component.getVersion().getId()), componentElement, + String.format("Update component with id %s", component.getId())); + } - Collection vspModelSubs = zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + @Override + public ComponentEntity get(ComponentEntity component) { + SessionContext context = createSessionContext(); + Optional element = zusammenAdaptor + .getElement(context, new ElementContext(component.getVspId(), component.getVersion().getId()), component.getId()); + if (element.isPresent()) { + ComponentEntity entity = new ElementToComponentConvertor().convert(element.get()); + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; + } + return null; + } - Optional componentsElement = vspModelSubs.stream() - .filter(elementInfo -> elementInfo.getInfo() != null - && ElementType.Components.name().equals(elementInfo.getInfo().getName())) - .findFirst(); - if (!componentsElement.isPresent()) { - return; + @Override + public void delete(ComponentEntity component) { + ZusammenElement componentElement = buildElement(new Id(component.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(component.getVspId(), component.getVersion().getId()), componentElement, + String.format("Delete component with id %s", component.getId())); } - ZusammenElement components = buildElement(componentsElement.get().getId(), Action.IGNORE); - components.setSubElements(componentsElement.get().getSubElements().stream() - .map(component -> buildElement(component.getId(), Action.DELETE)) - .collect(Collectors.toList())); + @Override + public ComponentEntity getQuestionnaireData(String vspId, Version version, String componentId) { + SessionContext context = createSessionContext(); + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new ComponentEntity(vspId, version, componentId)); + } - zusammenAdaptor.saveElement(context, elementContext, components, "Delete all components"); - } + private ComponentEntity getQuestionnaire(SessionContext context, ElementContext elementContext, ComponentEntity component) { + Optional questionnaireElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(component.getId()), ElementType.ComponentQuestionnaire.name()); + return questionnaireElement.map(new ElementToComponentQuestionnnaireConvertor()::convert).map(entity -> { + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; + }).orElse(null); + } - private ZusammenElement componentToZusammen(ComponentEntity component, Action action) { - ZusammenElement componentElement = buildComponentElement(component, action); + @Override + public void updateQuestionnaireData(String vspId, Version version, String componentId, String questionnaireData) { + ZusammenElement questionnaireElement = componentQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + ZusammenElement componentElement = buildElement(new Id(componentId), Action.IGNORE); + componentElement.setSubElements(Collections.singletonList(questionnaireElement)); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), componentElement, "Update component questionnaire"); + } - if (action == Action.CREATE) { - ZusammenElement mibs = buildStructuralElement(ElementType.Mibs, Action.CREATE); - mibs.addSubElement(buildStructuralElement(ElementType.SNMP_TRAP, Action.CREATE)); - mibs.addSubElement(buildStructuralElement(ElementType.VES_EVENTS, Action.CREATE)); - mibs.addSubElement(buildStructuralElement(ElementType.SNMP_POLL, Action.CREATE)); + @Override + public Collection listQuestionnaires(String vspId, Version version) { + return listCompositionAndQuestionnaire(vspId, version); + } - componentElement.addSubElement(mibs); - componentElement.addSubElement( - componentQuestionnaireToZusammen(component.getQuestionnaireData(), Action.CREATE)); - componentElement.addSubElement(buildStructuralElement(ElementType.Nics, Action.CREATE)); - componentElement.addSubElement(buildStructuralElement(ElementType.Processes, Action.CREATE)); - componentElement.addSubElement(buildStructuralElement(ElementType.Computes, Action.CREATE)); - componentElement.addSubElement(buildStructuralElement(ElementType.Images, Action.CREATE)); + @Override + public Collection listCompositionAndQuestionnaire(String vspId, Version version) { + SessionContext context = createSessionContext(); + Collection components = listComponents(zusammenAdaptor, context, vspId, version); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + components.forEach(component -> component.setQuestionnaireData(getQuestionnaire(context, elementContext, component).getQuestionnaireData())); + return components; } - return componentElement; - } - private ZusammenElement componentQuestionnaireToZusammen(String questionnaireData, - Action action) { - ZusammenElement questionnaireElement = - buildStructuralElement(ElementType.ComponentQuestionnaire, action); - questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); - return questionnaireElement; - } + @Override + public void deleteAll(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Collection vspModelSubs = zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + Optional componentsElement = vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null && ElementType.Components.name().equals(elementInfo.getInfo().getName())) + .findFirst(); + if (!componentsElement.isPresent()) { + return; + } + ZusammenElement components = buildElement(componentsElement.get().getId(), Action.IGNORE); + components.setSubElements(componentsElement.get().getSubElements().stream().map(component -> buildElement(component.getId(), Action.DELETE)) + .collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, components, "Delete all components"); + } - private ZusammenElement buildComponentElement(ComponentEntity component, Action action) { - ZusammenElement componentElement = - buildElement(component.getId() == null ? null : new Id(component.getId()), action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Component); - info.addProperty(ElementPropertyName.compositionData.name(), component.getCompositionData()); - componentElement.setInfo(info); - componentElement.setData(new ByteArrayInputStream(component.getCompositionData().getBytes())); - return componentElement; - } + private ZusammenElement componentToZusammen(ComponentEntity component, Action action) { + ZusammenElement componentElement = buildComponentElement(component, action); + if (action == Action.CREATE) { + ZusammenElement mibs = buildStructuralElement(ElementType.Mibs, Action.CREATE); + mibs.addSubElement(buildStructuralElement(ElementType.SNMP_TRAP, Action.CREATE)); + mibs.addSubElement(buildStructuralElement(ElementType.VES_EVENTS, Action.CREATE)); + mibs.addSubElement(buildStructuralElement(ElementType.SNMP_POLL, Action.CREATE)); + componentElement.addSubElement(mibs); + componentElement.addSubElement(componentQuestionnaireToZusammen(component.getQuestionnaireData(), Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Nics, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Processes, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Computes, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Images, Action.CREATE)); + } + return componentElement; + } + private ZusammenElement componentQuestionnaireToZusammen(String questionnaireData, Action action) { + ZusammenElement questionnaireElement = buildStructuralElement(ElementType.ComponentQuestionnaire, action); + questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); + return questionnaireElement; + } + private ZusammenElement buildComponentElement(ComponentEntity component, Action action) { + ZusammenElement componentElement = buildElement(component.getId() == null ? null : new Id(component.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Component); + info.addProperty(ElementPropertyName.compositionData.name(), component.getCompositionData()); + componentElement.setInfo(info); + componentElement.setData(new ByteArrayInputStream(component.getCompositionData().getBytes())); + return componentElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java index bb80a95aab..5662da2769 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -34,7 +33,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentDependencyModelConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.types.ElementPropertyName; - import java.util.ArrayList; import java.util.Collection; import java.util.Optional; @@ -47,148 +45,103 @@ import static org.openecomp.core.zusammen.api.ZusammenUtil.*; */ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDependencyModelDao { - private ZusammenAdaptor zusammenAdaptor; - - public ComponentDependencyModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public ComponentDependencyModelEntity get(ComponentDependencyModelEntity dependency) { + private ZusammenAdaptor zusammenAdaptor; - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - Optional componentDependencyElement = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(dependency.getId())); - - if (componentDependencyElement.isPresent()) { - ElementToComponentDependencyModelConvertor convertor = new - ElementToComponentDependencyModelConvertor(); - - ComponentDependencyModelEntity entity = convertor.convert(componentDependencyElement.get()); - entity.setVspId(dependency.getVspId()); - entity.setVersion(dependency.getVersion()); - return entity; + public ComponentDependencyModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - return null; - } - - @Override - public void create(ComponentDependencyModelEntity dependency) { - ZusammenElement componentDependency = - buildComponentDependencyElement(dependency, Action.CREATE); - - ZusammenElement componentDependencies = - buildStructuralElement(ElementType.ComponentDependencies, Action.IGNORE); - componentDependencies.addSubElement(componentDependency); - - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(componentDependencies); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - Element compDepsSavedElement = zusammenAdaptor - .saveElement(context, elementContext, vspModel, "Create component dependency model"); - - dependency.setId(compDepsSavedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(ComponentDependencyModelEntity dependency) { - ZusammenElement componentDependencyElement = - buildComponentDependencyElement(dependency, Action.UPDATE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, - String.format("Update component dependency model with id %s", dependency.getId())); - } - - @Override - public void delete(ComponentDependencyModelEntity dependency) { - ZusammenElement componentDependencyElement = - buildElement(new Id(dependency.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, - String.format("Delete component dependency model with id %s", dependency.getId())); - } - - @Override - public void registerVersioning(String versionableEntityType) { - //not implemented? - } - - @Override - public Collection list( - ComponentDependencyModelEntity dependency) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - Optional vspModel = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return new ArrayList<>(); + @Override + public ComponentDependencyModelEntity get(ComponentDependencyModelEntity dependency) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + Optional componentDependencyElement = zusammenAdaptor.getElementInfo(context, elementContext, new Id(dependency.getId())); + if (componentDependencyElement.isPresent()) { + ElementToComponentDependencyModelConvertor convertor = new ElementToComponentDependencyModelConvertor(); + ComponentDependencyModelEntity entity = convertor.convert(componentDependencyElement.get()); + entity.setVspId(dependency.getVspId()); + entity.setVersion(dependency.getVersion()); + return entity; + } + return null; } - ElementToComponentDependencyModelConvertor convertor = - new ElementToComponentDependencyModelConvertor(); - return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), - ElementType.ComponentDependencies.name()).stream() - .map(elementInfo -> { - ComponentDependencyModelEntity entity = convertor.convert(elementInfo); - entity.setVspId(dependency.getVspId()); - entity.setVersion(dependency.getVersion()); - entity.setId(elementInfo.getId().getValue()); - return entity; - }) - .collect(Collectors.toList()); - } + @Override + public void create(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependency = buildComponentDependencyElement(dependency, Action.CREATE); + ZusammenElement componentDependencies = buildStructuralElement(ElementType.ComponentDependencies, Action.IGNORE); + componentDependencies.addSubElement(componentDependency); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(componentDependencies); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + Element compDepsSavedElement = zusammenAdaptor.saveElement(context, elementContext, vspModel, "Create component dependency model"); + dependency.setId(compDepsSavedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - private ZusammenElement buildComponentDependencyElement(ComponentDependencyModelEntity compDep, - Action action) { - ZusammenElement componentDependencyElement = - buildElement(compDep.getId() == null ? null : new Id(compDep.getId()), action); + @Override + public void update(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependencyElement = buildComponentDependencyElement(dependency, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, + String.format("Update component dependency model with id %s", dependency.getId())); + } - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.ComponentDependency); - info.addProperty(ComponentDependencyModelPropertyName.RELATION.getVal(), compDep.getRelation()); - info.addProperty(ComponentDependencyModelPropertyName.SOURCE_COMPONENT_ID.getVal(), - compDep.getSourceComponentId()); - info.addProperty(ComponentDependencyModelPropertyName.TARGET_COMPONENT_ID.getVal(), - compDep.getTargetComponentId()); + @Override + public void delete(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependencyElement = buildElement(new Id(dependency.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, + String.format("Delete component dependency model with id %s", dependency.getId())); + } - componentDependencyElement.setInfo(info); + @Override + public void registerVersioning(String versionableEntityType) { + //not implemented? + } - return componentDependencyElement; - } + @Override + public Collection list(ComponentDependencyModelEntity dependency) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } + ElementToComponentDependencyModelConvertor convertor = new ElementToComponentDependencyModelConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), ElementType.ComponentDependencies.name()).stream() + .map(elementInfo -> { + ComponentDependencyModelEntity entity = convertor.convert(elementInfo); + entity.setVspId(dependency.getVspId()); + entity.setVersion(dependency.getVersion()); + entity.setId(elementInfo.getId().getValue()); + return entity; + }).collect(Collectors.toList()); + } - private enum ComponentDependencyModelPropertyName { - ID("id"), - RELATION("relation"), - SOURCE_COMPONENT_ID("sourcecomponent_id"), - TARGET_COMPONENT_ID("targetcomponent_id"); + private ZusammenElement buildComponentDependencyElement(ComponentDependencyModelEntity compDep, Action action) { + ZusammenElement componentDependencyElement = buildElement(compDep.getId() == null ? null : new Id(compDep.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.ComponentDependency); + info.addProperty(ComponentDependencyModelPropertyName.RELATION.getVal(), compDep.getRelation()); + info.addProperty(ComponentDependencyModelPropertyName.SOURCE_COMPONENT_ID.getVal(), compDep.getSourceComponentId()); + info.addProperty(ComponentDependencyModelPropertyName.TARGET_COMPONENT_ID.getVal(), compDep.getTargetComponentId()); + componentDependencyElement.setInfo(info); + return componentDependencyElement; + } - private String val; + private enum ComponentDependencyModelPropertyName { + ID("id"), RELATION("relation"), SOURCE_COMPONENT_ID("sourcecomponent_id"), TARGET_COMPONENT_ID("targetcomponent_id"); + private String val; - ComponentDependencyModelPropertyName(String val){ - this.val=val; - } + ComponentDependencyModelPropertyName(String val) { + this.val = val; + } - public String getVal() { - return val; + public String getVal() { + return val; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelPropertyName.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelPropertyName.java index 534c253811..7624886b9c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelPropertyName.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelPropertyName.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; /** * Created by ayalaben on 5/16/2017 */ -public enum ComponentDependencyModelPropertyName { - id, - relation, - sourcecomponent_id, - targetcomponent_id, - -} +public enum ComponentDependencyModelPropertyName {id, relation, sourcecomponent_id, targetcomponent_id,} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java index d1b540b312..48111ad041 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +30,11 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; @@ -38,222 +45,156 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class ComputeDaoZusammenImpl implements ComputeDao { - private ZusammenAdaptor zusammenAdaptor; - - public ComputeDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for ComputeDaoZusammenImpl - } - - @Override - public Collection list(ComputeEntity compute) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(compute.getVspId(), compute.getVersion().getId()); - - return listComputes(context, elementContext, compute); - } - - private Collection listComputes(SessionContext context, - ElementContext elementContext, - ComputeEntity compute) { - return zusammenAdaptor - .listElementsByName(context, elementContext, new Id(compute.getComponentId()), - ElementType.Computes.name()) - .stream() - .map(new ElementToComputeConvertor()::convert) - .map(computeEntity -> { - computeEntity.setComponentId(compute.getComponentId()); - computeEntity.setVspId(compute.getVspId()); - computeEntity.setVersion(compute.getVersion()); - return computeEntity; - }) - .collect(Collectors.toList()); - } - - @Override - public void create(ComputeEntity compute) { - ZusammenElement computeElement = computeToZusammen(compute, Action.CREATE); - - ZusammenElement computesElement = buildStructuralElement(ElementType.Computes, Action.IGNORE); - computesElement.setSubElements(Collections.singletonList(computeElement)); - - ZusammenElement componentElement = - buildElement(new Id(compute.getComponentId()), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList(computesElement)); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(compute.getVspId(), compute.getVersion().getId()); + private ZusammenAdaptor zusammenAdaptor; - Element savedElement = - zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create compute"); - compute.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(ComputeEntity compute) { - ZusammenElement computeElement = computeToZusammen(compute, Action.UPDATE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(compute.getVspId(), compute.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, computeElement, - String.format("Update compute with id %s", compute.getId())); - } - - @Override - public ComputeEntity get(ComputeEntity compute) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(compute.getVspId(), compute.getVersion().getId()); - Optional element = - zusammenAdaptor.getElement(context, elementContext, compute.getId()); - - if (element.isPresent()) { - - ElementToComputeConvertor convertor = new ElementToComputeConvertor(); - ComputeEntity entity = convertor.convert(element.get()); - entity.setVspId(compute.getVspId()); - entity.setVersion(compute.getVersion()); - entity.setComponentId(compute.getComponentId()); - return entity; - } else { - return null; + public ComputeDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - } - - @Override - public void delete(ComputeEntity compute) { - ZusammenElement computeElement = buildElement(new Id(compute.getId()), Action.DELETE); - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(compute.getVspId(), compute.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, computeElement, - String.format("Delete compute with id %s", compute.getId())); - } - - @Override - public ComputeEntity getQuestionnaireData(String vspId, Version version, String componentId, - String computeId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - return getQuestionnaire(context, elementContext, - new ComputeEntity(vspId, version, componentId, computeId)); - } - - private ComputeEntity getQuestionnaire(SessionContext context, ElementContext elementContext, - ComputeEntity compute) { - Optional questionnaireElement = zusammenAdaptor - .getElementByName(context, elementContext, new Id(compute.getId()), - ElementType.ComputeQuestionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - compute.setQuestionnaireData(questionnaireData); - return compute; - }) - .orElse(null); - } + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for ComputeDaoZusammenImpl + } - @Override - public void updateQuestionnaireData(String vspId, Version version, String componentId, - String computeId, String questionnaireData) { - ZusammenElement questionnaireElement = - computeQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + @Override + public Collection list(ComputeEntity compute) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(compute.getVspId(), compute.getVersion().getId()); + return listComputes(context, elementContext, compute); + } - ZusammenElement computeElement = buildElement(new Id(computeId), Action.IGNORE); - computeElement.setSubElements(Collections.singletonList(questionnaireElement)); + private Collection listComputes(SessionContext context, ElementContext elementContext, ComputeEntity compute) { + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(compute.getComponentId()), ElementType.Computes.name()).stream() + .map(new ElementToComputeConvertor()::convert).map(computeEntity -> { + computeEntity.setComponentId(compute.getComponentId()); + computeEntity.setVspId(compute.getVspId()); + computeEntity.setVersion(compute.getVersion()); + return computeEntity; + }).collect(Collectors.toList()); + } - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, computeElement, "Update compute " - + "questionnaire"); - } + @Override + public void create(ComputeEntity compute) { + ZusammenElement computeElement = computeToZusammen(compute, Action.CREATE); + ZusammenElement computesElement = buildStructuralElement(ElementType.Computes, Action.IGNORE); + computesElement.setSubElements(Collections.singletonList(computeElement)); + ZusammenElement componentElement = buildElement(new Id(compute.getComponentId()), Action.IGNORE); + componentElement.setSubElements(Collections.singletonList(computesElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(compute.getVspId(), compute.getVersion().getId()); + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create compute"); + compute.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - @Override - public Collection listByVsp(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + @Override + public void update(ComputeEntity compute) { + ZusammenElement computeElement = computeToZusammen(compute, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(compute.getVspId(), compute.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, computeElement, String.format("Update compute with id %s", compute.getId())); + } - Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, vspId, version); + @Override + public ComputeEntity get(ComputeEntity compute) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(compute.getVspId(), compute.getVersion().getId()); + Optional element = zusammenAdaptor.getElement(context, elementContext, compute.getId()); + if (element.isPresent()) { + ElementToComputeConvertor convertor = new ElementToComputeConvertor(); + ComputeEntity entity = convertor.convert(element.get()); + entity.setVspId(compute.getVspId()); + entity.setVersion(compute.getVersion()); + entity.setComponentId(compute.getComponentId()); + return entity; + } else { + return null; + } + } - return components.stream() - .map(component -> - listComputes(context, elementContext, - new ComputeEntity(vspId, version, component.getId(), null)).stream() - .map(compute -> getQuestionnaire(context, elementContext, compute)) - .collect(Collectors.toList())) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } + @Override + public void delete(ComputeEntity compute) { + ZusammenElement computeElement = buildElement(new Id(compute.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(compute.getVspId(), compute.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, computeElement, String.format("Delete compute with id %s", compute.getId())); + } - @Override - public void deleteAll(String vspId, Version version) { + @Override + public ComputeEntity getQuestionnaireData(String vspId, Version version, String componentId, String computeId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + return getQuestionnaire(context, elementContext, new ComputeEntity(vspId, version, componentId, computeId)); + } - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + private ComputeEntity getQuestionnaire(SessionContext context, ElementContext elementContext, ComputeEntity compute) { + Optional questionnaireElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(compute.getId()), ElementType.ComputeQuestionnaire.name()); + return questionnaireElement.map(element -> element.getData() == null ? null : new String(FileUtils.toByteArray(element.getData()))) + .map(questionnaireData -> { + compute.setQuestionnaireData(questionnaireData); + return compute; + }).orElse(null); + } - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, null, ElementType.Computes.name()); + @Override + public void updateQuestionnaireData(String vspId, Version version, String componentId, String computeId, String questionnaireData) { + ZusammenElement questionnaireElement = computeQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + ZusammenElement computeElement = buildElement(new Id(computeId), Action.IGNORE); + computeElement.setSubElements(Collections.singletonList(questionnaireElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, computeElement, "Update compute " + "questionnaire"); + } - if (optionalElement.isPresent()) { - Element computesElement = optionalElement.get(); - Collection computes = computesElement.getSubElements(); + @Override + public Collection listByVsp(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Collection components = ComponentDaoZusammenImpl.listComponents(zusammenAdaptor, context, vspId, version); + return components.stream().map( + component -> listComputes(context, elementContext, new ComputeEntity(vspId, version, component.getId(), null)).stream() + .map(compute -> getQuestionnaire(context, elementContext, compute)).collect(Collectors.toList())).flatMap(Collection::stream) + .collect(Collectors.toList()); + } - computes.forEach(compute -> { - ZusammenElement computeElement = buildElement(compute.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, computeElement, - "Delete compute with id " + compute.getElementId()); - }); + @Override + public void deleteAll(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional optionalElement = zusammenAdaptor.getElementByName(context, elementContext, null, ElementType.Computes.name()); + if (optionalElement.isPresent()) { + Element computesElement = optionalElement.get(); + Collection computes = computesElement.getSubElements(); + computes.forEach(compute -> { + ZusammenElement computeElement = buildElement(compute.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, computeElement, "Delete compute with id " + compute.getElementId()); + }); + } } - } - private ZusammenElement computeToZusammen(ComputeEntity compute, Action action) { - ZusammenElement computeElement = buildComputeElement(compute, action); - if (action == Action.CREATE) { - computeElement.setSubElements(Collections.singletonList( - computeQuestionnaireToZusammen(compute.getQuestionnaireData(), Action.CREATE))); + private ZusammenElement computeToZusammen(ComputeEntity compute, Action action) { + ZusammenElement computeElement = buildComputeElement(compute, action); + if (action == Action.CREATE) { + computeElement.setSubElements(Collections.singletonList(computeQuestionnaireToZusammen(compute.getQuestionnaireData(), Action.CREATE))); + } + return computeElement; } - return computeElement; - } - private ZusammenElement computeQuestionnaireToZusammen(String questionnaireData, - Action action) { - ZusammenElement questionnaireElement = - buildStructuralElement(ElementType.ComputeQuestionnaire, action); - questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); - return questionnaireElement; - } + private ZusammenElement computeQuestionnaireToZusammen(String questionnaireData, Action action) { + ZusammenElement questionnaireElement = buildStructuralElement(ElementType.ComputeQuestionnaire, action); + questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); + return questionnaireElement; + } - private ZusammenElement buildComputeElement(ComputeEntity compute, Action action) { - ZusammenElement computeElement = - buildElement(compute.getId() == null ? null : new Id(compute.getId()), action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Compute); - info.addProperty(ElementPropertyName.compositionData.name(), compute.getCompositionData()); - computeElement.setInfo(info); - computeElement.setData(new ByteArrayInputStream(compute.getCompositionData().getBytes())); - return computeElement; - } + private ZusammenElement buildComputeElement(ComputeEntity compute, Action action) { + ZusammenElement computeElement = buildElement(compute.getId() == null ? null : new Id(compute.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Compute); + info.addProperty(ElementPropertyName.compositionData.name(), compute.getCompositionData()); + computeElement.setInfo(info); + computeElement.setData(new ByteArrayInputStream(compute.getCompositionData().getBytes())); + return computeElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java index 8ccaf083d1..d72bd6b9b9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; @@ -27,6 +30,10 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; @@ -36,153 +43,105 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { - private ZusammenAdaptor zusammenAdaptor; - - public DeploymentFlavorDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for DeploymentFlavorDaoZusammenImpl - } - - @Override - public Collection list(DeploymentFlavorEntity deploymentFlavor) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); - - return listDeploymentFlavor(zusammenAdaptor, context, elementContext, - deploymentFlavor.getVspId(), - deploymentFlavor.getVersion()); - } + private ZusammenAdaptor zusammenAdaptor; - private static Collection listDeploymentFlavor( - ZusammenAdaptor zusammenAdaptor, - SessionContext context, - ElementContext elementContext, - String vspId, Version version) { - ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); - return zusammenAdaptor - .listElementsByName(context, elementContext, null, - ElementType.DeploymentFlavors.name()) - .stream().map(elementInfo -> { - DeploymentFlavorEntity entity = convertor.convert( - elementInfo); - entity.setVspId(vspId); - entity.setVersion(version); - return entity; - }) - .collect(Collectors.toList()); - } - - - @Override - public void create(DeploymentFlavorEntity deploymentFlavor) { - ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, - Action.CREATE); - ZusammenElement deploymentFlavorElements = - buildStructuralElement(ElementType.DeploymentFlavors, Action.IGNORE); - deploymentFlavorElements.getSubElements().add(deploymentFlavorElement); - - SessionContext context = createSessionContext(); - Element savedElement = zusammenAdaptor.saveElement(context, - new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), - deploymentFlavorElements, "Create deloymentFlavor"); - deploymentFlavor.setId(savedElement.getSubElements().iterator().next().getElementId() - .getValue()); - } - - @Override - public void update(DeploymentFlavorEntity deploymentFlavor) { - ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, - Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), - deploymentFlavorElement, String.format("Update deloymentFlavor with id %s", - deploymentFlavor.getId())); - } - - @Override - public DeploymentFlavorEntity get(DeploymentFlavorEntity deploymentFlavor) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); - - Optional element = - zusammenAdaptor.getElement(context, elementContext, deploymentFlavor.getId()); + public DeploymentFlavorDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - if (element.isPresent()) { - ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); - DeploymentFlavorEntity entity = convertor.convert(element.get()); - deploymentFlavor.setCompositionData(new String(FileUtils.toByteArray(element.get() - .getData()))); - entity.setVspId(deploymentFlavor.getVspId()); - entity.setVersion(deploymentFlavor.getVersion()); - return entity; + private static Collection listDeploymentFlavor(ZusammenAdaptor zusammenAdaptor, SessionContext context, + ElementContext elementContext, String vspId, Version version) { + ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.DeploymentFlavors.name()).stream().map(elementInfo -> { + DeploymentFlavorEntity entity = convertor.convert(elementInfo); + entity.setVspId(vspId); + entity.setVersion(version); + return entity; + }).collect(Collectors.toList()); } - return null; - } - @Override - public void delete(DeploymentFlavorEntity deploymentFlavor) { - ZusammenElement componentElement = - buildElement(new Id(deploymentFlavor.getId()), Action.DELETE); + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for DeploymentFlavorDaoZusammenImpl + } - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), - componentElement, String.format("Delete deloymentFlavor with id %s", - deploymentFlavor.getId())); - } + @Override + public Collection list(DeploymentFlavorEntity deploymentFlavor) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); + return listDeploymentFlavor(zusammenAdaptor, context, elementContext, deploymentFlavor.getVspId(), deploymentFlavor.getVersion()); + } - @Override - public void deleteAll(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + @Override + public void create(DeploymentFlavorEntity deploymentFlavor) { + ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.CREATE); + ZusammenElement deploymentFlavorElements = buildStructuralElement(ElementType.DeploymentFlavors, Action.IGNORE); + deploymentFlavorElements.getSubElements().add(deploymentFlavorElement); + SessionContext context = createSessionContext(); + Element savedElement = zusammenAdaptor + .saveElement(context, new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), deploymentFlavorElements, + "Create deloymentFlavor"); + deploymentFlavor.setId(savedElement.getSubElements().iterator().next().getElementId().getValue()); + } - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, null, ElementType.DeploymentFlavors.name()); + @Override + public void update(DeploymentFlavorEntity deploymentFlavor) { + ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), deploymentFlavorElement, + String.format("Update deloymentFlavor with id %s", deploymentFlavor.getId())); + } - if (optionalElement.isPresent()) { - Element deploymentFlavorsElement = optionalElement.get(); - Collection deploymentFlavors = deploymentFlavorsElement.getSubElements(); + @Override + public DeploymentFlavorEntity get(DeploymentFlavorEntity deploymentFlavor) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); + Optional element = zusammenAdaptor.getElement(context, elementContext, deploymentFlavor.getId()); + if (element.isPresent()) { + ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); + DeploymentFlavorEntity entity = convertor.convert(element.get()); + deploymentFlavor.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); + entity.setVspId(deploymentFlavor.getVspId()); + entity.setVersion(deploymentFlavor.getVersion()); + return entity; + } + return null; + } - deploymentFlavors.forEach(deplymentFlavor -> { - ZusammenElement deplymentFlavorZusammenElement = - buildElement(deplymentFlavor.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, - elementContext, deplymentFlavorZusammenElement, " Delete Deplyment Flavor with id " - + deplymentFlavor.getElementId()); - }); + @Override + public void delete(DeploymentFlavorEntity deploymentFlavor) { + ZusammenElement componentElement = buildElement(new Id(deploymentFlavor.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), componentElement, + String.format("Delete deloymentFlavor with id %s", deploymentFlavor.getId())); } - } - private ZusammenElement deploymentFlavorToZusammen(DeploymentFlavorEntity deploymentFlavor, - Action action) { - ZusammenElement deploymentFlavorElement = - buildElement(deploymentFlavor.getId() == null ? null : new Id(deploymentFlavor.getId()), - action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.DeploymentFlavor); - info.addProperty(ElementPropertyName.compositionData.name(), deploymentFlavor - .getCompositionData()); - deploymentFlavorElement.setInfo(info); - deploymentFlavorElement.setData(new ByteArrayInputStream(deploymentFlavor.getCompositionData() - .getBytes())); - return deploymentFlavorElement; - } + @Override + public void deleteAll(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional optionalElement = zusammenAdaptor.getElementByName(context, elementContext, null, ElementType.DeploymentFlavors.name()); + if (optionalElement.isPresent()) { + Element deploymentFlavorsElement = optionalElement.get(); + Collection deploymentFlavors = deploymentFlavorsElement.getSubElements(); + deploymentFlavors.forEach(deplymentFlavor -> { + ZusammenElement deplymentFlavorZusammenElement = buildElement(deplymentFlavor.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, deplymentFlavorZusammenElement, + " Delete Deplyment Flavor with id " + deplymentFlavor.getElementId()); + }); + } + } + private ZusammenElement deploymentFlavorToZusammen(DeploymentFlavorEntity deploymentFlavor, Action action) { + ZusammenElement deploymentFlavorElement = buildElement(deploymentFlavor.getId() == null ? null : new Id(deploymentFlavor.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.DeploymentFlavor); + info.addProperty(ElementPropertyName.compositionData.name(), deploymentFlavor.getCompositionData()); + deploymentFlavorElement.setInfo(info); + deploymentFlavorElement.setData(new ByteArrayInputStream(deploymentFlavor.getCompositionData().getBytes())); + return deploymentFlavorElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java index f82827d02b..5227a4cff4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +30,11 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; @@ -38,220 +45,156 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class ImageDaoZusammenImpl implements ImageDao { - private ZusammenAdaptor zusammenAdaptor; - - public ImageDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for ImageDaoZusammenImpl - } - - @Override - public Collection list(ImageEntity image) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(image.getVspId(), image.getVersion().getId()); - - return listImages(context, elementContext, image); - } - - private Collection listImages(SessionContext context, - ElementContext elementContext, ImageEntity image) { - return zusammenAdaptor - .listElementsByName(context, elementContext, new Id(image.getComponentId()), - ElementType.Images.name()) - .stream().map(new ElementToImageConvertor()::convert) - .map(imageEntity -> { - imageEntity.setComponentId(image.getComponentId()); - imageEntity.setVspId(image.getVspId()); - imageEntity.setVersion(image.getVersion()); - return imageEntity; - }) - .collect(Collectors.toList()); - } - - @Override - public void create(ImageEntity image) { - ZusammenElement imageElement = imageToZusammen(image, Action.CREATE); - - ZusammenElement imagesElement = - buildStructuralElement(ElementType.Images, Action.IGNORE); - imagesElement.setSubElements(Collections.singletonList(imageElement)); - - ZusammenElement componentElement = buildElement(new Id(image.getComponentId()), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList(imagesElement)); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(image.getVspId(), image.getVersion().getId()); - - Element savedElement = - zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create image"); - image.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public void update(ImageEntity image) { - ZusammenElement imageElement = imageToZusammen(image, Action.UPDATE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(image.getVspId(), image.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, imageElement, - String.format("Update image with id %s", image.getId())); - } - - @Override - public ImageEntity get(ImageEntity image) { - SessionContext context = createSessionContext(); - - ElementContext elementContext = - new ElementContext(image.getVspId(), image.getVersion().getId()); - Optional element = zusammenAdaptor.getElement(context, elementContext, image.getId()); - - if (element.isPresent()) { - ElementToImageConvertor convertor = new ElementToImageConvertor(); - ImageEntity entity = convertor.convert(element.get()); - entity.setComponentId(image.getComponentId()); - entity.setVspId(image.getVspId()); - entity.setVersion(image.getVersion()); - return entity; - } else { - return null; + public ImageDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - } - - @Override - public void delete(ImageEntity image) { - ZusammenElement imageElement = buildElement(new Id(image.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(image.getVspId(), image.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, imageElement, - String.format("Delete image with id %s", image.getId())); - } - @Override - public void deleteByVspId(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional elementOptional = zusammenAdaptor.getElementByName(context, elementContext, - null, ElementType.Images.name()); - - if (elementOptional.isPresent()) { - Element imagesElement = elementOptional.get(); - Collection images = imagesElement.getSubElements(); - images.forEach(image -> { - ZusammenElement imageZusammenElement = buildElement(image.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, imageZusammenElement, "Delete image " + - "with id " + image.getElementId()); - }); + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for ImageDaoZusammenImpl } - } - - @Override - public Collection listByVsp(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, vspId, version); + @Override + public Collection list(ImageEntity image) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(image.getVspId(), image.getVersion().getId()); + return listImages(context, elementContext, image); + } - return components.stream() - .map(component -> - listImages(context, elementContext, - new ImageEntity(vspId, version, component.getId(), null)).stream() - .map(image -> getQuestionnaire(context, elementContext, image)) - .collect(Collectors.toList())) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } + private Collection listImages(SessionContext context, ElementContext elementContext, ImageEntity image) { + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(image.getComponentId()), ElementType.Images.name()).stream() + .map(new ElementToImageConvertor()::convert).map(imageEntity -> { + imageEntity.setComponentId(image.getComponentId()); + imageEntity.setVspId(image.getVspId()); + imageEntity.setVersion(image.getVersion()); + return imageEntity; + }).collect(Collectors.toList()); + } - @Override - public ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, - String imageId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + @Override + public void create(ImageEntity image) { + ZusammenElement imageElement = imageToZusammen(image, Action.CREATE); + ZusammenElement imagesElement = buildStructuralElement(ElementType.Images, Action.IGNORE); + imagesElement.setSubElements(Collections.singletonList(imageElement)); + ZusammenElement componentElement = buildElement(new Id(image.getComponentId()), Action.IGNORE); + componentElement.setSubElements(Collections.singletonList(imagesElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(image.getVspId(), image.getVersion().getId()); + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create image"); + image.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - return getQuestionnaire(context, elementContext, - new ImageEntity(vspId, version, componentId, imageId)); - } + @Override + public void update(ImageEntity image) { + ZusammenElement imageElement = imageToZusammen(image, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(image.getVspId(), image.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, imageElement, String.format("Update image with id %s", image.getId())); + } - private ImageEntity getQuestionnaire(SessionContext context, ElementContext elementContext, - ImageEntity image) { - Optional questionnaireElement = zusammenAdaptor - .getElementByName(context, elementContext, new Id(image.getId()), - ElementType.ImageQuestionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - image.setQuestionnaireData(questionnaireData); - return image; - }) - .orElse(null); - } + @Override + public ImageEntity get(ImageEntity image) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(image.getVspId(), image.getVersion().getId()); + Optional element = zusammenAdaptor.getElement(context, elementContext, image.getId()); + if (element.isPresent()) { + ElementToImageConvertor convertor = new ElementToImageConvertor(); + ImageEntity entity = convertor.convert(element.get()); + entity.setComponentId(image.getComponentId()); + entity.setVspId(image.getVspId()); + entity.setVersion(image.getVersion()); + return entity; + } else { + return null; + } + } - @Override - public void updateQuestionnaireData(String vspId, Version version, String componentId, - String imageId, String questionnaireData) { - ZusammenElement questionnaireElement = - imageQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + @Override + public void delete(ImageEntity image) { + ZusammenElement imageElement = buildElement(new Id(image.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(image.getVspId(), image.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, imageElement, String.format("Delete image with id %s", image.getId())); + } - ZusammenElement imageElement = buildElement(new Id(imageId), Action.IGNORE); - imageElement.setSubElements(Collections.singletonList(questionnaireElement)); + @Override + public void deleteByVspId(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional elementOptional = zusammenAdaptor.getElementByName(context, elementContext, null, ElementType.Images.name()); + if (elementOptional.isPresent()) { + Element imagesElement = elementOptional.get(); + Collection images = imagesElement.getSubElements(); + images.forEach(image -> { + ZusammenElement imageZusammenElement = buildElement(image.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, imageZusammenElement, "Delete image " + "with id " + image.getElementId()); + }); + } + } - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, imageElement, "Update image " - + "questionnaire"); - } + @Override + public Collection listByVsp(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Collection components = ComponentDaoZusammenImpl.listComponents(zusammenAdaptor, context, vspId, version); + return components.stream().map( + component -> listImages(context, elementContext, new ImageEntity(vspId, version, component.getId(), null)).stream() + .map(image -> getQuestionnaire(context, elementContext, image)).collect(Collectors.toList())).flatMap(Collection::stream) + .collect(Collectors.toList()); + } + @Override + public ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, String imageId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + return getQuestionnaire(context, elementContext, new ImageEntity(vspId, version, componentId, imageId)); + } - private ZusammenElement imageToZusammen(ImageEntity image, Action action) { - ZusammenElement imageElement = buildImageElement(image, action); - if (action == Action.CREATE) { - imageElement.setSubElements(Collections.singletonList( - imageQuestionnaireToZusammen(image.getQuestionnaireData(), Action.CREATE))); + private ImageEntity getQuestionnaire(SessionContext context, ElementContext elementContext, ImageEntity image) { + Optional questionnaireElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(image.getId()), ElementType.ImageQuestionnaire.name()); + return questionnaireElement.map(element -> element.getData() == null ? null : new String(FileUtils.toByteArray(element.getData()))) + .map(questionnaireData -> { + image.setQuestionnaireData(questionnaireData); + return image; + }).orElse(null); } - return imageElement; - } - private ZusammenElement imageQuestionnaireToZusammen(String questionnaireData, - Action action) { - ZusammenElement questionnaireElement = - buildStructuralElement(ElementType.ImageQuestionnaire, action); - questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); - return questionnaireElement; - } + @Override + public void updateQuestionnaireData(String vspId, Version version, String componentId, String imageId, String questionnaireData) { + ZusammenElement questionnaireElement = imageQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + ZusammenElement imageElement = buildElement(new Id(imageId), Action.IGNORE); + imageElement.setSubElements(Collections.singletonList(questionnaireElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, imageElement, "Update image " + "questionnaire"); + } - private ZusammenElement buildImageElement(ImageEntity image, Action action) { - ZusammenElement imageElement = - buildElement(image.getId() == null ? null : new Id(image.getId()), action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Image); - info.addProperty(ElementPropertyName.compositionData.name(), image.getCompositionData()); - imageElement.setInfo(info); - imageElement.setData(new ByteArrayInputStream(image.getCompositionData().getBytes())); - return imageElement; - } + private ZusammenElement imageToZusammen(ImageEntity image, Action action) { + ZusammenElement imageElement = buildImageElement(image, action); + if (action == Action.CREATE) { + imageElement.setSubElements(Collections.singletonList(imageQuestionnaireToZusammen(image.getQuestionnaireData(), Action.CREATE))); + } + return imageElement; + } + private ZusammenElement imageQuestionnaireToZusammen(String questionnaireData, Action action) { + ZusammenElement questionnaireElement = buildStructuralElement(ElementType.ImageQuestionnaire, action); + questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); + return questionnaireElement; + } + private ZusammenElement buildImageElement(ImageEntity image, Action action) { + ZusammenElement imageElement = buildElement(image.getId() == null ? null : new Id(image.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Image); + info.addProperty(ElementPropertyName.compositionData.name(), image.getCompositionData()); + imageElement.setInfo(info); + imageElement.setData(new ByteArrayInputStream(image.getCompositionData().getBytes())); + return imageElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java index 4099e1264b..0230f3e486 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +31,12 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; @@ -36,141 +45,103 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class NetworkDaoZusammenImpl implements NetworkDao { - private ZusammenAdaptor zusammenAdaptor; - - public NetworkDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for NetworkDaoZusammenImpl - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public Collection list(NetworkEntity network) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(network.getVspId(), network.getVersion().getId()); - - Optional vspModel = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return new ArrayList<>(); + public NetworkDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), - ElementType.Networks.name()).stream() - .map(new ElementToNetworkConvertor()::convert) - .map(entity -> { - entity.setVspId(network.getVspId()); - entity.setVersion(network.getVersion()); - return entity; - }) - .collect(Collectors.toList()); - } - - @Override - public void create(NetworkEntity network) { - ZusammenElement networkElement = buildNetworkElement(network, Action.CREATE); - - ZusammenElement networksElement = buildStructuralElement(ElementType.Networks, Action.IGNORE); - networksElement.setSubElements(Collections.singletonList(networkElement)); - - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(networksElement); - - SessionContext context = createSessionContext(); - Element savedElement = zusammenAdaptor - .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), - vspModel, "Create network"); - network.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(NetworkEntity network) { - ZusammenElement networkElement = buildNetworkElement(network, Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor - .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), - networkElement, String.format("Update network with id %s", network.getId())); - } - - @Override - public NetworkEntity get(NetworkEntity network) { - SessionContext context = createSessionContext(); - - Optional element = - zusammenAdaptor.getElement(context, - new ElementContext(network.getVspId(), network.getVersion().getId()), network.getId()); - - if (element.isPresent()) { - ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); - NetworkEntity entity = convertor.convert(element.get()); - entity.setVspId(network.getVspId()); - entity.setVersion(network.getVersion()); - return entity; - } else { - return null; + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for NetworkDaoZusammenImpl } - } - - @Override - public void delete(NetworkEntity network) { - ZusammenElement networkElement = buildElement(new Id(network.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - zusammenAdaptor - .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), - networkElement, String.format("Delete network with id %s", network.getId())); - } + @Override + public Collection list(NetworkEntity network) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(network.getVspId(), network.getVersion().getId()); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), ElementType.Networks.name()).stream() + .map(new ElementToNetworkConvertor()::convert).map(entity -> { + entity.setVspId(network.getVspId()); + entity.setVersion(network.getVersion()); + return entity; + }).collect(Collectors.toList()); + } - @Override - public void deleteAll(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + @Override + public void create(NetworkEntity network) { + ZusammenElement networkElement = buildNetworkElement(network, Action.CREATE); + ZusammenElement networksElement = buildStructuralElement(ElementType.Networks, Action.IGNORE); + networksElement.setSubElements(Collections.singletonList(networkElement)); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(networksElement); + SessionContext context = createSessionContext(); + Element savedElement = zusammenAdaptor + .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), vspModel, "Create network"); + network.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - Collection vspModelSubs = zusammenAdaptor - .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + @Override + public void update(NetworkEntity network) { + ZusammenElement networkElement = buildNetworkElement(network, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), networkElement, + String.format("Update network with id %s", network.getId())); + } - Optional networksElement = vspModelSubs.stream() - .filter(elementInfo -> elementInfo.getInfo() != null - && ElementType.Networks.name().equals(elementInfo.getInfo().getName())) - .findFirst(); - if (!networksElement.isPresent()) { - return; + @Override + public NetworkEntity get(NetworkEntity network) { + SessionContext context = createSessionContext(); + Optional element = zusammenAdaptor + .getElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), network.getId()); + if (element.isPresent()) { + ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); + NetworkEntity entity = convertor.convert(element.get()); + entity.setVspId(network.getVspId()); + entity.setVersion(network.getVersion()); + return entity; + } else { + return null; + } } - ZusammenElement networks = buildElement(networksElement.get().getId(), Action.IGNORE); - networks.setSubElements(networksElement.get().getSubElements().stream() - .map(network -> buildElement(network.getId(), Action.DELETE)) - .collect(Collectors.toList())); + @Override + public void delete(NetworkEntity network) { + ZusammenElement networkElement = buildElement(new Id(network.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), networkElement, + String.format("Delete network with id %s", network.getId())); + } - zusammenAdaptor.saveElement(context, elementContext, networks, "Delete all networks"); - } + @Override + public void deleteAll(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Collection vspModelSubs = zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + Optional networksElement = vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null && ElementType.Networks.name().equals(elementInfo.getInfo().getName())).findFirst(); + if (!networksElement.isPresent()) { + return; + } + ZusammenElement networks = buildElement(networksElement.get().getId(), Action.IGNORE); + networks.setSubElements(networksElement.get().getSubElements().stream().map(network -> buildElement(network.getId(), Action.DELETE)) + .collect(Collectors.toList())); + zusammenAdaptor.saveElement(context, elementContext, networks, "Delete all networks"); + } - private ZusammenElement buildNetworkElement(NetworkEntity network, Action action) { - ZusammenElement networkElement = - buildElement(network.getId() == null ? null : new Id(network.getId()), action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Network); - info.addProperty(ElementPropertyName.compositionData.name(), network.getCompositionData()); - networkElement.setInfo(info); - networkElement.setData(new ByteArrayInputStream(network.getCompositionData().getBytes())); - return networkElement; - } + private ZusammenElement buildNetworkElement(NetworkEntity network, Action action) { + ZusammenElement networkElement = buildElement(network.getId() == null ? null : new Id(network.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Network); + info.addProperty(ElementPropertyName.compositionData.name(), network.getCompositionData()); + networkElement.setInfo(info); + networkElement.setData(new ByteArrayInputStream(network.getCompositionData().getBytes())); + return networkElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java index 05f8d9dcfc..baad1d7c89 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; @@ -27,6 +30,11 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.Collections; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; @@ -37,217 +45,159 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.Collections; -import java.util.Optional; -import java.util.stream.Collectors; +public class NicDaoZusammenImpl implements NicDao { -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; + private ZusammenAdaptor zusammenAdaptor; -public class NicDaoZusammenImpl implements NicDao { + public NicDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning is not implemented for NicDaoZusammenImpl + } + + @Override + public Collection list(NicEntity nic) { + SessionContext context = createSessionContext(); + return listNics(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nic); + } + + private Collection listNics(SessionContext context, ElementContext elementContext, NicEntity nic) { + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(nic.getComponentId()), ElementType.Nics.name()).stream() + .map(new ElementToNicConvertor()::convert).map(nicEntity -> { + nicEntity.setComponentId(nic.getComponentId()); + nicEntity.setVspId(nic.getVspId()); + nicEntity.setVersion(nic.getVersion()); + return nicEntity; + }).collect(Collectors.toList()); + } + + @Override + public void create(NicEntity nic) { + ZusammenElement nicElement = nicToZusammen(nic, Action.CREATE); + ZusammenElement nicsElement = buildStructuralElement(ElementType.Nics, Action.IGNORE); + nicsElement.setSubElements(Collections.singletonList(nicElement)); + ZusammenElement componentElement = buildElement(new Id(nic.getComponentId()), Action.IGNORE); + componentElement.setSubElements(Collections.singletonList(nicsElement)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(nic.getVspId(), nic.getVersion().getId()); + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create nic"); + nic.setId(savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); + } - private ZusammenAdaptor zusammenAdaptor; - - public NicDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning is not implemented for NicDaoZusammenImpl - } - - @Override - public Collection list(NicEntity nic) { - SessionContext context = createSessionContext(); - return listNics(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nic); - } - - private Collection listNics(SessionContext context, ElementContext elementContext, - NicEntity nic) { - return zusammenAdaptor.listElementsByName(context, elementContext, new Id(nic.getComponentId()), - ElementType.Nics.name()) - .stream() - .map(new ElementToNicConvertor()::convert) - .map(nicEntity -> { - nicEntity.setComponentId(nic.getComponentId()); - nicEntity.setVspId(nic.getVspId()); - nicEntity.setVersion(nic.getVersion()); - return nicEntity; - }) - .collect(Collectors.toList()); - } - - - @Override - public void create(NicEntity nic) { - ZusammenElement nicElement = nicToZusammen(nic, Action.CREATE); - - ZusammenElement nicsElement = buildStructuralElement(ElementType.Nics, Action.IGNORE); - nicsElement.setSubElements(Collections.singletonList(nicElement)); - - ZusammenElement componentElement = buildElement(new Id(nic.getComponentId()), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList(nicsElement)); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(nic.getVspId(), nic.getVersion().getId()); - - Element savedElement = - zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create nic"); - nic.setId(savedElement.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - - @Override - public void update(NicEntity nic) { - ZusammenElement nicElement = nicToZusammen(nic, Action.UPDATE); - - SessionContext context = createSessionContext(); - zusammenAdaptor - .saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), - nicElement, String.format("Update nic with id %s", nic.getId())); - } - - @Override - public NicEntity get(NicEntity nic) { - SessionContext context = createSessionContext(); - ElementToNicConvertor convertor = new ElementToNicConvertor(); - Optional element = zusammenAdaptor - .getElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), - nic.getId()); - - if (element.isPresent()) { - NicEntity entity = convertor.convert(element.get()); - entity.setVspId(nic.getVspId()); - entity.setVersion(nic.getVersion()); - entity.setComponentId(nic.getComponentId()); - - return entity; - } else { - return null; - } - } - - @Override - public void delete(NicEntity nic) { - ZusammenElement nicElement = buildElement(new Id(nic.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - zusammenAdaptor - .saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), - nicElement, String.format("Delete nic with id %s", nic.getId())); - } - - @Override - public NicEntity getQuestionnaireData(String vspId, Version version, String componentId, - String nicId) { - SessionContext context = createSessionContext(); - - return getQuestionnaire(context, new ElementContext(vspId, version.getId()), - new NicEntity(vspId, version, componentId, nicId)); - } - - private NicEntity getQuestionnaire(SessionContext context, ElementContext elementContext, - NicEntity nic) { - Optional questionnaireElement = zusammenAdaptor - .getElementByName(context, elementContext, new Id(nic.getId()), - ElementType.NicQuestionnaire.name()); - return questionnaireElement.map(new ElementToNicQuestionnaireConvertor()::convert) - .map(entity -> { - entity.setVspId(nic.getVspId()); - entity.setVersion(nic.getVersion()); - entity.setComponentId(nic.getComponentId()); - return entity; - }) - .orElse(null); - } - - @Override - public void updateQuestionnaireData(String vspId, Version version, String componentId, - String nicId, String questionnaireData) { - ZusammenElement questionnaireElement = - nicQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - - ZusammenElement nicElement = buildElement(new Id(nicId), Action.IGNORE); - nicElement.setSubElements(Collections.singletonList(questionnaireElement)); - - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), nicElement, - "Update nic questionnaire"); - } - - @Override - public Collection listByVsp(String vspId, Version version) { - SessionContext context = createSessionContext(); - - Collection components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, vspId, version); - - ElementContext elementContext = new ElementContext(vspId, version.getId()); - return components.stream() - .map(component -> - listNics(context, elementContext, - new NicEntity(vspId, version, component.getId(), null)).stream() - .map(nic -> { - nic.setQuestionnaireData(getQuestionnaire(context, elementContext, nic).getQuestionnaireData()); - return nic; - }) - .collect(Collectors.toList())) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - - @Override - public void deleteByComponentId(String vspId, Version version, String componentId) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, new Id(componentId), ElementType.Nics.name()); - - if (optionalElement.isPresent()) { - Element nicsElement = optionalElement.get(); - Collection nics = nicsElement.getSubElements(); - - nics.forEach(nic -> { - ZusammenElement nicZusammenElement = buildElement(nic.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, nicZusammenElement, - "Delete nic with id " + nic.getElementId()); - }); - } - } - - @Override - public void deleteByVspId(String vspId, Version version) { - // deleteByVspId not implemented for NicDaoZusammenImpl - } - - private ZusammenElement nicToZusammen(NicEntity nic, Action action) { - ZusammenElement nicElement = buildNicElement(nic, action); - if (action == Action.CREATE) { - nicElement.setSubElements(Collections.singletonList( - nicQuestionnaireToZusammen(nic.getQuestionnaireData(), Action.CREATE))); - } - return nicElement; - } - - private ZusammenElement nicQuestionnaireToZusammen(String questionnaireData, - Action action) { - ZusammenElement questionnaireElement = - buildStructuralElement(ElementType.NicQuestionnaire, action); - questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); - return questionnaireElement; - } - - private ZusammenElement buildNicElement(NicEntity nic, Action action) { - ZusammenElement nicElement = - buildElement(nic.getId() == null ? null : new Id(nic.getId()), action); - Info info = new Info(); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Nic); - info.addProperty(ElementPropertyName.compositionData.name(), nic.getCompositionData()); - nicElement.setInfo(info); - nicElement.setData(new ByteArrayInputStream(nic.getCompositionData().getBytes())); - return nicElement; - } + @Override + public void update(NicEntity nic) { + ZusammenElement nicElement = nicToZusammen(nic, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nicElement, + String.format("Update nic with id %s", nic.getId())); + } + + @Override + public NicEntity get(NicEntity nic) { + SessionContext context = createSessionContext(); + ElementToNicConvertor convertor = new ElementToNicConvertor(); + Optional element = zusammenAdaptor.getElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nic.getId()); + if (element.isPresent()) { + NicEntity entity = convertor.convert(element.get()); + entity.setVspId(nic.getVspId()); + entity.setVersion(nic.getVersion()); + entity.setComponentId(nic.getComponentId()); + return entity; + } else { + return null; + } + } + + @Override + public void delete(NicEntity nic) { + ZusammenElement nicElement = buildElement(new Id(nic.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nicElement, + String.format("Delete nic with id %s", nic.getId())); + } + + @Override + public NicEntity getQuestionnaireData(String vspId, Version version, String componentId, String nicId) { + SessionContext context = createSessionContext(); + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new NicEntity(vspId, version, componentId, nicId)); + } + + private NicEntity getQuestionnaire(SessionContext context, ElementContext elementContext, NicEntity nic) { + Optional questionnaireElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(nic.getId()), ElementType.NicQuestionnaire.name()); + return questionnaireElement.map(new ElementToNicQuestionnaireConvertor()::convert).map(entity -> { + entity.setVspId(nic.getVspId()); + entity.setVersion(nic.getVersion()); + entity.setComponentId(nic.getComponentId()); + return entity; + }).orElse(null); + } + + @Override + public void updateQuestionnaireData(String vspId, Version version, String componentId, String nicId, String questionnaireData) { + ZusammenElement questionnaireElement = nicQuestionnaireToZusammen(questionnaireData, Action.UPDATE); + ZusammenElement nicElement = buildElement(new Id(nicId), Action.IGNORE); + nicElement.setSubElements(Collections.singletonList(questionnaireElement)); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), nicElement, "Update nic questionnaire"); + } + + @Override + public Collection listByVsp(String vspId, Version version) { + SessionContext context = createSessionContext(); + Collection components = ComponentDaoZusammenImpl.listComponents(zusammenAdaptor, context, vspId, version); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + return components.stream() + .map(component -> listNics(context, elementContext, new NicEntity(vspId, version, component.getId(), null)).stream().map(nic -> { + nic.setQuestionnaireData(getQuestionnaire(context, elementContext, nic).getQuestionnaireData()); + return nic; + }).collect(Collectors.toList())).flatMap(Collection::stream).collect(Collectors.toList()); + } + + @Override + public void deleteByComponentId(String vspId, Version version, String componentId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional optionalElement = zusammenAdaptor.getElementByName(context, elementContext, new Id(componentId), ElementType.Nics.name()); + if (optionalElement.isPresent()) { + Element nicsElement = optionalElement.get(); + Collection nics = nicsElement.getSubElements(); + nics.forEach(nic -> { + ZusammenElement nicZusammenElement = buildElement(nic.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, nicZusammenElement, "Delete nic with id " + nic.getElementId()); + }); + } + } + + @Override + public void deleteByVspId(String vspId, Version version) { + // deleteByVspId not implemented for NicDaoZusammenImpl + } + + private ZusammenElement nicToZusammen(NicEntity nic, Action action) { + ZusammenElement nicElement = buildNicElement(nic, action); + if (action == Action.CREATE) { + nicElement.setSubElements(Collections.singletonList(nicQuestionnaireToZusammen(nic.getQuestionnaireData(), Action.CREATE))); + } + return nicElement; + } + + private ZusammenElement nicQuestionnaireToZusammen(String questionnaireData, Action action) { + ZusammenElement questionnaireElement = buildStructuralElement(ElementType.NicQuestionnaire, action); + questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); + return questionnaireElement; + } + + private ZusammenElement buildNicElement(NicEntity nic, Action action) { + ZusammenElement nicElement = buildElement(nic.getId() == null ? null : new Id(nic.getId()), action); + Info info = new Info(); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Nic); + info.addProperty(ElementPropertyName.compositionData.name(), nic.getCompositionData()); + nicElement.setInfo(info); + nicElement.setData(new ByteArrayInputStream(nic.getCompositionData().getBytes())); + return nicElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java index 4c1e2e1ef2..fb26714375 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; @@ -41,251 +40,173 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCan import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; -public class OrchestrationTemplateCandidateDaoZusammenImpl - implements OrchestrationTemplateCandidateDao { - - private static final Logger logger = - LoggerFactory.getLogger(OrchestrationTemplateCandidateDaoZusammenImpl.class); - - private final ZusammenAdaptor zusammenAdaptor; - - private static final String EMPTY_DATA = "{}"; - - public OrchestrationTemplateCandidateDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } +public class OrchestrationTemplateCandidateDaoZusammenImpl implements OrchestrationTemplateCandidateDao { - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for OrchestrationTemplateCandidateDaoZusammenImpl - } + private static final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateDaoZusammenImpl.class); + private static final String EMPTY_DATA = "{}"; + private final ZusammenAdaptor zusammenAdaptor; - @Override - public Optional get(String vspId, Version version) { - logger.info("Getting orchestration template for vsp id {}", vspId); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional candidateElement = - zusammenAdaptor.getElementByName(context, elementContext, null, - ElementType.OrchestrationTemplateCandidate.name()); - - if (!candidateElement.isPresent() || - VspZusammenUtil.hasEmptyData(candidateElement.get().getData()) || - candidateElement.get().getSubElements().isEmpty()) { - logger.info("Orchestration template for vsp id {} does not exist / has empty data", vspId); - return Optional.empty(); + public OrchestrationTemplateCandidateDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - OrchestrationTemplateCandidateData candidate = new OrchestrationTemplateCandidateData(); - candidate.setFilesDataStructure( - new String(FileUtils.toByteArray(candidateElement.get().getData()))); - - candidateElement.get().getSubElements().stream() - .map(element -> zusammenAdaptor - .getElement(context, elementContext, element.getElementId().toString())) - .forEach(element -> element.ifPresent( - candidateInfoElement -> populateCandidate(candidate, candidateInfoElement, true))); - - logger.info("Finished getting orchestration template for vsp id {}", vspId); - return candidate.getFileSuffix() == null ? Optional.empty() : Optional.of(candidate); - } - - @Override - public Optional getInfo(String vspId, Version version) { - logger.info("Getting orchestration template info for vsp id {}", vspId); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional candidateElement = - zusammenAdaptor.getElementInfoByName(context, elementContext, null, - ElementType.OrchestrationTemplateCandidate.name()); - - if (!candidateElement.isPresent() || candidateElement.get().getSubElements().isEmpty()) { - logger.info("Orchestration template info for vsp id {} does not exist", vspId); - return Optional.empty(); + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for OrchestrationTemplateCandidateDaoZusammenImpl } - OrchestrationTemplateCandidateData candidate = new OrchestrationTemplateCandidateData(); - candidateElement.get().getSubElements().stream() - .map(elementInfo -> zusammenAdaptor - .getElement(context, elementContext, elementInfo.getId().toString())) - .forEach(element -> element.ifPresent( - candidateInfoElement -> populateCandidate(candidate, candidateInfoElement, false))); - logger.info("Finished getting orchestration template info for vsp id {}", vspId); - return candidate.getFileSuffix() == null ? Optional.empty() : Optional.of(candidate); - } - - private void populateCandidate(final OrchestrationTemplateCandidateData candidate, - final Element candidateInfoElement, - final boolean fullData) { - final String elementName = candidateInfoElement.getInfo().getName(); - if (ElementType.OrchestrationTemplateCandidateContent.name().equals(elementName)) { - if (fullData) { - candidate.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateInfoElement.getData()))); - } - candidate.setFileSuffix(candidateInfoElement.getInfo() - .getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); - candidate.setFileName(candidateInfoElement.getInfo() - .getProperty(InfoPropertyName.FILE_NAME.getVal())); - } else if (ElementType.OrchestrationTemplateCandidateValidationData.name().equals(elementName)) { - candidate.setValidationData(new String(FileUtils.toByteArray(candidateInfoElement.getData()))); - } else if (ElementType.ORIGINAL_ONBOARDED_PACKAGE.name().equals(elementName)) { - candidate.setOriginalFileName(candidateInfoElement.getInfo() - .getProperty(InfoPropertyName.ORIGINAL_FILE_NAME.getVal())); - candidate.setOriginalFileSuffix(candidateInfoElement.getInfo() - .getProperty(InfoPropertyName.ORIGINAL_FILE_SUFFIX.getVal())); - if (fullData) { - candidate.setOriginalFileContentData( - ByteBuffer.wrap(FileUtils.toByteArray(candidateInfoElement.getData())) - ); - } + @Override + public Optional get(String vspId, Version version) { + logger.info("Getting orchestration template for vsp id {}", vspId); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional candidateElement = zusammenAdaptor + .getElementByName(context, elementContext, null, ElementType.OrchestrationTemplateCandidate.name()); + if (!candidateElement.isPresent() || VspZusammenUtil.hasEmptyData(candidateElement.get().getData()) || candidateElement.get().getSubElements() + .isEmpty()) { + logger.info("Orchestration template for vsp id {} does not exist / has empty data", vspId); + return Optional.empty(); + } + OrchestrationTemplateCandidateData candidate = new OrchestrationTemplateCandidateData(); + candidate.setFilesDataStructure(new String(FileUtils.toByteArray(candidateElement.get().getData()))); + candidateElement.get().getSubElements().stream() + .map(element -> zusammenAdaptor.getElement(context, elementContext, element.getElementId().toString())) + .forEach(element -> element.ifPresent(candidateInfoElement -> populateCandidate(candidate, candidateInfoElement, true))); + logger.info("Finished getting orchestration template for vsp id {}", vspId); + return candidate.getFileSuffix() == null ? Optional.empty() : Optional.of(candidate); } - } - - @Override - public void delete(String vspId, Version version) { - ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); - - ZusammenElement candidateContentElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); - candidateContentElement.setData(emptyData); - - ZusammenElement validationData = buildStructuralElement(ElementType - .OrchestrationTemplateCandidateValidationData, Action.UPDATE); - validationData.setData(emptyData); - - ZusammenElement candidateElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); - candidateElement.setData(emptyData); - candidateElement.addSubElement(candidateContentElement); - candidateElement.addSubElement(validationData); - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, candidateElement, - "Delete Orchestration Template Candidate Elements's content"); - } - - @Override - public void update(final String vspId, final Version version, - final OrchestrationTemplateCandidateData candidateData) { - logger.info("Uploading candidate data entity for vsp id {}", vspId); - final ZusammenElement candidateElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); - candidateElement - .setData(new ByteArrayInputStream(candidateData.getFilesDataStructure().getBytes())); - - final ZusammenElement candidateContentElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); - candidateContentElement - .setData(new ByteArrayInputStream(candidateData.getContentData().array())); - candidateContentElement.getInfo() - .addProperty(InfoPropertyName.FILE_SUFFIX.getVal(), candidateData.getFileSuffix()); - candidateContentElement.getInfo() - .addProperty(InfoPropertyName.FILE_NAME.getVal(), candidateData.getFileName()); - - if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) { - final ZusammenElement originalPackageElement = - buildStructuralElement(ElementType.ORIGINAL_ONBOARDED_PACKAGE, Action.UPDATE); - originalPackageElement.getInfo() - .addProperty(InfoPropertyName.ORIGINAL_FILE_NAME.getVal(), candidateData.getOriginalFileName()); - originalPackageElement.getInfo() - .addProperty(InfoPropertyName.ORIGINAL_FILE_SUFFIX.getVal(), candidateData.getOriginalFileSuffix()); - originalPackageElement.setData(new ByteArrayInputStream(candidateData.getOriginalFileContentData().array())); - candidateElement.addSubElement(originalPackageElement); + @Override + public Optional getInfo(String vspId, Version version) { + logger.info("Getting orchestration template info for vsp id {}", vspId); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional candidateElement = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.OrchestrationTemplateCandidate.name()); + if (!candidateElement.isPresent() || candidateElement.get().getSubElements().isEmpty()) { + logger.info("Orchestration template info for vsp id {} does not exist", vspId); + return Optional.empty(); + } + OrchestrationTemplateCandidateData candidate = new OrchestrationTemplateCandidateData(); + candidateElement.get().getSubElements().stream() + .map(elementInfo -> zusammenAdaptor.getElement(context, elementContext, elementInfo.getId().toString())) + .forEach(element -> element.ifPresent(candidateInfoElement -> populateCandidate(candidate, candidateInfoElement, false))); + logger.info("Finished getting orchestration template info for vsp id {}", vspId); + return candidate.getFileSuffix() == null ? Optional.empty() : Optional.of(candidate); } - final ZusammenElement validationData = buildStructuralElement(ElementType - .OrchestrationTemplateCandidateValidationData, Action.UPDATE); - if (candidateData.getValidationData() != null) { - validationData - .setData(new ByteArrayInputStream(candidateData.getValidationData().getBytes())); - } - candidateElement.addSubElement(validationData); - candidateElement.addSubElement(candidateContentElement); - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, candidateElement, - "Update Orchestration Template Candidate"); - logger.info("Finished uploading candidate data entity for vsp id {}", vspId); - } - - @Override - public void updateValidationData(String vspId, Version version, - ValidationStructureList validationData) { - logger - .info("Updating validation data of orchestration template candidate for VSP id {} ", vspId); - - ZusammenElement validationDataElement = buildStructuralElement(ElementType - .OrchestrationTemplateCandidateValidationData, Action.UPDATE); - validationDataElement.setData(validationData == null ? new ByteArrayInputStream(EMPTY_DATA - .getBytes()) : new ByteArrayInputStream(JsonUtil.object2Json(validationData).getBytes())); - - ZusammenElement candidateElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.IGNORE); - candidateElement.addSubElement(validationDataElement); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, candidateElement, - "Update Orchestration Template Candidate validation data"); - logger - .info("Finished updating validation data of orchestration template candidate for VSP id {}", - vspId); - } - - @Override - public void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { - logger.info("Updating orchestration template for VSP id {}", vspId); - - ZusammenElement candidateElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); - candidateElement - .setData(new ByteArrayInputStream(JsonUtil.object2Json(fileDataStructure).getBytes())); - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - zusammenAdaptor.saveElement(context, elementContext, candidateElement, - "Update Orchestration Template Candidate structure"); - logger.info("Finished uploading candidate data entity for vsp id {}", vspId); - } - - - @Override - public Optional getStructure(String vspId, Version version) { - logger.info("Getting orchestration template candidate structure for vsp id {}", vspId); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); + private void populateCandidate(final OrchestrationTemplateCandidateData candidate, final Element candidateInfoElement, final boolean fullData) { + final String elementName = candidateInfoElement.getInfo().getName(); + if (ElementType.OrchestrationTemplateCandidateContent.name().equals(elementName)) { + if (fullData) { + candidate.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateInfoElement.getData()))); + } + candidate.setFileSuffix(candidateInfoElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); + candidate.setFileName(candidateInfoElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); + } else if (ElementType.OrchestrationTemplateCandidateValidationData.name().equals(elementName)) { + candidate.setValidationData(new String(FileUtils.toByteArray(candidateInfoElement.getData()))); + } else if (ElementType.ORIGINAL_ONBOARDED_PACKAGE.name().equals(elementName)) { + candidate.setOriginalFileName(candidateInfoElement.getInfo().getProperty(InfoPropertyName.ORIGINAL_FILE_NAME.getVal())); + candidate.setOriginalFileSuffix(candidateInfoElement.getInfo().getProperty(InfoPropertyName.ORIGINAL_FILE_SUFFIX.getVal())); + if (fullData) { + candidate.setOriginalFileContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateInfoElement.getData()))); + } + } + } - Optional element = zusammenAdaptor.getElementByName(context, elementContext, null, - ElementType.OrchestrationTemplateCandidate.name()); + @Override + public void delete(String vspId, Version version) { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); + ZusammenElement candidateContentElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); + candidateContentElement.setData(emptyData); + ZusammenElement validationData = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE); + validationData.setData(emptyData); + ZusammenElement candidateElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); + candidateElement.setData(emptyData); + candidateElement.addSubElement(candidateContentElement); + candidateElement.addSubElement(validationData); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Delete Orchestration Template Candidate Elements's content"); + } - if (element.isPresent() && !VspZusammenUtil.hasEmptyData(element.get().getData())) { - return Optional.of(new String(FileUtils.toByteArray(element.get().getData()))); + @Override + public void update(final String vspId, final Version version, final OrchestrationTemplateCandidateData candidateData) { + logger.info("Uploading candidate data entity for vsp id {}", vspId); + final ZusammenElement candidateElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); + candidateElement.setData(new ByteArrayInputStream(candidateData.getFilesDataStructure().getBytes())); + final ZusammenElement candidateContentElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); + candidateContentElement.setData(new ByteArrayInputStream(candidateData.getContentData().array())); + candidateContentElement.getInfo().addProperty(InfoPropertyName.FILE_SUFFIX.getVal(), candidateData.getFileSuffix()); + candidateContentElement.getInfo().addProperty(InfoPropertyName.FILE_NAME.getVal(), candidateData.getFileName()); + if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(candidateData.getFileSuffix())) { + final ZusammenElement originalPackageElement = buildStructuralElement(ElementType.ORIGINAL_ONBOARDED_PACKAGE, Action.UPDATE); + originalPackageElement.getInfo().addProperty(InfoPropertyName.ORIGINAL_FILE_NAME.getVal(), candidateData.getOriginalFileName()); + originalPackageElement.getInfo().addProperty(InfoPropertyName.ORIGINAL_FILE_SUFFIX.getVal(), candidateData.getOriginalFileSuffix()); + originalPackageElement.setData(new ByteArrayInputStream(candidateData.getOriginalFileContentData().array())); + candidateElement.addSubElement(originalPackageElement); + } + final ZusammenElement validationData = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE); + if (candidateData.getValidationData() != null) { + validationData.setData(new ByteArrayInputStream(candidateData.getValidationData().getBytes())); + } + candidateElement.addSubElement(validationData); + candidateElement.addSubElement(candidateContentElement); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Update Orchestration Template Candidate"); + logger.info("Finished uploading candidate data entity for vsp id {}", vspId); } - logger.info("Finished getting orchestration template candidate structure for vsp id {}", vspId); + @Override + public void updateValidationData(String vspId, Version version, ValidationStructureList validationData) { + logger.info("Updating validation data of orchestration template candidate for VSP id {} ", vspId); + ZusammenElement validationDataElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE); + validationDataElement.setData(validationData == null ? new ByteArrayInputStream(EMPTY_DATA.getBytes()) + : new ByteArrayInputStream(JsonUtil.object2Json(validationData).getBytes())); + ZusammenElement candidateElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.IGNORE); + candidateElement.addSubElement(validationDataElement); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Update Orchestration Template Candidate validation data"); + logger.info("Finished updating validation data of orchestration template candidate for VSP id {}", vspId); + } - return Optional.empty(); - } + @Override + public void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { + logger.info("Updating orchestration template for VSP id {}", vspId); + ZusammenElement candidateElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); + candidateElement.setData(new ByteArrayInputStream(JsonUtil.object2Json(fileDataStructure).getBytes())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Update Orchestration Template Candidate structure"); + logger.info("Finished uploading candidate data entity for vsp id {}", vspId); + } - public enum InfoPropertyName { - FILE_SUFFIX("fileSuffix"), - FILE_NAME("fileName"), - ORIGINAL_FILE_NAME("originalFilename"), - ORIGINAL_FILE_SUFFIX("originalFileSuffix"); + @Override + public Optional getStructure(String vspId, Version version) { + logger.info("Getting orchestration template candidate structure for vsp id {}", vspId); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional element = zusammenAdaptor + .getElementByName(context, elementContext, null, ElementType.OrchestrationTemplateCandidate.name()); + if (element.isPresent() && !VspZusammenUtil.hasEmptyData(element.get().getData())) { + return Optional.of(new String(FileUtils.toByteArray(element.get().getData()))); + } + logger.info("Finished getting orchestration template candidate structure for vsp id {}", vspId); + return Optional.empty(); + } - private final String val; + public enum InfoPropertyName { + FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName"), ORIGINAL_FILE_NAME("originalFilename"), ORIGINAL_FILE_SUFFIX("originalFileSuffix"); + private final String val; - InfoPropertyName(String val) { - this.val = val; - } + InfoPropertyName(String val) { + this.val = val; + } - private String getVal() { - return val; + private String getVal() { + return val; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java index bc186e7629..dd78a94eb5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -23,6 +25,10 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.utils.fileutils.FileUtils; +import java.io.ByteArrayInputStream; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.Optional; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; @@ -31,205 +37,142 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.ByteArrayInputStream; -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.Optional; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; -import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; - public class OrchestrationTemplateDaoZusammenImpl implements OrchestrationTemplateDao { - private static final Logger LOGGER = LoggerFactory.getLogger( - OrchestrationTemplateDaoZusammenImpl.class); - private ZusammenAdaptor zusammenAdaptor; - - public OrchestrationTemplateDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for OrchestrationTemplateDaoZusammenImpl - } - - @Override - public OrchestrationTemplateEntity getInfo(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional vspModel = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return null; - } - - Optional elementInfo = zusammenAdaptor - .getElementInfoByName(context, elementContext, vspModel.get().getId(), - ElementType.OrchestrationTemplate.name()); - if (!elementInfo.isPresent()) { - return null; - } - - Optional element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - ElementType.OrchestrationTemplateValidationData.name()); + private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateDaoZusammenImpl.class); + private ZusammenAdaptor zusammenAdaptor; - OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); - if (!element.isPresent()) { - return orchestrationTemplate; + public OrchestrationTemplateDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - orchestrationTemplate - .setFileSuffix(element.get().getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); - orchestrationTemplate - .setFileName(element.get().getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); - if (!VspZusammenUtil.hasEmptyData(element.get().getData())) { - orchestrationTemplate - .setValidationData(new String(FileUtils.toByteArray(element.get().getData()))); - } - return orchestrationTemplate; - } - - @Override - public OrchestrationTemplateEntity get(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); - Optional vspModel = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return orchestrationTemplate; + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for OrchestrationTemplateDaoZusammenImpl } - Optional orchestrationTemplateElementOpt = zusammenAdaptor - .getElementByName(context, elementContext, vspModel.get().getId(), - ElementType.OrchestrationTemplate.name()); - - if (! orchestrationTemplateElementOpt.isPresent()) { - return orchestrationTemplate; - } else { - Element orchestrationTemplateElement = orchestrationTemplateElementOpt.get(); - - if (VspZusammenUtil.hasEmptyData(orchestrationTemplateElement.getData())) { - return orchestrationTemplate; - } - - orchestrationTemplate.setContentData( - ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData()))); - - Collection subElements = orchestrationTemplateElement.getSubElements(); - if (subElements.isEmpty()) { + @Override + public OrchestrationTemplateEntity getInfo(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return null; + } + Optional elementInfo = zusammenAdaptor + .getElementInfoByName(context, elementContext, vspModel.get().getId(), ElementType.OrchestrationTemplate.name()); + if (!elementInfo.isPresent()) { + return null; + } + Optional element = zusammenAdaptor + .getElementByName(context, elementContext, elementInfo.get().getId(), ElementType.OrchestrationTemplateValidationData.name()); + OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); + if (!element.isPresent()) { + return orchestrationTemplate; + } + orchestrationTemplate.setFileSuffix(element.get().getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); + orchestrationTemplate.setFileName(element.get().getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); + if (!VspZusammenUtil.hasEmptyData(element.get().getData())) { + orchestrationTemplate.setValidationData(new String(FileUtils.toByteArray(element.get().getData()))); + } return orchestrationTemplate; - } - - for (Element element : subElements) { - Optional subElementOpt = zusammenAdaptor.getElement(context, - elementContext, element.getElementId().toString()); - - subElementOpt.ifPresent(subElement -> { - if (subElement.getInfo().getName().equals(ElementType - .OrchestrationTemplateValidationData.name())) { - - orchestrationTemplate.setFileSuffix(subElement.getInfo() - .getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); - orchestrationTemplate.setFileName(subElement.getInfo() - .getProperty(InfoPropertyName.FILE_NAME.getVal())); + } - if (!VspZusammenUtil.hasEmptyData(subElement.getData())) { - orchestrationTemplate.setValidationData( - new String(FileUtils.toByteArray(subElement.getData()))); + @Override + public OrchestrationTemplateEntity get(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return orchestrationTemplate; + } + Optional orchestrationTemplateElementOpt = zusammenAdaptor + .getElementByName(context, elementContext, vspModel.get().getId(), ElementType.OrchestrationTemplate.name()); + if (!orchestrationTemplateElementOpt.isPresent()) { + return orchestrationTemplate; + } else { + Element orchestrationTemplateElement = orchestrationTemplateElementOpt.get(); + if (VspZusammenUtil.hasEmptyData(orchestrationTemplateElement.getData())) { + return orchestrationTemplate; } - } else if (subElement.getInfo().getName().equals(ElementType - .OrchestrationTemplateStructure.name())) { - orchestrationTemplate.setFilesDataStructure(new String(FileUtils.toByteArray(subElement - .getData()))); - } - }); - } + orchestrationTemplate.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData()))); + Collection subElements = orchestrationTemplateElement.getSubElements(); + if (subElements.isEmpty()) { + return orchestrationTemplate; + } + for (Element element : subElements) { + Optional subElementOpt = zusammenAdaptor.getElement(context, elementContext, element.getElementId().toString()); + subElementOpt.ifPresent(subElement -> { + if (subElement.getInfo().getName().equals(ElementType.OrchestrationTemplateValidationData.name())) { + orchestrationTemplate.setFileSuffix(subElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); + orchestrationTemplate.setFileName(subElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); + if (!VspZusammenUtil.hasEmptyData(subElement.getData())) { + orchestrationTemplate.setValidationData(new String(FileUtils.toByteArray(subElement.getData()))); + } + } else if (subElement.getInfo().getName().equals(ElementType.OrchestrationTemplateStructure.name())) { + orchestrationTemplate.setFilesDataStructure(new String(FileUtils.toByteArray(subElement.getData()))); + } + }); + } + } + return orchestrationTemplate; } - return orchestrationTemplate; - } - - @Override - public void update(String vspId, Version version, - OrchestrationTemplateEntity orchestrationTemplate) { - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - ZusammenElement validationData = - buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.UPDATE); - validationData - .setData(new ByteArrayInputStream(orchestrationTemplate.getValidationData().getBytes())); - validationData.getInfo() - .addProperty(InfoPropertyName.FILE_SUFFIX.getVal(), orchestrationTemplate.getFileSuffix()); - validationData.getInfo() - .addProperty(InfoPropertyName.FILE_NAME.getVal(), orchestrationTemplate.getFileName()); - ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType - .OrchestrationTemplateStructure, Action.UPDATE); - orchestrationTemplateStructure - .setData(new ByteArrayInputStream(orchestrationTemplate.getFilesDataStructure() - .getBytes())); - ZusammenElement orchestrationTemplateElement = - buildStructuralElement(ElementType.OrchestrationTemplate, Action.UPDATE); - orchestrationTemplateElement - .setData(new ByteArrayInputStream(orchestrationTemplate.getContentData().array())); - orchestrationTemplateElement.addSubElement(validationData); - orchestrationTemplateElement.addSubElement(orchestrationTemplateStructure); - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); - vspModel.addSubElement(orchestrationTemplateElement); - - zusammenAdaptor.saveElement(context, elementContext, vspModel, "Update Orchestration Template"); - } - @Override - public Optional getOrchestrationTemplateStructure(String vspId, Version version) { - LOGGER.info("Getting orchestration template structure for VendorSoftwareProduct id" + - " " + "-> " + vspId); - - SessionContext context = createSessionContext(); - ElementContext elementContext = new ElementContext(vspId, version.getId()); - - Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, - null, ElementType.VspModel.name()); - if (!vspModel.isPresent()) { - return Optional.empty(); - } - Optional orchestrationTemplateElement = zusammenAdaptor.getElementByName(context, - elementContext, vspModel.get().getId(), ElementType.OrchestrationTemplate.name()); - if (!orchestrationTemplateElement.isPresent()) { - return Optional.empty(); + @Override + public void update(String vspId, Version version, OrchestrationTemplateEntity orchestrationTemplate) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + ZusammenElement validationData = buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.UPDATE); + validationData.setData(new ByteArrayInputStream(orchestrationTemplate.getValidationData().getBytes())); + validationData.getInfo().addProperty(InfoPropertyName.FILE_SUFFIX.getVal(), orchestrationTemplate.getFileSuffix()); + validationData.getInfo().addProperty(InfoPropertyName.FILE_NAME.getVal(), orchestrationTemplate.getFileName()); + ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE); + orchestrationTemplateStructure.setData(new ByteArrayInputStream(orchestrationTemplate.getFilesDataStructure().getBytes())); + ZusammenElement orchestrationTemplateElement = buildStructuralElement(ElementType.OrchestrationTemplate, Action.UPDATE); + orchestrationTemplateElement.setData(new ByteArrayInputStream(orchestrationTemplate.getContentData().array())); + orchestrationTemplateElement.addSubElement(validationData); + orchestrationTemplateElement.addSubElement(orchestrationTemplateStructure); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(orchestrationTemplateElement); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Update Orchestration Template"); } - Optional orchestrationTemplateStructureElement = zusammenAdaptor - .getElementByName(context, elementContext, - orchestrationTemplateElement.get().getElementId(), - ElementType.OrchestrationTemplateStructure.name()); - if (orchestrationTemplateStructureElement.isPresent() && - !VspZusammenUtil.hasEmptyData(orchestrationTemplateStructureElement.get().getData())) { - return Optional.of(new String( - FileUtils.toByteArray(orchestrationTemplateStructureElement.get().getData()))); + @Override + public Optional getOrchestrationTemplateStructure(String vspId, Version version) { + LOGGER.info("Getting orchestration template structure for VendorSoftwareProduct id" + " " + "-> " + vspId); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional vspModel = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return Optional.empty(); + } + Optional orchestrationTemplateElement = zusammenAdaptor + .getElementByName(context, elementContext, vspModel.get().getId(), ElementType.OrchestrationTemplate.name()); + if (!orchestrationTemplateElement.isPresent()) { + return Optional.empty(); + } + Optional orchestrationTemplateStructureElement = zusammenAdaptor + .getElementByName(context, elementContext, orchestrationTemplateElement.get().getElementId(), + ElementType.OrchestrationTemplateStructure.name()); + if (orchestrationTemplateStructureElement.isPresent() && !VspZusammenUtil + .hasEmptyData(orchestrationTemplateStructureElement.get().getData())) { + return Optional.of(new String(FileUtils.toByteArray(orchestrationTemplateStructureElement.get().getData()))); + } + LOGGER.info("Finished getting orchestration template structure for VendorSoftwareProduct " + "id -> " + vspId); + return Optional.empty(); } - LOGGER.info("Finished getting orchestration template structure for VendorSoftwareProduct " + - "id -> " + vspId); - return Optional.empty(); - } + private enum InfoPropertyName { + FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName"); + private String val; - private enum InfoPropertyName { - FILE_SUFFIX("fileSuffix"), - FILE_NAME("fileName"); - - private String val; - - InfoPropertyName(String val){ - this.val=val; - } + InfoPropertyName(String val) { + this.val = val; + } - public String getVal() { - return val; + public String getVal() { + return val; + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java index 76e14d8606..28bf1d8ddb 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.DESCRIPTION; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.PROCESS_TYPE; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; @@ -28,6 +35,12 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; @@ -36,238 +49,176 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.types.ElementPropertyName; -import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; -import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.*; - /** * @author Avrahamg. * @since March 23, 2017 */ public class ProcessDaoZusammenImpl implements ProcessDao { - private ZusammenAdaptor zusammenAdaptor; - - public ProcessDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - // registerVersioning not implemented for ProcessDaoZusammenImpl - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public void create(ProcessEntity processEntity) { - ZusammenElement processElement = buildProcessElement(processEntity, Action.CREATE); - - ZusammenElement processesElement = - buildStructuralElement(ElementType.Processes, Action.IGNORE); - ZusammenElement aggregatedElement = VspZusammenUtil.aggregateElements(processesElement, - processElement); - ZusammenElement componentElement; - if (processEntity.getComponentId() != null) { - componentElement = buildElement(new Id(processEntity.getComponentId()), Action.IGNORE); - aggregatedElement = - VspZusammenUtil.aggregateElements(componentElement, aggregatedElement); + public ProcessDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; } - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - - Element savedElement = - zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Create process"); - processEntity - .setId(processEntity.getComponentId() == null - ? savedElement.getSubElements().iterator().next().getElementId().getValue() - : savedElement.getSubElements().iterator().next().getSubElements() - .iterator().next().getElementId().getValue()); - } - - @Override - public ProcessEntity get(ProcessEntity processEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - - return zusammenAdaptor.getElementInfo(context, elementContext, new Id(processEntity.getId())) - .map(elementInfo -> convertToProcessEntity(elementInfo, new ElementToProcessConvertor(), - processEntity)) - .orElse(null); - } - - @Override - public void update(ProcessEntity processEntity) { - ProcessEntity retrieved = getArtifact(processEntity); - if (retrieved != null && retrieved.getArtifact() != null) { - processEntity.setArtifactName(retrieved.getArtifactName()); - processEntity.setArtifact(retrieved.getArtifact()); + @Override + public void registerVersioning(String versionableEntityType) { + // registerVersioning not implemented for ProcessDaoZusammenImpl } - update(processEntity, "Update process"); - } - - @Override - public void delete(ProcessEntity processEntity) { - ZusammenElement processElement = buildElement(new Id(processEntity.getId()), Action.DELETE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - - zusammenAdaptor.saveElement(context, elementContext, processElement, - String.format("Delete process with id %s", processEntity.getId())); - } - - @Override - public void deleteAll(ProcessEntity processEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, new Id(processEntity.getComponentId()), ElementType.Processes.name()); - - if (optionalElement.isPresent()) { - Element processesElement = optionalElement.get(); - Collection processes = processesElement.getSubElements(); - - processes.forEach(process -> { - ZusammenElement processZusammenElement = - buildElement(process.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, - "Delete Process with id " + process.getElementId()); - }); + @Override + public void create(ProcessEntity processEntity) { + ZusammenElement processElement = buildProcessElement(processEntity, Action.CREATE); + ZusammenElement processesElement = buildStructuralElement(ElementType.Processes, Action.IGNORE); + ZusammenElement aggregatedElement = VspZusammenUtil.aggregateElements(processesElement, processElement); + ZusammenElement componentElement; + if (processEntity.getComponentId() != null) { + componentElement = buildElement(new Id(processEntity.getComponentId()), Action.IGNORE); + aggregatedElement = VspZusammenUtil.aggregateElements(componentElement, aggregatedElement); + } + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Create process"); + processEntity.setId(processEntity.getComponentId() == null ? savedElement.getSubElements().iterator().next().getElementId().getValue() + : savedElement.getSubElements().iterator().next().getSubElements().iterator().next().getElementId().getValue()); } - } - - @Override - public void deleteVspAll(String vspId, Version version) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(vspId, version.getId()); - - Optional optionalElement = zusammenAdaptor.getElementByName(context, - elementContext, null, ElementType.Processes.name()); - if (optionalElement.isPresent()) { - Element processesElement = optionalElement.get(); - Collection processes = processesElement.getSubElements(); - - processes.forEach(process -> { - ZusammenElement processZusammenElement = - buildElement(process.getElementId(), Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, - "Delete Process with id " + process.getElementId()); - }); + @Override + public ProcessEntity get(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(processEntity.getId())) + .map(elementInfo -> convertToProcessEntity(elementInfo, new ElementToProcessConvertor(), processEntity)).orElse(null); } - } - - @Override - public ProcessEntity getArtifact(ProcessEntity processEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - - return zusammenAdaptor.getElement(context, elementContext, processEntity.getId()) - .map(element -> { - ProcessEntity process = new ElementToProcessConvertor().convert(element); - process.setVspId(processEntity.getVspId()); - process.setVersion(processEntity.getVersion()); - process.setComponentId(processEntity.getComponentId()); - return process; - }) - .orElse(null); - } - @Override - public void uploadArtifact(ProcessEntity processEntity) { - ProcessEntity retrieved = get(processEntity); - if (retrieved != null) { - retrieved.setArtifactName(processEntity.getArtifactName()); - retrieved.setArtifact(processEntity.getArtifact()); - - update(retrieved, "Upload process artifact"); + @Override + public void update(ProcessEntity processEntity) { + ProcessEntity retrieved = getArtifact(processEntity); + if (retrieved != null && retrieved.getArtifact() != null) { + processEntity.setArtifactName(retrieved.getArtifactName()); + processEntity.setArtifact(retrieved.getArtifact()); + } + update(processEntity, "Update process"); } - } - - @Override - public void deleteArtifact(ProcessEntity processEntity) { - ProcessEntity retrieved = get(processEntity); - if (retrieved != null) { - retrieved.setArtifactName(null); - retrieved.setArtifact(null); - update(retrieved, "Delete process artifact"); + @Override + public void delete(ProcessEntity processEntity) { + ZusammenElement processElement = buildElement(new Id(processEntity.getId()), Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, processElement, String.format("Delete process with id %s", processEntity.getId())); } - } - - @Override - public Collection list(ProcessEntity processEntity) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - Optional processesOptional = - zusammenAdaptor.getElementInfoByName(context, elementContext, - extractParentElementId(processEntity), ElementType.Processes.name()); - if (!processesOptional.isPresent()) { - return new ArrayList<>(); + @Override + public void deleteAll(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + Optional optionalElement = zusammenAdaptor + .getElementByName(context, elementContext, new Id(processEntity.getComponentId()), ElementType.Processes.name()); + if (optionalElement.isPresent()) { + Element processesElement = optionalElement.get(); + Collection processes = processesElement.getSubElements(); + processes.forEach(process -> { + ZusammenElement processZusammenElement = buildElement(process.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, "Delete Process with id " + process.getElementId()); + }); + } } - ElementToProcessConvertor convertor = new ElementToProcessConvertor(); - return zusammenAdaptor.listElements(context, elementContext, processesOptional.get().getId()) - .stream() - .map(elementInfo -> convertToProcessEntity(elementInfo, convertor, processEntity)) - .collect(Collectors.toList()); - } - private ProcessEntity convertToProcessEntity(ElementInfo elementInfo, - ElementToProcessConvertor convertor, - ProcessEntity inputProcess) { - ProcessEntity process = convertor.convert(elementInfo); - process.setVspId(inputProcess.getVspId()); - process.setVersion(inputProcess.getVersion()); - process.setComponentId(inputProcess.getComponentId()); - return process; - } + @Override + public void deleteVspAll(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + Optional optionalElement = zusammenAdaptor.getElementByName(context, elementContext, null, ElementType.Processes.name()); + if (optionalElement.isPresent()) { + Element processesElement = optionalElement.get(); + Collection processes = processesElement.getSubElements(); + processes.forEach(process -> { + ZusammenElement processZusammenElement = buildElement(process.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, "Delete Process with id " + process.getElementId()); + }); + } + } - private void update(ProcessEntity processEntity, String message) { - ZusammenElement processElement = buildProcessElement(processEntity, Action.UPDATE); + @Override + public ProcessEntity getArtifact(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + return zusammenAdaptor.getElement(context, elementContext, processEntity.getId()).map(element -> { + ProcessEntity process = new ElementToProcessConvertor().convert(element); + process.setVspId(processEntity.getVspId()); + process.setVersion(processEntity.getVersion()); + process.setComponentId(processEntity.getComponentId()); + return process; + }).orElse(null); + } - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + @Override + public void uploadArtifact(ProcessEntity processEntity) { + ProcessEntity retrieved = get(processEntity); + if (retrieved != null) { + retrieved.setArtifactName(processEntity.getArtifactName()); + retrieved.setArtifact(processEntity.getArtifact()); + update(retrieved, "Upload process artifact"); + } + } - zusammenAdaptor.saveElement(context, elementContext, processElement, message); - } + @Override + public void deleteArtifact(ProcessEntity processEntity) { + ProcessEntity retrieved = get(processEntity); + if (retrieved != null) { + retrieved.setArtifactName(null); + retrieved.setArtifact(null); + update(retrieved, "Delete process artifact"); + } + } - private Id extractParentElementId(ProcessEntity processEntity) { - return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); - } + @Override + public Collection list(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + Optional processesOptional = zusammenAdaptor + .getElementInfoByName(context, elementContext, extractParentElementId(processEntity), ElementType.Processes.name()); + if (!processesOptional.isPresent()) { + return new ArrayList<>(); + } + ElementToProcessConvertor convertor = new ElementToProcessConvertor(); + return zusammenAdaptor.listElements(context, elementContext, processesOptional.get().getId()).stream() + .map(elementInfo -> convertToProcessEntity(elementInfo, convertor, processEntity)).collect(Collectors.toList()); + } - private ZusammenElement buildProcessElement(ProcessEntity process, Action action) { + private ProcessEntity convertToProcessEntity(ElementInfo elementInfo, ElementToProcessConvertor convertor, ProcessEntity inputProcess) { + ProcessEntity process = convertor.convert(elementInfo); + process.setVspId(inputProcess.getVspId()); + process.setVersion(inputProcess.getVersion()); + process.setComponentId(inputProcess.getComponentId()); + return process; + } - Info info = new Info(); - info.setName(process.getName()); - info.addProperty(NAME, process.getName()); - info.addProperty(ElementPropertyName.elementType.name(), ElementType.Process); - info.addProperty(ARTIFACT_NAME, process.getArtifactName()); - info.addProperty(DESCRIPTION, process.getDescription()); - info.addProperty(PROCESS_TYPE, process.getType() != null ? process.getType().name() : null); + private void update(ProcessEntity processEntity, String message) { + ZusammenElement processElement = buildProcessElement(processEntity, Action.UPDATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, processElement, message); + } - ZusammenElement processElement = buildElement(new Id(process.getId()), action); - processElement.setInfo(info); - if (Objects.nonNull(process.getArtifact())) { - processElement.setData(new ByteArrayInputStream(process.getArtifact().array())); + private Id extractParentElementId(ProcessEntity processEntity) { + return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); } - return processElement; - } + private ZusammenElement buildProcessElement(ProcessEntity process, Action action) { + Info info = new Info(); + info.setName(process.getName()); + info.addProperty(NAME, process.getName()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Process); + info.addProperty(ARTIFACT_NAME, process.getArtifactName()); + info.addProperty(DESCRIPTION, process.getDescription()); + info.addProperty(PROCESS_TYPE, process.getType() != null ? process.getType().name() : null); + ZusammenElement processElement = buildElement(new Id(process.getId()), action); + processElement.setInfo(info); + if (Objects.nonNull(process.getArtifact())) { + processElement.setData(new ByteArrayInputStream(process.getArtifact().array())); + } + return processElement; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java index de42344788..9655434e74 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java @@ -15,11 +15,17 @@ */ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import java.io.ByteArrayInputStream; +import java.util.Collection; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; @@ -33,256 +39,197 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; -import java.io.ByteArrayInputStream; -import java.util.Collection; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; -import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; - public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareProductInfoDao { - private static final String EMPTY_DATA = "{}"; - - private ZusammenAdaptor zusammenAdaptor; - - public VendorSoftwareProductInfoDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public void registerVersioning(String versionableEntityType) { - VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorSoftwareProduct", - null, null); - - ActionVersioningManagerFactory.getInstance().createInterface() - .register(versionableEntityType, metadata); - } - - @Override - public Collection list(VspDetails entity) { - return zusammenAdaptor.listItems(createSessionContext()).stream() - .filter(item -> "VendorSoftwareProduct".equals(item.getInfo().getProperty("item_type"))) - .map(new ElementToVSPGeneralConvertor()::convert) - .collect(Collectors.toList()); - } - - @Override - public void create(VspDetails vspDetails) { - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); - - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); - zusammenAdaptor.saveElement(context, elementContext, generalElement, - "Create VSP General Info Element"); - - createVspStructure(context, elementContext); - } - - private void createVspStructure(SessionContext context, ElementContext elementContext) { - createOrchestrationTemplateCandidateStructure(context, elementContext); - createVspModelStructure(context, elementContext); - - zusammenAdaptor.saveElement(context, elementContext, - buildStructuralElement(ElementType.DeploymentFlavors, Action.CREATE), - "Create VSP Deployment Flavors Element"); - - zusammenAdaptor.saveElement(context, elementContext, - buildStructuralElement(ElementType.Processes, Action.CREATE), - "Create VSP Processes Element"); - } - - private void createOrchestrationTemplateCandidateStructure(SessionContext context, - ElementContext elementContext) { - ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); - ZusammenElement candidateContentElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.CREATE); - candidateContentElement.setData(emptyData); - ZusammenElement validationData = buildStructuralElement(ElementType - .OrchestrationTemplateCandidateValidationData, Action.CREATE); - ZusammenElement candidateElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.CREATE); - candidateElement.setData(emptyData); - candidateElement.addSubElement(candidateContentElement); - candidateElement.addSubElement(validationData); - zusammenAdaptor.saveElement(context, elementContext, candidateElement, - "Create Orchestration Template Candidate Elements"); - } + private static final String EMPTY_DATA = "{}"; + private ZusammenAdaptor zusammenAdaptor; - private void createVspModelStructure(SessionContext context, ElementContext elementContext) { - ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.CREATE); - vspModel.addSubElement(buildOrchestrationTemplateStructure()); - vspModel.addSubElement(buildStructuralElement(ElementType.Networks, Action.CREATE)); - vspModel.addSubElement(buildStructuralElement(ElementType.Components, Action.CREATE)); - vspModel - .addSubElement(buildStructuralElement(ElementType.ComponentDependencies, Action.CREATE)); - - ZusammenElement templates = buildStructuralElement(ElementType.Templates, Action.CREATE); - ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.CREATE); - vspModel.addSubElement( - buildServiceModelStructure(ElementType.ServiceModel, templates, artifacts)); - vspModel.addSubElement( - buildServiceModelStructure(ElementType.EnrichedServiceModel, templates, artifacts)); - - zusammenAdaptor.saveElement(context, elementContext, vspModel, "Create VSP Model Elements"); - } - - private ZusammenElement buildOrchestrationTemplateStructure() { - ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); - - ZusammenElement validationData = - buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.CREATE); - validationData.setData(emptyData); - - ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType - .OrchestrationTemplateStructure, Action.CREATE); - validationData.setData(emptyData); - - ZusammenElement orchestrationTemplate = - buildStructuralElement(ElementType.OrchestrationTemplate, Action.CREATE); - orchestrationTemplate.setData(emptyData); - orchestrationTemplate.addSubElement(validationData); - orchestrationTemplate.addSubElement(orchestrationTemplateStructure); - - return orchestrationTemplate; - } - - private ZusammenElement buildServiceModelStructure(ElementType serviceModelElementType, - ZusammenElement templates, - ZusammenElement artifacts) { - ZusammenElement serviceModel = buildStructuralElement(serviceModelElementType, Action.CREATE); - serviceModel.addSubElement(templates); - serviceModel.addSubElement(artifacts); - return serviceModel; - } + public VendorSoftwareProductInfoDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - @Override - public void update(VspDetails vspDetails) { - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.UPDATE); + @Override + public void registerVersioning(String versionableEntityType) { + VersionableEntityMetadata metadata = new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorSoftwareProduct", null, null); + ActionVersioningManagerFactory.getInstance().createInterface().register(versionableEntityType, metadata); + } - SessionContext context = createSessionContext(); - zusammenAdaptor.saveElement(context, - new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()), generalElement, - "Update VSP General Info Element"); - } + @Override + public Collection list(VspDetails entity) { + return zusammenAdaptor.listItems(createSessionContext()).stream() + .filter(item -> "VendorSoftwareProduct".equals(item.getInfo().getProperty("item_type"))).map(new ElementToVSPGeneralConvertor()::convert) + .collect(Collectors.toList()); + } - @Override - public VspDetails get(VspDetails vspDetails) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); - return zusammenAdaptor.getElementInfoByName(context, elementContext, null, - ElementType.VendorSoftwareProduct.name()) - .map(new ElementToVSPGeneralConvertor()::convert) - .map(vsp -> { - vsp.setId(vspDetails.getId()); - vsp.setVersion(vspDetails.getVersion()); - return vsp; - }) - .orElse(null); - } + @Override + public void create(VspDetails vspDetails) { + ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, generalElement, "Create VSP General Info Element"); + createVspStructure(context, elementContext); + } - @Override - public void delete(VspDetails vspDetails) { - SessionContext context = createSessionContext(); - ElementContext elementContext = - new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + private void createVspStructure(SessionContext context, ElementContext elementContext) { + createOrchestrationTemplateCandidateStructure(context, elementContext); + createVspModelStructure(context, elementContext); + zusammenAdaptor.saveElement(context, elementContext, buildStructuralElement(ElementType.DeploymentFlavors, Action.CREATE), + "Create VSP Deployment Flavors Element"); + zusammenAdaptor + .saveElement(context, elementContext, buildStructuralElement(ElementType.Processes, Action.CREATE), "Create VSP Processes Element"); + } - zusammenAdaptor.saveElement(context, elementContext, - buildStructuralElement(ElementType.VspModel, Action.DELETE), - "Delete VSP Model Elements"); + private void createOrchestrationTemplateCandidateStructure(SessionContext context, ElementContext elementContext) { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); + ZusammenElement candidateContentElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.CREATE); + candidateContentElement.setData(emptyData); + ZusammenElement validationData = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.CREATE); + ZusammenElement candidateElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.CREATE); + candidateElement.setData(emptyData); + candidateElement.addSubElement(candidateContentElement); + candidateElement.addSubElement(validationData); + zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Create Orchestration Template Candidate Elements"); + } - createVspModelStructure(context, elementContext); - } + private void createVspModelStructure(SessionContext context, ElementContext elementContext) { + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.CREATE); + vspModel.addSubElement(buildOrchestrationTemplateStructure()); + vspModel.addSubElement(buildStructuralElement(ElementType.Networks, Action.CREATE)); + vspModel.addSubElement(buildStructuralElement(ElementType.Components, Action.CREATE)); + vspModel.addSubElement(buildStructuralElement(ElementType.ComponentDependencies, Action.CREATE)); + ZusammenElement templates = buildStructuralElement(ElementType.Templates, Action.CREATE); + ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.CREATE); + vspModel.addSubElement(buildServiceModelStructure(ElementType.ServiceModel, templates, artifacts)); + vspModel.addSubElement(buildServiceModelStructure(ElementType.EnrichedServiceModel, templates, artifacts)); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Create VSP Model Elements"); + } - @Override - public void updateQuestionnaireData(String vspId, Version version, String questionnaireData) { - SessionContext context = createSessionContext(); + private ZusammenElement buildOrchestrationTemplateStructure() { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); + ZusammenElement validationData = buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.CREATE); + validationData.setData(emptyData); + ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.CREATE); + validationData.setData(emptyData); + ZusammenElement orchestrationTemplate = buildStructuralElement(ElementType.OrchestrationTemplate, Action.CREATE); + orchestrationTemplate.setData(emptyData); + orchestrationTemplate.addSubElement(validationData); + orchestrationTemplate.addSubElement(orchestrationTemplateStructure); + return orchestrationTemplate; + } - ZusammenElement questionnaireElement = mapQuestionnaireToZusammenElement(questionnaireData); - zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), - questionnaireElement, "Update VSP Questionnaire"); - } + private ZusammenElement buildServiceModelStructure(ElementType serviceModelElementType, ZusammenElement templates, ZusammenElement artifacts) { + ZusammenElement serviceModel = buildStructuralElement(serviceModelElementType, Action.CREATE); + serviceModel.addSubElement(templates); + serviceModel.addSubElement(artifacts); + return serviceModel; + } - @Override - public VspQuestionnaireEntity getQuestionnaire(String vspId, Version version) { - SessionContext context = createSessionContext(); - VspQuestionnaireEntity entity = new ElementToVSPQuestionnaireConvertor().convert(zusammenAdaptor - .getElementByName(context, new ElementContext(vspId, version.getId()), null, - ElementType.VSPQuestionnaire.name()) - .orElse(null)); - entity.setId(vspId); - entity.setVersion(version); - return entity; - } + @Override + public void update(VspDetails vspDetails) { + ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()), generalElement, + "Update VSP General Info Element"); + } - @Override - public boolean isManual(String vspId, Version version) { - final VspDetails vspDetails = get(new VspDetails(vspId, version)); - return vspDetails != null && - OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod()); - } + @Override + public VspDetails get(VspDetails vspDetails) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + return zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VendorSoftwareProduct.name()) + .map(new ElementToVSPGeneralConvertor()::convert).map(vsp -> { + vsp.setId(vspDetails.getId()); + vsp.setVersion(vspDetails.getVersion()); + return vsp; + }).orElse(null); + } - private ZusammenElement mapVspDetailsToZusammenElement(VspDetails vspDetails, Action action) { - ZusammenElement generalElement = - buildStructuralElement(ElementType.VendorSoftwareProduct, action); - addVspDetailsToInfo(generalElement.getInfo(), vspDetails); - return generalElement; - } + @Override + public void delete(VspDetails vspDetails) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + zusammenAdaptor + .saveElement(context, elementContext, buildStructuralElement(ElementType.VspModel, Action.DELETE), "Delete VSP Model Elements"); + createVspModelStructure(context, elementContext); + } - private ZusammenElement mapQuestionnaireToZusammenElement(String questionnaireData) { - ZusammenElement questionnaireElement = - buildStructuralElement(ElementType.VSPQuestionnaire, Action.UPDATE); - questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); - return questionnaireElement; - } + @Override + public void updateQuestionnaireData(String vspId, Version version, String questionnaireData) { + SessionContext context = createSessionContext(); + ZusammenElement questionnaireElement = mapQuestionnaireToZusammenElement(questionnaireData); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), questionnaireElement, "Update VSP Questionnaire"); + } - private void addVspDetailsToInfo(Info info, VspDetails vspDetails) { - info.addProperty(InfoPropertyName.NAME.getValue(), vspDetails.getName()); - info.addProperty(InfoPropertyName.DESCRIPTION.getValue(), vspDetails.getDescription()); - info.addProperty(InfoPropertyName.ICON.getValue(), vspDetails.getIcon()); - info.addProperty(InfoPropertyName.CATEGORY.getValue(), vspDetails.getCategory()); - info.addProperty(InfoPropertyName.SUB_CATEGORY.getValue(), vspDetails.getSubCategory()); - info.addProperty(InfoPropertyName.VENDOR_ID.getValue(), vspDetails.getVendorId()); - info.addProperty(InfoPropertyName.VENDOR_NAME.getValue(), vspDetails.getVendorName()); - if (vspDetails.getVlmVersion() != null) { - info.addProperty(InfoPropertyName.VENDOR_VERSION.getValue(), - vspDetails.getVlmVersion().getId()); + @Override + public VspQuestionnaireEntity getQuestionnaire(String vspId, Version version) { + SessionContext context = createSessionContext(); + VspQuestionnaireEntity entity = new ElementToVSPQuestionnaireConvertor().convert( + zusammenAdaptor.getElementByName(context, new ElementContext(vspId, version.getId()), null, ElementType.VSPQuestionnaire.name()) + .orElse(null)); + entity.setId(vspId); + entity.setVersion(version); + return entity; } - info.addProperty(InfoPropertyName.LICENSE_TYPE.getValue(), - vspDetails.getLicenseType()); - info.addProperty(InfoPropertyName.LICENSE_AGREEMENT.getValue(), - vspDetails.getLicenseAgreement()); - info.addProperty(InfoPropertyName.FEATURE_GROUPS.getValue(), vspDetails.getFeatureGroups()); - info.addProperty(InfoPropertyName.ON_BOARDING_METHOD.getValue(), - vspDetails.getOnboardingMethod()); - } - public enum InfoPropertyName { - NAME("name"), - DESCRIPTION("description"), - ICON("icon"), - CATEGORY("category"), - SUB_CATEGORY("subCategory"), - VENDOR_ID("vendorId"), - VENDOR_NAME("vendorName"), - VENDOR_VERSION("vendorVersion"), - LICENSE_TYPE("licenseType"), - LICENSE_AGREEMENT("licenseAgreement"), - FEATURE_GROUPS("featureGroups"), - ON_BOARDING_METHOD("onboardingMethod"); + @Override + public boolean isManual(String vspId, Version version) { + final VspDetails vspDetails = get(new VspDetails(vspId, version)); + return vspDetails != null && OnboardingMethod.Manual.name().equals(vspDetails.getOnboardingMethod()); + } - private String value; + private ZusammenElement mapVspDetailsToZusammenElement(VspDetails vspDetails, Action action) { + ZusammenElement generalElement = buildStructuralElement(ElementType.VendorSoftwareProduct, action); + addVspDetailsToInfo(generalElement.getInfo(), vspDetails); + return generalElement; + } - InfoPropertyName(String value) { - this.value = value; + private ZusammenElement mapQuestionnaireToZusammenElement(String questionnaireData) { + ZusammenElement questionnaireElement = buildStructuralElement(ElementType.VSPQuestionnaire, Action.UPDATE); + questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); + return questionnaireElement; } - public String getValue() { - return value; + private void addVspDetailsToInfo(Info info, VspDetails vspDetails) { + info.addProperty(InfoPropertyName.NAME.getValue(), vspDetails.getName()); + info.addProperty(InfoPropertyName.DESCRIPTION.getValue(), vspDetails.getDescription()); + info.addProperty(InfoPropertyName.ICON.getValue(), vspDetails.getIcon()); + info.addProperty(InfoPropertyName.CATEGORY.getValue(), vspDetails.getCategory()); + info.addProperty(InfoPropertyName.SUB_CATEGORY.getValue(), vspDetails.getSubCategory()); + info.addProperty(InfoPropertyName.VENDOR_ID.getValue(), vspDetails.getVendorId()); + info.addProperty(InfoPropertyName.VENDOR_NAME.getValue(), vspDetails.getVendorName()); + if (vspDetails.getVlmVersion() != null) { + info.addProperty(InfoPropertyName.VENDOR_VERSION.getValue(), vspDetails.getVlmVersion().getId()); + } + info.addProperty(InfoPropertyName.LICENSE_TYPE.getValue(), vspDetails.getLicenseType()); + info.addProperty(InfoPropertyName.LICENSE_AGREEMENT.getValue(), vspDetails.getLicenseAgreement()); + info.addProperty(InfoPropertyName.FEATURE_GROUPS.getValue(), vspDetails.getFeatureGroups()); + info.addProperty(InfoPropertyName.ON_BOARDING_METHOD.getValue(), vspDetails.getOnboardingMethod()); } - } + public enum InfoPropertyName { + // @formatter:off + NAME("name"), + DESCRIPTION("description"), + ICON("icon"), + CATEGORY("category"), + SUB_CATEGORY("subCategory"), + VENDOR_ID("vendorId"), + VENDOR_NAME("vendorName"), + VENDOR_VERSION("vendorVersion"), + LICENSE_TYPE("licenseType"), + LICENSE_AGREEMENT("licenseAgreement"), + FEATURE_GROUPS("featureGroups"), + ON_BOARDING_METHOD("onboardingMethod"); + // @formatter:on + + private String value; + + InfoPropertyName(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java index d78e48bff8..c0b1be61bf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,47 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import org.apache.commons.io.IOUtils; - import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Objects; +import org.apache.commons.io.IOUtils; class VspZusammenUtil { - private VspZusammenUtil(){} + private VspZusammenUtil() { + } - static ZusammenElement aggregateElements(ZusammenElement... elements) { - ZusammenElement head = null; - ZusammenElement father = null; - for (ZusammenElement element : elements) { - if (Objects.isNull(head)) { - head = father = element; - } else { - if (father != null) { - father.getSubElements().add(element); - father = element; + static ZusammenElement aggregateElements(ZusammenElement... elements) { + ZusammenElement head = null; + ZusammenElement father = null; + for (ZusammenElement element : elements) { + if (Objects.isNull(head)) { + head = father = element; + } else { + if (father != null) { + father.getSubElements().add(element); + father = element; + } + } } - } + return head; } - return head; - } - - static boolean hasEmptyData(InputStream elementData) { - String EMPTY_DATA = "{}"; - byte[] byteElementData; - try { - byteElementData = IOUtils.toByteArray(elementData); - } catch (IOException ex) { - return false; - } - if (Arrays.equals(EMPTY_DATA.getBytes(), byteElementData)) { - return true; + static boolean hasEmptyData(InputStream elementData) { + String EMPTY_DATA = "{}"; + byte[] byteElementData; + try { + byteElementData = IOUtils.toByteArray(elementData); + } catch (IOException ex) { + return false; + } + if (Arrays.equals(EMPTY_DATA.getBytes(), byteElementData)) { + return true; + } + return false; } - return false; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java index b7a172ed90..d4c7fd05db 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -30,29 +29,24 @@ import org.openecomp.types.ElementPropertyName; public class ElementToComponentConvertor extends ElementConvertor { - @Override - public ComponentEntity convert(Element element) { - ComponentEntity componentEntity = new ComponentEntity(); - componentEntity.setId(element.getElementId().getValue()); - componentEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToComponentEntity(componentEntity,element.getInfo()); - return componentEntity; - } - - @Override - public ComponentEntity convert( ElementInfo elementInfo) { - ComponentEntity componentEntity = new ComponentEntity(); - componentEntity.setId(elementInfo.getId().getValue()); - mapInfoToComponentEntity(componentEntity,elementInfo.getInfo()); - return componentEntity; - } - - - public void mapInfoToComponentEntity(ComponentEntity componentEntity,Info info){ - - - componentEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - + @Override + public ComponentEntity convert(Element element) { + ComponentEntity componentEntity = new ComponentEntity(); + componentEntity.setId(element.getElementId().getValue()); + componentEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToComponentEntity(componentEntity, element.getInfo()); + return componentEntity; + } + + @Override + public ComponentEntity convert(ElementInfo elementInfo) { + ComponentEntity componentEntity = new ComponentEntity(); + componentEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentEntity(componentEntity, elementInfo.getInfo()); + return componentEntity; + } + + public void mapInfoToComponentEntity(ComponentEntity componentEntity, Info info) { + componentEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java index 232ff336aa..b00f4e4846 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -27,35 +26,27 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComponentDependencyModelPropertyName; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -public class ElementToComponentDependencyModelConvertor extends ElementConvertor { - - @Override - public ComponentDependencyModelEntity convert( Element element) { - ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); - componentDependencyModelEntity.setId(element.getElementId().getValue()); - mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity,element.getInfo()); - return componentDependencyModelEntity; - } - - @Override - public ComponentDependencyModelEntity convert(ElementInfo elementInfo) { - ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); - - componentDependencyModelEntity.setId(elementInfo.getId().getValue()); - mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity,elementInfo.getInfo()); - return componentDependencyModelEntity; - } - - - public void mapInfoToComponentDependencyModelEntity(ComponentDependencyModelEntity componentDependencyModelEntity,Info info){ - - componentDependencyModelEntity.setSourceComponentId(info - .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); - componentDependencyModelEntity.setTargetComponentId(info - .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); - componentDependencyModelEntity.setRelation(info - .getProperty(ComponentDependencyModelPropertyName.relation.name())); - - } - +public class ElementToComponentDependencyModelConvertor extends ElementConvertor { + + @Override + public ComponentDependencyModelEntity convert(Element element) { + ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); + componentDependencyModelEntity.setId(element.getElementId().getValue()); + mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity, element.getInfo()); + return componentDependencyModelEntity; + } + + @Override + public ComponentDependencyModelEntity convert(ElementInfo elementInfo) { + ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); + componentDependencyModelEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity, elementInfo.getInfo()); + return componentDependencyModelEntity; + } + + public void mapInfoToComponentDependencyModelEntity(ComponentDependencyModelEntity componentDependencyModelEntity, Info info) { + componentDependencyModelEntity.setSourceComponentId(info.getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); + componentDependencyModelEntity.setTargetComponentId(info.getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); + componentDependencyModelEntity.setRelation(info.getProperty(ComponentDependencyModelPropertyName.relation.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java index 2a8b3b9c81..044a862e4d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,49 +17,40 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; + import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; +import java.nio.ByteBuffer; import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; -import java.nio.ByteBuffer; - -import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; - public class ElementToComponentMonitoringUploadConvertor extends ElementConvertor { - @Override - public ComponentMonitoringUploadEntity convert(Element element) { - ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); - - mibEntity.setId(element.getElementId().getValue()); - mibEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); - mapInfoToComponentMonitoringUploadEntity(mibEntity, element.getInfo()); - return mibEntity; - } - - @Override - public ComponentMonitoringUploadEntity convert(ElementInfo elementInfo) { - ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); - - mibEntity.setId(elementInfo.getId().getValue()); - mapInfoToComponentMonitoringUploadEntity(mibEntity, elementInfo.getInfo()); - return mibEntity; - } - - - public void mapInfoToComponentMonitoringUploadEntity(ComponentMonitoringUploadEntity mibEntity, - Info info) { - - mibEntity.setArtifactName((String) info.getProperties().get(ARTIFACT_NAME)); - mibEntity.setType(MonitoringUploadType.valueOf(info.getName())); - } - - + @Override + public ComponentMonitoringUploadEntity convert(Element element) { + ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); + mibEntity.setId(element.getElementId().getValue()); + mibEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + mapInfoToComponentMonitoringUploadEntity(mibEntity, element.getInfo()); + return mibEntity; + } + + @Override + public ComponentMonitoringUploadEntity convert(ElementInfo elementInfo) { + ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); + mibEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentMonitoringUploadEntity(mibEntity, elementInfo.getInfo()); + return mibEntity; + } + + public void mapInfoToComponentMonitoringUploadEntity(ComponentMonitoringUploadEntity mibEntity, Info info) { + mibEntity.setArtifactName((String) info.getProperties().get(ARTIFACT_NAME)); + mibEntity.setType(MonitoringUploadType.valueOf(info.getName())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java index f8ab803280..febafaae2f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -25,17 +24,16 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; - /** * Created by ayalaben on 9/27/2017 */ public class ElementToComponentQuestionnnaireConvertor extends ElementConvertor { - @Override - public ComponentEntity convert( Element element) { - ComponentEntity componentEntity = new ComponentEntity(); - componentEntity.setId(element.getElementId().getValue()); - componentEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); - return componentEntity; - } + @Override + public ComponentEntity convert(Element element) { + ComponentEntity componentEntity = new ComponentEntity(); + componentEntity.setId(element.getElementId().getValue()); + componentEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return componentEntity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java index ca0d564ce2..b3271f5db4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,45 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; - -public class ElementToCompositionEntityConvertor extends ElementConvertor { +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; - @Override - public CompositionEntity convert(Element element) { +public class ElementToCompositionEntityConvertor extends ElementConvertor { - CompositionEntity compositionEntity = null; - switch (getElementType(element)) { - case ComponentQuestionnaire: - compositionEntity = new ComponentEntity(); - break; - case VSPQuestionnaire: - compositionEntity = new VspQuestionnaireEntity(); - break; - case ImageQuestionnaire: - compositionEntity = new ImageEntity(); - break; - case ComputeQuestionnaire: - compositionEntity = new ComponentEntity(); - break; - case NicQuestionnaire: - compositionEntity = new NicEntity(); + @Override + public CompositionEntity convert(Element element) { + CompositionEntity compositionEntity = null; + switch (getElementType(element)) { + case ComponentQuestionnaire: + compositionEntity = new ComponentEntity(); + break; + case VSPQuestionnaire: + compositionEntity = new VspQuestionnaireEntity(); + break; + case ImageQuestionnaire: + compositionEntity = new ImageEntity(); + break; + case ComputeQuestionnaire: + compositionEntity = new ComponentEntity(); + break; + case NicQuestionnaire: + compositionEntity = new NicEntity(); + } + if (compositionEntity != null) { + compositionEntity.setId(element.getElementId().getValue()); + compositionEntity.setQuestionnaireData(element.getData() == null ? null : new String(FileUtils.toByteArray(element.getData()))); + return compositionEntity; + } else { + return null; + } } - if (compositionEntity != null) { - compositionEntity.setId(element.getElementId().getValue()); - compositionEntity.setQuestionnaireData(element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))); - return compositionEntity; - } else { - return null; - } - } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java index ee10221862..12fba38009 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -28,33 +27,26 @@ import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.types.ElementPropertyName; -public class ElementToComputeConvertor extends ElementConvertor { - - @Override - public ComputeEntity convert( Element element) { - ComputeEntity computeEntity = new ComputeEntity(); - - computeEntity.setId(element.getElementId().getValue()); - computeEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToComputeEntity(computeEntity,element.getInfo()); - return computeEntity; - } - - @Override - public ComputeEntity convert( ElementInfo elementInfo) { - ComputeEntity computeEntity = new ComputeEntity(); - - computeEntity.setId(elementInfo.getId().getValue()); - mapInfoToComputeEntity(computeEntity,elementInfo.getInfo()); - return computeEntity; - } - - - public void mapInfoToComputeEntity(ComputeEntity computeEntity,Info info){ - - - computeEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - +public class ElementToComputeConvertor extends ElementConvertor { + + @Override + public ComputeEntity convert(Element element) { + ComputeEntity computeEntity = new ComputeEntity(); + computeEntity.setId(element.getElementId().getValue()); + computeEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToComputeEntity(computeEntity, element.getInfo()); + return computeEntity; + } + + @Override + public ComputeEntity convert(ElementInfo elementInfo) { + ComputeEntity computeEntity = new ComputeEntity(); + computeEntity.setId(elementInfo.getId().getValue()); + mapInfoToComputeEntity(computeEntity, elementInfo.getInfo()); + return computeEntity; + } + + public void mapInfoToComputeEntity(ComputeEntity computeEntity, Info info) { + computeEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java index bc5b556625..c255dcce24 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -25,15 +24,13 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; -public class ElementToComputeQuestionnaireConvertor extends ElementConvertor { - - @Override - public ComputeEntity convert( Element element) { - ComputeEntity computeEntity = new ComputeEntity(); - - computeEntity.setId(element.getElementId().getValue()); - computeEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); - return computeEntity; - } +public class ElementToComputeQuestionnaireConvertor extends ElementConvertor { + @Override + public ComputeEntity convert(Element element) { + ComputeEntity computeEntity = new ComputeEntity(); + computeEntity.setId(element.getElementId().getValue()); + computeEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return computeEntity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java index 19719c6827..c354da1707 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -28,33 +27,26 @@ import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.types.ElementPropertyName; -public class ElementToDeploymentFlavorConvertor extends ElementConvertor { - - @Override - public DeploymentFlavorEntity convert( Element element) { - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); - - deploymentFlavorEntity.setId(element.getElementId().getValue()); - deploymentFlavorEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity,element.getInfo()); - return deploymentFlavorEntity; - } - - @Override - public DeploymentFlavorEntity convert( ElementInfo elementInfo) { - DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); - - deploymentFlavorEntity.setId(elementInfo.getId().getValue()); - mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity,elementInfo.getInfo()); - return deploymentFlavorEntity; - } - - - public void mapInfoToDeploymentFlavorEntity(DeploymentFlavorEntity deploymentFlavorEntity,Info info){ - - - deploymentFlavorEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - +public class ElementToDeploymentFlavorConvertor extends ElementConvertor { + + @Override + public DeploymentFlavorEntity convert(Element element) { + DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); + deploymentFlavorEntity.setId(element.getElementId().getValue()); + deploymentFlavorEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity, element.getInfo()); + return deploymentFlavorEntity; + } + + @Override + public DeploymentFlavorEntity convert(ElementInfo elementInfo) { + DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); + deploymentFlavorEntity.setId(elementInfo.getId().getValue()); + mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity, elementInfo.getInfo()); + return deploymentFlavorEntity; + } + + public void mapInfoToDeploymentFlavorEntity(DeploymentFlavorEntity deploymentFlavorEntity, Info info) { + deploymentFlavorEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java index 66621d6934..5aa164c06b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -28,33 +27,26 @@ import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.types.ElementPropertyName; -public class ElementToImageConvertor extends ElementConvertor { - - @Override - public ImageEntity convert( Element element) { - ImageEntity imageEntity = new ImageEntity(); - - imageEntity.setId(element.getElementId().getValue()); - imageEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToImageEntity(imageEntity,element.getInfo()); - return imageEntity; - } - - @Override - public ImageEntity convert( ElementInfo elementInfo) { - ImageEntity imageEntity = new ImageEntity(); - - imageEntity.setId(elementInfo.getId().getValue()); - mapInfoToImageEntity(imageEntity,elementInfo.getInfo()); - return imageEntity; - } - - - public void mapInfoToImageEntity(ImageEntity imageEntity,Info info){ - - - imageEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - +public class ElementToImageConvertor extends ElementConvertor { + + @Override + public ImageEntity convert(Element element) { + ImageEntity imageEntity = new ImageEntity(); + imageEntity.setId(element.getElementId().getValue()); + imageEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToImageEntity(imageEntity, element.getInfo()); + return imageEntity; + } + + @Override + public ImageEntity convert(ElementInfo elementInfo) { + ImageEntity imageEntity = new ImageEntity(); + imageEntity.setId(elementInfo.getId().getValue()); + mapInfoToImageEntity(imageEntity, elementInfo.getInfo()); + return imageEntity; + } + + public void mapInfoToImageEntity(ImageEntity imageEntity, Info info) { + imageEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java index 4dfe9d297f..32aa3c4041 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -25,15 +24,13 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; -public class ElementToImageQuestionnaireConvertor extends ElementConvertor { - - @Override - public ImageEntity convert( Element element) { - ImageEntity imageEntity = new ImageEntity(); - - imageEntity.setId(element.getElementId().getValue()); - imageEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); - return imageEntity; - } +public class ElementToImageQuestionnaireConvertor extends ElementConvertor { + @Override + public ImageEntity convert(Element element) { + ImageEntity imageEntity = new ImageEntity(); + imageEntity.setId(element.getElementId().getValue()); + imageEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return imageEntity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java index 8c4a284fa4..0f2b208808 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import org.openecomp.convertor.ElementConvertor; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import java.util.HashMap; import java.util.Map; - -import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; +import org.openecomp.convertor.ElementConvertor; /** * Created by ayalaben on 9/5/2017. */ +public class ElementToMonitoringUploadMapConvertor extends ElementConvertor> { -public class ElementToMonitoringUploadMapConvertor extends ElementConvertor> { - - @Override - public Map convert(Element element) { - HashMap map = new HashMap<>(); - map.put("File Name",element.getInfo().getProperty(ARTIFACT_NAME)); - return map; - } + @Override + public Map convert(Element element) { + HashMap map = new HashMap<>(); + map.put("File Name", element.getInfo().getProperty(ARTIFACT_NAME)); + return map; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java index a34e650e78..0a64ff54c2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -28,31 +27,26 @@ import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.types.ElementPropertyName; -public class ElementToNetworkConvertor extends ElementConvertor { - - @Override - public NetworkEntity convert( Element element) { - NetworkEntity networkEntity = new NetworkEntity(); - - networkEntity.setId(element.getElementId().getValue()); - networkEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToNetworkEntity(networkEntity,element.getInfo()); - return networkEntity; - } - - @Override - public NetworkEntity convert( ElementInfo elementInfo) { - NetworkEntity networkEntity = new NetworkEntity(); - - networkEntity.setId(elementInfo.getId().getValue()); - mapInfoToNetworkEntity(networkEntity,elementInfo.getInfo()); - return networkEntity; - } - - - public void mapInfoToNetworkEntity(NetworkEntity networkEntity,Info info){ - networkEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - +public class ElementToNetworkConvertor extends ElementConvertor { + + @Override + public NetworkEntity convert(Element element) { + NetworkEntity networkEntity = new NetworkEntity(); + networkEntity.setId(element.getElementId().getValue()); + networkEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToNetworkEntity(networkEntity, element.getInfo()); + return networkEntity; + } + + @Override + public NetworkEntity convert(ElementInfo elementInfo) { + NetworkEntity networkEntity = new NetworkEntity(); + networkEntity.setId(elementInfo.getId().getValue()); + mapInfoToNetworkEntity(networkEntity, elementInfo.getInfo()); + return networkEntity; + } + + public void mapInfoToNetworkEntity(NetworkEntity networkEntity, Info info) { + networkEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java index a41eb382b2..e126586420 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -28,32 +27,26 @@ import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.types.ElementPropertyName; -public class ElementToNicConvertor extends ElementConvertor { - - @Override - public NicEntity convert( Element element) { - NicEntity nicEntity = new NicEntity(); - - nicEntity.setId(element.getElementId().getValue()); - nicEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); - mapInfoToNicEntity(nicEntity,element.getInfo()); - return nicEntity; - } - - @Override - public NicEntity convert( ElementInfo elementInfo) { - NicEntity nicEntity = new NicEntity(); - - nicEntity.setId(elementInfo.getId().getValue()); - mapInfoToNicEntity(nicEntity,elementInfo.getInfo()); - return nicEntity; - } - - - public void mapInfoToNicEntity(NicEntity nicEntity,Info info){ - - nicEntity.setCompositionData( - info.getProperty(ElementPropertyName.compositionData.name())); - } - +public class ElementToNicConvertor extends ElementConvertor { + + @Override + public NicEntity convert(Element element) { + NicEntity nicEntity = new NicEntity(); + nicEntity.setId(element.getElementId().getValue()); + nicEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToNicEntity(nicEntity, element.getInfo()); + return nicEntity; + } + + @Override + public NicEntity convert(ElementInfo elementInfo) { + NicEntity nicEntity = new NicEntity(); + nicEntity.setId(elementInfo.getId().getValue()); + mapInfoToNicEntity(nicEntity, elementInfo.getInfo()); + return nicEntity; + } + + public void mapInfoToNicEntity(NicEntity nicEntity, Info info) { + nicEntity.setCompositionData(info.getProperty(ElementPropertyName.compositionData.name())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java index ec84ae9f6d..fe397f772d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -25,17 +24,13 @@ import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -public class ElementToNicQuestionnaireConvertor extends ElementConvertor { - - @Override - public NicEntity convert( Element element) { - NicEntity nicEntity = new NicEntity(); - - nicEntity.setId(element.getElementId().getValue()); - nicEntity.setQuestionnaireData( element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))); - return nicEntity; - } +public class ElementToNicQuestionnaireConvertor extends ElementConvertor { + @Override + public NicEntity convert(Element element) { + NicEntity nicEntity = new NicEntity(); + nicEntity.setId(element.getElementId().getValue()); + nicEntity.setQuestionnaireData(element.getData() == null ? null : new String(FileUtils.toByteArray(element.getData()))); + return nicEntity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java index de9cc520b3..653c561ca6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -29,12 +28,10 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStru /** * Created by ayalaben on 9/6/2017 */ -public class ElementToOrchestrationTemplateCandidateMapConvertor - extends ElementConvertor { +public class ElementToOrchestrationTemplateCandidateMapConvertor extends ElementConvertor { - @Override - public FilesDataStructure convert(Element element) { - return JsonUtil.json2Object(new String(FileUtils.toByteArray(element.getData())), - FilesDataStructure.class); - } + @Override + public FilesDataStructure convert(Element element) { + return JsonUtil.json2Object(new String(FileUtils.toByteArray(element.getData())), FilesDataStructure.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java index ec8aa172bd..d14f870eac 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,55 +17,51 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.datatypes.item.Info; +import java.nio.ByteBuffer; import org.openecomp.convertor.ElementConvertor; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; -import java.nio.ByteBuffer; - public class ElementToProcessConvertor extends ElementConvertor { - public static final String NAME = "name"; - public static final String ARTIFACT_NAME = "artifactName"; - public static final String DESCRIPTION = "description"; - public static final String PROCESS_TYPE = "processType"; + public static final String NAME = "name"; + public static final String ARTIFACT_NAME = "artifactName"; + public static final String DESCRIPTION = "description"; + public static final String PROCESS_TYPE = "processType"; - @Override - public ProcessEntity convert(Element element) { - if (element == null) { - return null; + @Override + public ProcessEntity convert(Element element) { + if (element == null) { + return null; + } + ProcessEntity processEntity = new ProcessEntity(); + processEntity.setId(element.getElementId().getValue()); + processEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + mapInfoToProcessEntity(processEntity, element.getInfo()); + return processEntity; } - ProcessEntity processEntity = new ProcessEntity(); - processEntity.setId(element.getElementId().getValue()); - processEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); - mapInfoToProcessEntity(processEntity, element.getInfo()); - return processEntity; - } - @Override - public ProcessEntity convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public ProcessEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + ProcessEntity processEntity = new ProcessEntity(); + processEntity.setId(elementInfo.getId().getValue()); + mapInfoToProcessEntity(processEntity, elementInfo.getInfo()); + return processEntity; } - ProcessEntity processEntity = new ProcessEntity(); - processEntity.setId(elementInfo.getId().getValue()); - mapInfoToProcessEntity(processEntity, elementInfo.getInfo()); - return processEntity; - } - public void mapInfoToProcessEntity(ProcessEntity processEntity, Info info) { - processEntity.setName(info.getProperty(NAME)); - processEntity.setArtifactName(info.getProperty(ARTIFACT_NAME)); - processEntity.setDescription(info.getProperty(DESCRIPTION)); - processEntity.setType(info.getProperty - (PROCESS_TYPE) != null ? ProcessType.valueOf(info.getProperty - (PROCESS_TYPE)) : null); - } + public void mapInfoToProcessEntity(ProcessEntity processEntity, Info info) { + processEntity.setName(info.getProperty(NAME)); + processEntity.setArtifactName(info.getProperty(ARTIFACT_NAME)); + processEntity.setDescription(info.getProperty(DESCRIPTION)); + processEntity.setType(info.getProperty(PROCESS_TYPE) != null ? ProcessType.valueOf(info.getProperty(PROCESS_TYPE)) : null); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java index 574d3b30f6..e6a151a6c3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import org.openecomp.convertor.ElementConvertor; - import java.util.HashMap; import java.util.Map; +import org.openecomp.convertor.ElementConvertor; /** * Created by ayalaben on 9/11/2017 */ -public class ElementToServiceModelMapConvertor extends ElementConvertor> { - @Override - public Map convert(Element element) { - //TODO : after merge with 1802 change to heat fle name/TOSCA file name - HashMap map = new HashMap<>(); - map.put("Service Model Definition Entry", element.getInfo().getProperty("base")); - return map; - } +public class ElementToServiceModelMapConvertor extends ElementConvertor> { + + @Override + public Map convert(Element element) { + //TODO : after merge with 1802 change to heat fle name/TOSCA file name + HashMap map = new HashMap<>(); + map.put("Service Model Definition Entry", element.getInfo().getProperty("base")); + return map; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java index d8bb1798ff..8234eeeaf1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -29,72 +28,51 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.VendorSoftwareP import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; - public class ElementToVSPGeneralConvertor extends ElementConvertor { - @Override - public VspDetails convert(Element element) { - if (element == null) { - return null; - } - return mapInfoToVspDetails(element.getInfo()); - } - - @Override - public VspDetails convert(Item item) { - if (item == null) { - return null; + @Override + public VspDetails convert(Element element) { + if (element == null) { + return null; + } + return mapInfoToVspDetails(element.getInfo()); } - VspDetails vspDetails = mapInfoToVspDetails(item.getInfo()); - vspDetails.setId(item.getId().getValue()); - return vspDetails; - } - @Override - public VspDetails convert(ElementInfo elementInfo) { - if (elementInfo == null) { - return null; + @Override + public VspDetails convert(Item item) { + if (item == null) { + return null; + } + VspDetails vspDetails = mapInfoToVspDetails(item.getInfo()); + vspDetails.setId(item.getId().getValue()); + return vspDetails; } - return mapInfoToVspDetails(elementInfo.getInfo()); - - } - - private VspDetails mapInfoToVspDetails(Info info) { - - VspDetails vspDetails = new VspDetails(); - - vspDetails.setName(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl - .InfoPropertyName.NAME.getValue())); - vspDetails.setDescription(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.DESCRIPTION.getValue())); - vspDetails.setIcon(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.ICON.getValue())); - vspDetails.setCategory(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.CATEGORY.getValue())); - vspDetails.setSubCategory(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.SUB_CATEGORY.getValue())); - vspDetails.setVendorId(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_ID.getValue())); - vspDetails.setVendorName(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_NAME.getValue())); - if (info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_VERSION.getValue()) != null) { - vspDetails.setVlmVersion(new Version(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_VERSION.getValue()))); + @Override + public VspDetails convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapInfoToVspDetails(elementInfo.getInfo()); } - vspDetails.setLicenseType(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.LICENSE_TYPE.getValue())); - vspDetails.setLicenseAgreement(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.LICENSE_AGREEMENT.getValue())); - vspDetails.setFeatureGroups(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.FEATURE_GROUPS.getValue())); - vspDetails.setOnboardingMethod(info.getProperty( - VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.ON_BOARDING_METHOD.getValue())); - - return vspDetails; - } - - + private VspDetails mapInfoToVspDetails(Info info) { + VspDetails vspDetails = new VspDetails(); + vspDetails.setName(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.NAME.getValue())); + vspDetails.setDescription(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.DESCRIPTION.getValue())); + vspDetails.setIcon(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.ICON.getValue())); + vspDetails.setCategory(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.CATEGORY.getValue())); + vspDetails.setSubCategory(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.SUB_CATEGORY.getValue())); + vspDetails.setVendorId(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_ID.getValue())); + vspDetails.setVendorName(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_NAME.getValue())); + if (info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_VERSION.getValue()) != null) { + vspDetails + .setVlmVersion(new Version(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.VENDOR_VERSION.getValue()))); + } + vspDetails.setLicenseType(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.LICENSE_TYPE.getValue())); + vspDetails.setLicenseAgreement(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.LICENSE_AGREEMENT.getValue())); + vspDetails.setFeatureGroups(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.FEATURE_GROUPS.getValue())); + vspDetails.setOnboardingMethod(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.ON_BOARDING_METHOD.getValue())); + return vspDetails; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java index b8797cf8e2..71a2b4782d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; @@ -23,11 +22,10 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; public class ElementToVSPQuestionnaireConvertor extends ElementConvertor { - @Override - public VspQuestionnaireEntity convert(Element element) { - VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); - entity.setQuestionnaireData( - element == null ? "{}" : new String(FileUtils.toByteArray(element.getData()))); - return entity; - } + @Override + public VspQuestionnaireEntity convert(Element element) { + VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); + entity.setQuestionnaireData(element == null ? "{}" : new String(FileUtils.toByteArray(element.getData()))); + return entity; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java index 83abbfb123..13ade278bf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.errors; /** @@ -21,110 +20,64 @@ package org.openecomp.sdc.vendorsoftwareproduct.errors; */ public class VendorSoftwareProductErrorCodes { - public static final String VSP_NOT_FOUND = "VSP_NOT_FOUND"; - public static final String VSP_INVALID = "VSP_INVALID"; - public static final String VFC_INVALID = "VFC_INVALID"; - public static final String FAILED_TO_CREATE_VSP = "FAILED_TO_CREATE_VSP"; - - public static final String UPLOAD_INVALID = "UPLOAD_INVALID"; - - public static final String PACKAGE_NOT_FOUND = "PACKAGE_NOT_FOUND"; - - public static final String PACKAGE_INVALID = "PACKAGE_INVALID"; - public static final String VSP_COMPOSITION_EDIT_NOT_ALLOWED = "VSP_COMPOSITION_EDIT_NOT_ALLOWED"; - - public static final String CREATE_PACKAGE_FOR_NON_FINAL_VSP = "CREATE_PACKAGE_FOR_NON_FINAL_VSP"; - - public static final String TRANSLATION_FILE_CREATION = "TRANSLATION_FILE_CREATION"; - - public static final String HEAT_PACKAGE_FILE_CREATION = "HEAT_PACKAGE_FILE_CREATION"; - - public static final String TOSCA_ENTRY_NOT_FOUND = "TOSCA_ENTRY_NOT_FOUND"; - public static final String TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE = - "TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE"; - - public static final String MONITORING_UPLOAD_INVALID = "MONITORING_UPLOAD_INVALID"; - - public static final String ORCHESTRATION_NOT_FOUND = "ORCHESTRATION_NOT_FOUND"; - - - public static final String CYCLIC_DEPENDENCY_IN_COMPONENTS = "CYCLIC_DEPENDENCY_IN_COMPONENTS"; - - public static final String INVALID_COMPONENT_RELATION_TYPE = "INVALID_COMPONENT_RELATION_TYPE"; - - public static final String NO_SOURCE_COMPONENT = "NO_SOURCE_COMPONENT"; - - public static final String SAME_SOURCE_TARGET_COMPONENT = "SAME_SOURCE_TARGET_COMPONENT"; - - public static final String DUPLICATE_NIC_NAME_NOT_ALLOWED = "DUPLICATE_NIC_NAME_NOT_ALLOWED"; - public static final String NIC_NAME_FORMAT_NOT_ALLOWED = "NIC_NAME_FORMAT_NOT_ALLOWED"; - - public static final String NULL_NETWORKID_NOT_ALLOWED = "NULL_NETWORKID_NOT_ALLOWED"; - - public static final String NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK = - "NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK"; - - public static final String VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING = - "VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - public static final String VSP_VFC_COUNT_EXCEED = "VSP_VFC_COUNT_EXCEED"; - public static final String VSP_VFC_DUPLICATE_NAME = "VSP_VFC_DUPLICATE_NAME"; - public static final String VSP_INVALID_ONBOARDING_METHOD = "VSP_INVALID_ONBOARDING_METHOD"; - public static final String - ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - public static final String NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK - = "NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK"; - - public static final String VFC_ATTRIBUTE_UPDATE_NOT_ALLOWED = - "VFC_ATTRIBUTE_UPDATE_NOT_ALLOWED"; - public static final String NETWORK_TYPE_UPDATE_NOT_ALLOWED - = "NETWORK_TYPE_UPDATE_NOT_ALLOWED"; - public static final String DELETE_NIC_NOT_ALLOWED = "DELETE_NIC_NOT_ALLOWED"; - - public static final String CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = - "CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - - public static final String DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = - "DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - - public static final String EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = - "EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - - public static final String FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR = - "FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR"; - - public static final String - ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - - public static final String DUPLICATE_IMAGE_NAME_NOT_ALLOWED = "DUPLICATE_IMAGE_NAME_NOT_ALLOWED"; - public static final String DUPLICATE_IMAGE_VERSION_NOT_ALLOWED = "DUPLICATE_IMAGE_VERSION_NOT_ALLOWED"; - public static final String IMAGE_NAME_FORMAT_NOT_ALLOWED = "IMAGE_NAME_FORMAT_NOT_ALLOWED"; - public static final String VFC_IMAGE_INVALID_FORMAT = "VFC_IMAGE_INVALID_FORMAT"; - public static final String FEATURE_GROUP_NOT_EXIST_FOR_VSP = "FEATURE_GROUP_NOT_EXIST_FOR_VSP"; - - public static final String - ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING"; - public static final String VFC_COMPUTE_INVALID_FORMAT = "VFC_COMPUTE_INVALID_FORMAT"; - public static final String UPDATE_COMPUTE_NOT_ALLOWED = "UPDATE_COMPUTE_NOT_ALLOWED"; - public static final String - INVALID_COMPONENT_COMPUTE_ASSOCIATION = "INVALID_COMPONENT_COMPUTE_ASSOCIATION"; - public static final String SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED - = "SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED"; - public static final String DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED - = "DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED"; - public static final String DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED = - "DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED"; - public static final String INVALID_COMPUTE_FLAVOR_ID = "INVALID_COMPUTE_FLAVOR_ID"; - public static final String INVALID_COMPONENT_ID = "INVALID_COMPONENT_ID"; - public static final String DUPLICATE_COMPUTE_NAME_NOT_ALLOWED = "DUPLICATE_COMPUTE_NAME_NOT_ALLOWED"; - public static final String COMPUTE_NAME_FORMAT_NOT_ALLOWED = "COMPUTE_NAME_FORMAT_NOT_ALLOWED"; - - public static final String DELETE_IMAGE_NOT_ALLOWED = "DELETE_IMAGE_NOT_ALLOWED"; - public static final String UPDATE_IMAGE_NOT_ALLOWED = "UPDATE_IMAGE_NOT_ALLOWED"; - - public static final String INVALID_EXTENSION = "INVALID_EXTENSION"; - - public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = - "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; - - private VendorSoftwareProductErrorCodes(){} + public static final String VSP_NOT_FOUND = "VSP_NOT_FOUND"; + public static final String VSP_INVALID = "VSP_INVALID"; + public static final String VFC_INVALID = "VFC_INVALID"; + public static final String FAILED_TO_CREATE_VSP = "FAILED_TO_CREATE_VSP"; + public static final String UPLOAD_INVALID = "UPLOAD_INVALID"; + public static final String PACKAGE_NOT_FOUND = "PACKAGE_NOT_FOUND"; + public static final String PACKAGE_INVALID = "PACKAGE_INVALID"; + public static final String VSP_COMPOSITION_EDIT_NOT_ALLOWED = "VSP_COMPOSITION_EDIT_NOT_ALLOWED"; + public static final String CREATE_PACKAGE_FOR_NON_FINAL_VSP = "CREATE_PACKAGE_FOR_NON_FINAL_VSP"; + public static final String TRANSLATION_FILE_CREATION = "TRANSLATION_FILE_CREATION"; + public static final String HEAT_PACKAGE_FILE_CREATION = "HEAT_PACKAGE_FILE_CREATION"; + public static final String TOSCA_ENTRY_NOT_FOUND = "TOSCA_ENTRY_NOT_FOUND"; + public static final String TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE = "TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE"; + public static final String MONITORING_UPLOAD_INVALID = "MONITORING_UPLOAD_INVALID"; + public static final String ORCHESTRATION_NOT_FOUND = "ORCHESTRATION_NOT_FOUND"; + public static final String CYCLIC_DEPENDENCY_IN_COMPONENTS = "CYCLIC_DEPENDENCY_IN_COMPONENTS"; + public static final String INVALID_COMPONENT_RELATION_TYPE = "INVALID_COMPONENT_RELATION_TYPE"; + public static final String NO_SOURCE_COMPONENT = "NO_SOURCE_COMPONENT"; + public static final String SAME_SOURCE_TARGET_COMPONENT = "SAME_SOURCE_TARGET_COMPONENT"; + public static final String DUPLICATE_NIC_NAME_NOT_ALLOWED = "DUPLICATE_NIC_NAME_NOT_ALLOWED"; + public static final String NIC_NAME_FORMAT_NOT_ALLOWED = "NIC_NAME_FORMAT_NOT_ALLOWED"; + public static final String NULL_NETWORKID_NOT_ALLOWED = "NULL_NETWORKID_NOT_ALLOWED"; + public static final String NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK = "NETWORKID_NOT_ALLOWED_FOR_EXTERNAL_NETWORK"; + public static final String VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING = "VFC_ADD_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String VSP_VFC_COUNT_EXCEED = "VSP_VFC_COUNT_EXCEED"; + public static final String VSP_VFC_DUPLICATE_NAME = "VSP_VFC_DUPLICATE_NAME"; + public static final String VSP_INVALID_ONBOARDING_METHOD = "VSP_INVALID_ONBOARDING_METHOD"; + public static final String ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_NIC_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK = "NETWORK_DESCRIPTION_NOT_ALLOWED_FOR_INTERNAL_NETWORK"; + public static final String VFC_ATTRIBUTE_UPDATE_NOT_ALLOWED = "VFC_ATTRIBUTE_UPDATE_NOT_ALLOWED"; + public static final String NETWORK_TYPE_UPDATE_NOT_ALLOWED = "NETWORK_TYPE_UPDATE_NOT_ALLOWED"; + public static final String DELETE_NIC_NOT_ALLOWED = "DELETE_NIC_NOT_ALLOWED"; + public static final String CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = "CREATE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = "DELETE_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING = "EDIT_DEPLOYMENT_FLAVOR_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR = "FEATUREGROUP_REQUIRED_IN_DEPLOYMENT_FLAVOR"; + public static final String ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_IMAGE_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String DUPLICATE_IMAGE_NAME_NOT_ALLOWED = "DUPLICATE_IMAGE_NAME_NOT_ALLOWED"; + public static final String DUPLICATE_IMAGE_VERSION_NOT_ALLOWED = "DUPLICATE_IMAGE_VERSION_NOT_ALLOWED"; + public static final String IMAGE_NAME_FORMAT_NOT_ALLOWED = "IMAGE_NAME_FORMAT_NOT_ALLOWED"; + public static final String VFC_IMAGE_INVALID_FORMAT = "VFC_IMAGE_INVALID_FORMAT"; + public static final String FEATURE_GROUP_NOT_EXIST_FOR_VSP = "FEATURE_GROUP_NOT_EXIST_FOR_VSP"; + public static final String ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING = "ADD_COMPUTE_NOT_ALLOWED_IN_HEAT_ONBOARDING"; + public static final String VFC_COMPUTE_INVALID_FORMAT = "VFC_COMPUTE_INVALID_FORMAT"; + public static final String UPDATE_COMPUTE_NOT_ALLOWED = "UPDATE_COMPUTE_NOT_ALLOWED"; + public static final String INVALID_COMPONENT_COMPUTE_ASSOCIATION = "INVALID_COMPONENT_COMPUTE_ASSOCIATION"; + public static final String SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED = "SAME_VFC_ASSOCIATION_MORE_THAN_ONCE_NOT_ALLOWED"; + public static final String DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED = "DUPLICATE_DEPLOYMENT_FLAVOR_MODEL_NOT_ALLOWED"; + public static final String DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED = "DEPLOYMENT_FLAVOR_NAME_FORMAT_NOT_ALLOWED"; + public static final String INVALID_COMPUTE_FLAVOR_ID = "INVALID_COMPUTE_FLAVOR_ID"; + public static final String INVALID_COMPONENT_ID = "INVALID_COMPONENT_ID"; + public static final String DUPLICATE_COMPUTE_NAME_NOT_ALLOWED = "DUPLICATE_COMPUTE_NAME_NOT_ALLOWED"; + public static final String COMPUTE_NAME_FORMAT_NOT_ALLOWED = "COMPUTE_NAME_FORMAT_NOT_ALLOWED"; + public static final String DELETE_IMAGE_NOT_ALLOWED = "DELETE_IMAGE_NOT_ALLOWED"; + public static final String UPDATE_IMAGE_NOT_ALLOWED = "UPDATE_IMAGE_NOT_ALLOWED"; + public static final String INVALID_EXTENSION = "INVALID_EXTENSION"; + public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; + + private VendorSoftwareProductErrorCodes() { + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactoryImpl.java index df5e44122d..90019a2467 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/InformationArtifactGeneratorFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; - import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactGenerator; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactGeneratorImpl; - public class InformationArtifactGeneratorFactoryImpl extends InformationArtifactGeneratorFactory { - @Override - public InformationArtifactGenerator createInterface() { - return new TxtInformationArtifactGeneratorImpl(); - } + @Override + public InformationArtifactGenerator createInterface() { + return new TxtInformationArtifactGeneratorImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnaireDataServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnaireDataServiceFactoryImpl.java index 865c7f1189..3c0cbe5ff3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnaireDataServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/QuestionnaireDataServiceFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory; - import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; import org.openecomp.sdc.vendorsoftwareproduct.quiestionnaire.QuestionnaireDataServiceImpl; - public class QuestionnaireDataServiceFactoryImpl extends QuestionnnaireDataServiceFactory { - @Override - public QuestionnaireDataService createInterface() { - return new QuestionnaireDataServiceImpl(); - } + @Override + public QuestionnaireDataService createInterface() { + return new QuestionnaireDataServiceImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CandidateServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CandidateServiceFactoryImpl.java index b98605a53d..b777b586d0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CandidateServiceFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CandidateServiceFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory.impl; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.OrchestrationTemplateCandidateDaoFactoryImpl; @@ -26,12 +25,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.factory.ManifestCreatorFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremodule.CandidateServiceImpl; - public class CandidateServiceFactoryImpl extends CandidateServiceFactory { - @Override - public CandidateService createInterface() { - return new CandidateServiceImpl(ManifestCreatorFactory.getInstance().createInterface(), - OrchestrationTemplateCandidateDaoFactoryImpl.getInstance().createInterface()); - } + @Override + public CandidateService createInterface() { + return new CandidateServiceImpl(ManifestCreatorFactory.getInstance().createInterface(), + OrchestrationTemplateCandidateDaoFactoryImpl.getInstance().createInterface()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionDataExtractorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionDataExtractorFactoryImpl.java index 21b0d9c0a8..fe0e82e9f4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionDataExtractorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionDataExtractorFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory.impl; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; @@ -26,8 +25,8 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.impl.composition.Composi public class CompositionDataExtractorFactoryImpl extends CompositionDataExtractorFactory { - @Override - public CompositionDataExtractor createInterface() { - return new CompositionDataExtractorImpl(); - } + @Override + public CompositionDataExtractor createInterface() { + return new CompositionDataExtractorImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/ManifestCreatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/ManifestCreatorFactoryImpl.java index c7d088408e..6700fe977c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/ManifestCreatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/ManifestCreatorFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.factory.impl; import org.openecomp.sdc.vendorsoftwareproduct.factory.ManifestCreatorFactory; @@ -29,8 +28,8 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremo */ public class ManifestCreatorFactoryImpl extends ManifestCreatorFactory { - @Override - public ManifestCreator createInterface(){ - return new ManifestCreatorNamingConventionImpl(); - } + @Override + public ManifestCreator createInterface() { + return new ManifestCreatorNamingConventionImpl(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactConstants.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactConstants.java index 4fee8aec75..28575c77c0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactConstants.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactConstants.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,81 +17,68 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl; /** * @author KATYR * @since December 07, 2016 */ - public class TxtInformationArtifactConstants { - public static final String QUOTEMARK = "\""; - public static final String SPACE = " "; - public static final String TAB = SPACE + SPACE + SPACE + SPACE; - public static final String NL = System.lineSeparator(); - public static final String DELIMITER = ":"; - public static final String FOUR_TABS = TAB + TAB + TAB + TAB; - - - public static final String TITLE = "1." + TAB + "VSP Details" + DELIMITER; - public static final String VSP_NAME = "a." + TAB + "Name" + DELIMITER; - public static final String VSP_DESC = "b." + TAB + "Description"; - public static final String VSP_VENDOR = "d." + TAB + "Vendor" + DELIMITER; - public static final String VSP_VERSION = "c." + TAB + "Version" + DELIMITER; - public static final String VSP_CATEGORY = "e." + TAB + "Category" + DELIMITER; - public static final String LICENSE_DETAILS = "f." + TAB + "License Details" + DELIMITER; - public static final String LICENSE_MODEL_VERSION = - "i." + TAB + "License Model Version" + DELIMITER; - public static final String LICENSE_AGREEMENT_NAME = - "ii." + TAB + "License Agreement Name" + DELIMITER; - public static final String LIST_OF_FEATURE_GROUPS = "iii" + TAB + "List of Feature Groups"+DELIMITER; - public static final String HIGH_AVAILABILITY = "g." + TAB + "High Availability"; - public static final String USING_AVAILABILITY_ZONES = "i." + TAB + "Using Availability " - + "Zones" + DELIMITER; - public static final String STORAGE_BACKUP_DETAILS = "h." + TAB + "Storage Data Back-up " - + "Details" + DELIMITER; - public static final String IS_DATA_REPLICATION = - "i." + TAB + "Data Replication Required?" + DELIMITER; - public static final String DATA_SIZE_TO_REP = - "ii." + TAB + " Data Size to replicate in GB" + DELIMITER; - public static final String DATA_REP_FREQUENCY = - "iii." + TAB + "Data replication frequency" + DELIMITER; - public static final String DATA_REP_SOURCE = "iv." + TAB + "Replication Source" + DELIMITER; - public static final String DATA_REP_DEST = "v." + TAB + "Replication Destination" + DELIMITER; - public static final String LIST_OF_NETWORKS = "List of Internal Networks";//currently not used - public static final String LIST_OF_VFCS = "3." + TAB + "List of VFCs"; - public static final String FOR_EACH_VFC = "a." + TAB + "For each VFC" + DELIMITER; - public static final String VFC_NAME = "i." + TAB + "VFC Name" + DELIMITER; - public static final String VFC_DESC = "ii." + TAB + "Description" + DELIMITER; - public static final String VFC_IMAGES = "iii." + TAB + "Images" + DELIMITER; - public static final String VFC_COMPUTE = "iv." + TAB + "Compute/VM Characteristics"; - public static final String VFC_COMPUTE_VCPU = "1." + TAB + "vCPU" + DELIMITER; - public static final String VFC_COMPUTE_CPU_OVER_SUBSCRIPTION = "2." + TAB + "CPU " - + "over-subscription" + DELIMITER; - public static final String VFC_COMPUTE_MEMORY = "3." + TAB + "Memory" + DELIMITER; - public static final String VFC_COMPUTE_DISK = "4." + TAB + "Disk" + DELIMITER; - public static final String HYPERVISOR_DETAILS = "v." + TAB + "Hypervisor Details"; - public static final String HYPERVISOR_DETAILS_NAME = "1." + TAB + "Name" + DELIMITER; - public static final String HYPERVISOR_DETAILS_DRIVERS = "2." + TAB + "Drivers" + DELIMITER; - public static final String GUEST_OS_DETAILS = "vi." + TAB + "Guest OS Details"; - public static final String GUEST_OS_NAME = "1." + TAB + "Name" + DELIMITER; - public static final String GUEST_OS_BIT_SIZE = "2." + TAB + "Bit Size" + DELIMITER; - public static final String GUEST_OS_TOOLS = "3." + TAB + "Tools" + DELIMITER; - public static final String VFC_INSTANCE_NUMBER = "vii." + TAB + "Number of VFC Instances"; - public static final String VFC_INSTANCE_NUMBER_MIN = "1." + TAB + "Minimum" + DELIMITER; - public static final String VFC_INSTANCE_NUMBER_MAX = "2." + TAB + "Maximum" + DELIMITER; - public static final String VNICS = "viii." + TAB + "vNICs"; - public static final String VNICS_NAME = "1." + TAB + "Name" + DELIMITER; - public static final String VNICS_PURPOSE = "2." + TAB + "Purpose" + DELIMITER; - public static final String VNICS_INT_EXT = "3." + TAB + "Internal/External" + DELIMITER; - public static final String VNICS_NETWORK = "4." + TAB + "Network" + DELIMITER; - public static final String VNICS_PROTOCOLS = "5." + TAB + "Protocols" + DELIMITER; - public static final String VNICS_IPV4 = "6." + TAB + "IP v4 Required" + DELIMITER; - public static final String VNICS_IPV6 = "7." + TAB + "IP v6 Required" + DELIMITER; - public static final String RECOVERY_DETAILS = "ix." + TAB + "Recovery Details" + DELIMITER; - public static final String RECOVERY_DETAILS_POINT = "1." + TAB + "Recovery Point" + DELIMITER; - public static final String RECOVERY_DETAILS_TIME = "2." + TAB + "Recovery Time" + DELIMITER; - + public static final String QUOTEMARK = "\""; + public static final String SPACE = " "; + public static final String TAB = SPACE + SPACE + SPACE + SPACE; + public static final String NL = System.lineSeparator(); + public static final String DELIMITER = ":"; + public static final String FOUR_TABS = TAB + TAB + TAB + TAB; + public static final String TITLE = "1." + TAB + "VSP Details" + DELIMITER; + public static final String VSP_NAME = "a." + TAB + "Name" + DELIMITER; + public static final String VSP_DESC = "b." + TAB + "Description"; + public static final String VSP_VENDOR = "d." + TAB + "Vendor" + DELIMITER; + public static final String VSP_VERSION = "c." + TAB + "Version" + DELIMITER; + public static final String VSP_CATEGORY = "e." + TAB + "Category" + DELIMITER; + public static final String LICENSE_DETAILS = "f." + TAB + "License Details" + DELIMITER; + public static final String LICENSE_MODEL_VERSION = "i." + TAB + "License Model Version" + DELIMITER; + public static final String LICENSE_AGREEMENT_NAME = "ii." + TAB + "License Agreement Name" + DELIMITER; + public static final String LIST_OF_FEATURE_GROUPS = "iii" + TAB + "List of Feature Groups" + DELIMITER; + public static final String HIGH_AVAILABILITY = "g." + TAB + "High Availability"; + public static final String USING_AVAILABILITY_ZONES = "i." + TAB + "Using Availability " + "Zones" + DELIMITER; + public static final String STORAGE_BACKUP_DETAILS = "h." + TAB + "Storage Data Back-up " + "Details" + DELIMITER; + public static final String IS_DATA_REPLICATION = "i." + TAB + "Data Replication Required?" + DELIMITER; + public static final String DATA_SIZE_TO_REP = "ii." + TAB + " Data Size to replicate in GB" + DELIMITER; + public static final String DATA_REP_FREQUENCY = "iii." + TAB + "Data replication frequency" + DELIMITER; + public static final String DATA_REP_SOURCE = "iv." + TAB + "Replication Source" + DELIMITER; + public static final String DATA_REP_DEST = "v." + TAB + "Replication Destination" + DELIMITER; + public static final String LIST_OF_NETWORKS = "List of Internal Networks";//currently not used + public static final String LIST_OF_VFCS = "3." + TAB + "List of VFCs"; + public static final String FOR_EACH_VFC = "a." + TAB + "For each VFC" + DELIMITER; + public static final String VFC_NAME = "i." + TAB + "VFC Name" + DELIMITER; + public static final String VFC_DESC = "ii." + TAB + "Description" + DELIMITER; + public static final String VFC_IMAGES = "iii." + TAB + "Images" + DELIMITER; + public static final String VFC_COMPUTE = "iv." + TAB + "Compute/VM Characteristics"; + public static final String VFC_COMPUTE_VCPU = "1." + TAB + "vCPU" + DELIMITER; + public static final String VFC_COMPUTE_CPU_OVER_SUBSCRIPTION = "2." + TAB + "CPU " + "over-subscription" + DELIMITER; + public static final String VFC_COMPUTE_MEMORY = "3." + TAB + "Memory" + DELIMITER; + public static final String VFC_COMPUTE_DISK = "4." + TAB + "Disk" + DELIMITER; + public static final String HYPERVISOR_DETAILS = "v." + TAB + "Hypervisor Details"; + public static final String HYPERVISOR_DETAILS_NAME = "1." + TAB + "Name" + DELIMITER; + public static final String HYPERVISOR_DETAILS_DRIVERS = "2." + TAB + "Drivers" + DELIMITER; + public static final String GUEST_OS_DETAILS = "vi." + TAB + "Guest OS Details"; + public static final String GUEST_OS_NAME = "1." + TAB + "Name" + DELIMITER; + public static final String GUEST_OS_BIT_SIZE = "2." + TAB + "Bit Size" + DELIMITER; + public static final String GUEST_OS_TOOLS = "3." + TAB + "Tools" + DELIMITER; + public static final String VFC_INSTANCE_NUMBER = "vii." + TAB + "Number of VFC Instances"; + public static final String VFC_INSTANCE_NUMBER_MIN = "1." + TAB + "Minimum" + DELIMITER; + public static final String VFC_INSTANCE_NUMBER_MAX = "2." + TAB + "Maximum" + DELIMITER; + public static final String VNICS = "viii." + TAB + "vNICs"; + public static final String VNICS_NAME = "1." + TAB + "Name" + DELIMITER; + public static final String VNICS_PURPOSE = "2." + TAB + "Purpose" + DELIMITER; + public static final String VNICS_INT_EXT = "3." + TAB + "Internal/External" + DELIMITER; + public static final String VNICS_NETWORK = "4." + TAB + "Network" + DELIMITER; + public static final String VNICS_PROTOCOLS = "5." + TAB + "Protocols" + DELIMITER; + public static final String VNICS_IPV4 = "6." + TAB + "IP v4 Required" + DELIMITER; + public static final String VNICS_IPV6 = "7." + TAB + "IP v6 Required" + DELIMITER; + public static final String RECOVERY_DETAILS = "ix." + TAB + "Recovery Details" + DELIMITER; + public static final String RECOVERY_DETAILS_POINT = "1." + TAB + "Recovery Point" + DELIMITER; + public static final String RECOVERY_DETAILS_TIME = "2." + TAB + "Recovery Time" + DELIMITER; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java index e69ca8d149..7a50d9aab8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,63 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.DATA_REP_DEST; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.DATA_REP_FREQUENCY; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.DATA_REP_SOURCE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.DATA_SIZE_TO_REP; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.FOR_EACH_VFC; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.GUEST_OS_BIT_SIZE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.GUEST_OS_DETAILS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.GUEST_OS_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.GUEST_OS_TOOLS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HIGH_AVAILABILITY; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HYPERVISOR_DETAILS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HYPERVISOR_DETAILS_DRIVERS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HYPERVISOR_DETAILS_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.IS_DATA_REPLICATION; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.LICENSE_AGREEMENT_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.LICENSE_DETAILS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.LICENSE_MODEL_VERSION; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.LIST_OF_FEATURE_GROUPS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.LIST_OF_VFCS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.NL; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.RECOVERY_DETAILS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.RECOVERY_DETAILS_POINT; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.RECOVERY_DETAILS_TIME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.SPACE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.STORAGE_BACKUP_DETAILS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.TAB; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.TITLE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.USING_AVAILABILITY_ZONES; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_CPU_OVER_SUBSCRIPTION; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_DISK; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_MEMORY; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_VCPU; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_DESC; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_IMAGES; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_INSTANCE_NUMBER; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_INSTANCE_NUMBER_MAX; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_INSTANCE_NUMBER_MIN; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_INT_EXT; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_IPV4; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_IPV6; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_NETWORK; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_PROTOCOLS; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VNICS_PURPOSE; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VSP_CATEGORY; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VSP_DESC; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VSP_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VSP_VENDOR; +import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VSP_VERSION; + +import java.util.List; +import java.util.Optional; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.QuestionnnaireDataServiceFactory; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; @@ -40,223 +94,149 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.G import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.StorageDataReplication; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; -import java.util.Optional; - -import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.*; - /** * @author katyr * @since November 23, 2016 */ - public class TxtInformationArtifactGeneratorImpl implements InformationArtifactGenerator { - private QuestionnaireDataService questionnaireDataService = QuestionnnaireDataServiceFactory - .getInstance().createInterface(); - private StringBuilder textArtifact; - @Override - public String generate(String vspId, Version version) { - InformationArtifactData informationArtifactData = - questionnaireDataService.generateQuestionnaireDataForInformationArtifact(vspId, version); - return createTxtArtifact(informationArtifactData); - } - private String createTxtArtifact(InformationArtifactData informationArtifactData) { - textArtifact = new StringBuilder(); - addVspVlmEntries(informationArtifactData); - addAvailabilityEntries(); - addDataEntries(informationArtifactData); - addEntryWithIndent(LIST_OF_VFCS, "", TAB); - addEntryWithIndent(FOR_EACH_VFC, "", TAB + TAB); - List componentQuestionnaires = - informationArtifactData.getComponentQuestionnaires(); - - for (ComponentQuestionnaire componentQuestionnaire : componentQuestionnaires) { - addEntriesPerComponent(componentQuestionnaire); + private QuestionnaireDataService questionnaireDataService = QuestionnnaireDataServiceFactory.getInstance().createInterface(); + private StringBuilder textArtifact; + static String roundVersionAsNeeded(Version version) { + if (version.isFinal()) { + return version.toString(); + } else { + return String.valueOf(Math.ceil(Double.valueOf(version.toString()))); + } } - List nicQuestionnaires = informationArtifactData.getNicQuestionnaires(); - for (NicQuestionnaire nicQuestionnaire : nicQuestionnaires) { - addEntriesPerNic(nicQuestionnaire); - + @Override + public String generate(String vspId, Version version) { + InformationArtifactData informationArtifactData = questionnaireDataService.generateQuestionnaireDataForInformationArtifact(vspId, version); + return createTxtArtifact(informationArtifactData); } - for (ComponentQuestionnaire componentQuestionnaire : componentQuestionnaires) { - addRecoveryEntriesPerComponent(componentQuestionnaire); - } - return textArtifact.toString(); - - } - - private void addDataEntries(InformationArtifactData informationArtifactData) { - addEntryWithIndent(STORAGE_BACKUP_DETAILS, "", TAB); - - Optional storageDataReplication = - Optional.of(informationArtifactData).map(InformationArtifactData::getVspQuestionnaire) - .map(VspQuestionnaire::getGeneral).map(General::getStorageDataReplication); - storageDataReplication - .ifPresent(replication -> addEntryWithIndent(IS_DATA_REPLICATION, - String.valueOf(replication.isStorageReplicationAcrossRegion()), TAB + TAB)); - - storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_SIZE_TO_REP, - String.valueOf(rep.getStorageReplicationSize()), TAB + TAB)); - - storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_REP_FREQUENCY, - String.valueOf(rep.getStorageReplicationFrequency()), TAB + TAB)); - - storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_REP_SOURCE, - String.valueOf(rep.getStorageReplicationSource()), TAB + TAB)); - - storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_REP_DEST, - String.valueOf(rep.getStorageReplicationDestination()), TAB + TAB)); - } + private String createTxtArtifact(InformationArtifactData informationArtifactData) { + textArtifact = new StringBuilder(); + addVspVlmEntries(informationArtifactData); + addAvailabilityEntries(); + addDataEntries(informationArtifactData); + addEntryWithIndent(LIST_OF_VFCS, "", TAB); + addEntryWithIndent(FOR_EACH_VFC, "", TAB + TAB); + List componentQuestionnaires = informationArtifactData.getComponentQuestionnaires(); + for (ComponentQuestionnaire componentQuestionnaire : componentQuestionnaires) { + addEntriesPerComponent(componentQuestionnaire); + } + List nicQuestionnaires = informationArtifactData.getNicQuestionnaires(); + for (NicQuestionnaire nicQuestionnaire : nicQuestionnaires) { + addEntriesPerNic(nicQuestionnaire); + } + for (ComponentQuestionnaire componentQuestionnaire : componentQuestionnaires) { + addRecoveryEntriesPerComponent(componentQuestionnaire); + } + return textArtifact.toString(); + } - private void addAvailabilityEntries() { - addEntryWithIndent(HIGH_AVAILABILITY, "", TAB); + private void addDataEntries(InformationArtifactData informationArtifactData) { + addEntryWithIndent(STORAGE_BACKUP_DETAILS, "", TAB); + Optional storageDataReplication = Optional.of(informationArtifactData) + .map(InformationArtifactData::getVspQuestionnaire).map(VspQuestionnaire::getGeneral).map(General::getStorageDataReplication); + storageDataReplication.ifPresent( + replication -> addEntryWithIndent(IS_DATA_REPLICATION, String.valueOf(replication.isStorageReplicationAcrossRegion()), TAB + TAB)); + storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_SIZE_TO_REP, String.valueOf(rep.getStorageReplicationSize()), TAB + TAB)); + storageDataReplication + .ifPresent(rep -> addEntryWithIndent(DATA_REP_FREQUENCY, String.valueOf(rep.getStorageReplicationFrequency()), TAB + TAB)); + storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_REP_SOURCE, String.valueOf(rep.getStorageReplicationSource()), TAB + TAB)); + storageDataReplication.ifPresent(rep -> addEntryWithIndent(DATA_REP_DEST, String.valueOf(rep.getStorageReplicationDestination()), TAB + TAB)); + } - Optional availability = - Optional.of(new InformationArtifactData()).map(InformationArtifactData::getVspQuestionnaire) + private void addAvailabilityEntries() { + addEntryWithIndent(HIGH_AVAILABILITY, "", TAB); + Optional availability = Optional.of(new InformationArtifactData()).map(InformationArtifactData::getVspQuestionnaire) .map(VspQuestionnaire::getGeneral).map(General::getAvailability); - availability - .ifPresent(availabilityVal -> addEntryWithIndent(USING_AVAILABILITY_ZONES, String.valueOf( - availabilityVal.isUseAvailabilityZonesForHighAvailability()), TAB + TAB)); - } - - private void addVspVlmEntries(InformationArtifactData informationArtifactData) { - addEntryWithIndent(TITLE, "", ""); - Optional vspDetails = Optional.of(informationArtifactData).map - (InformationArtifactData::getVspDetails); - addEntryWithIndent(VSP_NAME, informationArtifactData.getVspDetails().getName(), TAB); - addEntryWithIndent(VSP_DESC, informationArtifactData.getVspDetails().getDescription(), TAB); - addEntryWithIndent(VSP_VERSION, - roundVersionAsNeeded(informationArtifactData.getVspDetails().getVersion()), TAB); - addEntryWithIndent(VSP_VENDOR, informationArtifactData.getVspDetails().getVendorName(), TAB); - addEntryWithIndent(VSP_CATEGORY, informationArtifactData.getVspDetails().getCategory(), TAB); - addEntryWithIndent(LICENSE_DETAILS, "", TAB); - addEntryWithIndent(LICENSE_MODEL_VERSION, - informationArtifactData.getVspDetails().getVlmVersion() == null - ? "" - : informationArtifactData.getVspDetails().getVlmVersion().toString(), - TAB + TAB); - addEntryWithIndent(LICENSE_AGREEMENT_NAME, informationArtifactData.getVspDetails() - .getLicenseAgreement(), TAB + TAB); - addEntryWithIndent(LIST_OF_FEATURE_GROUPS, "", TAB + TAB); - vspDetails.ifPresent(vspDets -> addListEntriesWithIndent(vspDets - .getFeatureGroups(), TAB + TAB + TAB)); - } - - static String roundVersionAsNeeded(Version version) { - if (version.isFinal()) { - return version.toString(); - } else { - return String.valueOf(Math.ceil(Double.valueOf(version.toString()))); + availability.ifPresent(availabilityVal -> addEntryWithIndent(USING_AVAILABILITY_ZONES, + String.valueOf(availabilityVal.isUseAvailabilityZonesForHighAvailability()), TAB + TAB)); } - } - - private void addRecoveryEntriesPerComponent(ComponentQuestionnaire componentQuestionnaire) { - addEntryWithIndent(RECOVERY_DETAILS, "", TAB + TAB + TAB); - Optional recovery = Optional.of(componentQuestionnaire).map( - ComponentQuestionnaire::getGeneral).map( - org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general - .General::getRecovery); - recovery.ifPresent(recoveryVal -> addEntryWithIndent(RECOVERY_DETAILS_POINT, String.valueOf( - recoveryVal.getPointObjective()), TAB + TAB + TAB + TAB)); - - recovery.ifPresent(recoveryVal -> addEntryWithIndent(RECOVERY_DETAILS_TIME, String.valueOf( - recoveryVal.getTimeObjective()), TAB + TAB + TAB + TAB)); - } - - private void addEntriesPerNic(NicQuestionnaire nicQuestionnaire) { - addEntryWithIndent(VNICS, "", TAB + TAB + TAB); - Optional networkOpt = Optional.of(nicQuestionnaire).map( - NicQuestionnaire::getNetwork); - - networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_NAME, network - .getNetworkDescription(), - TAB + TAB + TAB + TAB)); - networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_PURPOSE, network - .getNetworkDescription(), TAB + TAB + TAB + TAB)); - networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_INT_EXT, network - .getNetworkDescription(), TAB + TAB + TAB + TAB)); - networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_NETWORK, network.toString(), - TAB + TAB + TAB + TAB)); - addEntryWithIndent(VNICS_PROTOCOLS, nicQuestionnaire.getProtocols() == null ? "" : nicQuestionnaire.getProtocols().toString(), - TAB + TAB + TAB + TAB); - - Optional ipconfigOpt = Optional.of(nicQuestionnaire).map - (NicQuestionnaire::getIpConfiguration); - ipconfigOpt.ifPresent(ipconfig -> addEntryWithIndent(VNICS_IPV4, String.valueOf(ipconfig - .isIpv4Required()), TAB + TAB + TAB + TAB)); - ipconfigOpt.ifPresent(ipconfig -> addEntryWithIndent(VNICS_IPV6, String.valueOf(ipconfig - .isIpv6Required()), TAB + TAB + TAB + TAB)); - } - - private void addEntriesPerComponent(ComponentQuestionnaire componentQuestionnaire) { - addEntryWithIndent(VFC_NAME, "", TAB + TAB + TAB); - addEntryWithIndent(VFC_DESC, "", TAB + TAB + TAB); - addEntryWithIndent(VFC_IMAGES, "", TAB + TAB + TAB); - //todo component name +desc +img+vcpu - addEntryWithIndent(VFC_COMPUTE, "", TAB + TAB + TAB); - addEntryWithIndent(VFC_COMPUTE_VCPU, "", TAB + TAB + TAB + TAB); - addEntryWithIndent(VFC_COMPUTE_CPU_OVER_SUBSCRIPTION, "", - TAB + TAB + TAB + TAB); - addEntryWithIndent(VFC_COMPUTE_MEMORY, "", TAB + TAB + TAB + TAB); - addEntryWithIndent(VFC_COMPUTE_DISK, "", TAB + TAB + TAB + TAB); - - addEntryWithIndent(HYPERVISOR_DETAILS, "", TAB + TAB + TAB); - - Optional hypervisorOpt = Optional.of(componentQuestionnaire).map( - ComponentQuestionnaire::getGeneral).map( - org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general - .General::getHypervisor); - hypervisorOpt.ifPresent(hypervisor -> addEntryWithIndent(HYPERVISOR_DETAILS_NAME, hypervisor - .getHypervisor(), TAB - + TAB + TAB + TAB)); - - hypervisorOpt.ifPresent(hypervisor -> addEntryWithIndent(HYPERVISOR_DETAILS_DRIVERS, hypervisor - .getDrivers(), TAB + TAB + TAB + TAB)); - addEntryWithIndent(GUEST_OS_DETAILS, "", TAB + TAB + TAB); - Optional guestOSOptional = Optional.of(componentQuestionnaire).map - (ComponentQuestionnaire::getCompute).map(Compute::getGuestOS); - guestOSOptional.ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_NAME, guestOs.getName(), - TAB + TAB + TAB + TAB)); - - - guestOSOptional - .ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_BIT_SIZE, String.valueOf(guestOs - .getBitSize()), TAB + TAB + TAB + TAB)); - guestOSOptional.ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_TOOLS, guestOs.getTools - (), TAB + TAB + TAB + TAB)); - - addEntryWithIndent(VFC_INSTANCE_NUMBER, "", - TAB + TAB + TAB); - - Optional numVmsOpt = Optional.of(componentQuestionnaire).map - (ComponentQuestionnaire::getCompute).map(Compute::getNumOfVMs); - numVmsOpt.ifPresent(numVms -> addEntryWithIndent(VFC_INSTANCE_NUMBER_MIN, String.valueOf - (numVms.getMinimum()), TAB + TAB + TAB + TAB)); - - numVmsOpt.ifPresent(numVms -> addEntryWithIndent(VFC_INSTANCE_NUMBER_MAX, String.valueOf - (numVms.getMaximum()), TAB + TAB + TAB + TAB)); - } + private void addVspVlmEntries(InformationArtifactData informationArtifactData) { + addEntryWithIndent(TITLE, "", ""); + Optional vspDetails = Optional.of(informationArtifactData).map(InformationArtifactData::getVspDetails); + addEntryWithIndent(VSP_NAME, informationArtifactData.getVspDetails().getName(), TAB); + addEntryWithIndent(VSP_DESC, informationArtifactData.getVspDetails().getDescription(), TAB); + addEntryWithIndent(VSP_VERSION, roundVersionAsNeeded(informationArtifactData.getVspDetails().getVersion()), TAB); + addEntryWithIndent(VSP_VENDOR, informationArtifactData.getVspDetails().getVendorName(), TAB); + addEntryWithIndent(VSP_CATEGORY, informationArtifactData.getVspDetails().getCategory(), TAB); + addEntryWithIndent(LICENSE_DETAILS, "", TAB); + addEntryWithIndent(LICENSE_MODEL_VERSION, + informationArtifactData.getVspDetails().getVlmVersion() == null ? "" : informationArtifactData.getVspDetails().getVlmVersion().toString(), + TAB + TAB); + addEntryWithIndent(LICENSE_AGREEMENT_NAME, informationArtifactData.getVspDetails().getLicenseAgreement(), TAB + TAB); + addEntryWithIndent(LIST_OF_FEATURE_GROUPS, "", TAB + TAB); + vspDetails.ifPresent(vspDets -> addListEntriesWithIndent(vspDets.getFeatureGroups(), TAB + TAB + TAB)); + } - private void addListEntriesWithIndent(List fieldValues, String indent) { - int counter = 1; - if (fieldValues == null) { - return; + private void addRecoveryEntriesPerComponent(ComponentQuestionnaire componentQuestionnaire) { + addEntryWithIndent(RECOVERY_DETAILS, "", TAB + TAB + TAB); + Optional recovery = Optional.of(componentQuestionnaire).map(ComponentQuestionnaire::getGeneral) + .map(org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.General::getRecovery); + recovery.ifPresent( + recoveryVal -> addEntryWithIndent(RECOVERY_DETAILS_POINT, String.valueOf(recoveryVal.getPointObjective()), TAB + TAB + TAB + TAB)); + recovery.ifPresent( + recoveryVal -> addEntryWithIndent(RECOVERY_DETAILS_TIME, String.valueOf(recoveryVal.getTimeObjective()), TAB + TAB + TAB + TAB)); } - for (String fieldValue : fieldValues) { - textArtifact.append(indent).append(counter++).append(".").append(TAB).append(fieldValue) - .append - (NL); + + private void addEntriesPerNic(NicQuestionnaire nicQuestionnaire) { + addEntryWithIndent(VNICS, "", TAB + TAB + TAB); + Optional networkOpt = Optional.of(nicQuestionnaire).map(NicQuestionnaire::getNetwork); + networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_NAME, network.getNetworkDescription(), TAB + TAB + TAB + TAB)); + networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_PURPOSE, network.getNetworkDescription(), TAB + TAB + TAB + TAB)); + networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_INT_EXT, network.getNetworkDescription(), TAB + TAB + TAB + TAB)); + networkOpt.ifPresent(network -> addEntryWithIndent(VNICS_NETWORK, network.toString(), TAB + TAB + TAB + TAB)); + addEntryWithIndent(VNICS_PROTOCOLS, nicQuestionnaire.getProtocols() == null ? "" : nicQuestionnaire.getProtocols().toString(), + TAB + TAB + TAB + TAB); + Optional ipconfigOpt = Optional.of(nicQuestionnaire).map(NicQuestionnaire::getIpConfiguration); + ipconfigOpt.ifPresent(ipconfig -> addEntryWithIndent(VNICS_IPV4, String.valueOf(ipconfig.isIpv4Required()), TAB + TAB + TAB + TAB)); + ipconfigOpt.ifPresent(ipconfig -> addEntryWithIndent(VNICS_IPV6, String.valueOf(ipconfig.isIpv6Required()), TAB + TAB + TAB + TAB)); } - } + private void addEntriesPerComponent(ComponentQuestionnaire componentQuestionnaire) { + addEntryWithIndent(VFC_NAME, "", TAB + TAB + TAB); + addEntryWithIndent(VFC_DESC, "", TAB + TAB + TAB); + addEntryWithIndent(VFC_IMAGES, "", TAB + TAB + TAB); + //todo component name +desc +img+vcpu + addEntryWithIndent(VFC_COMPUTE, "", TAB + TAB + TAB); + addEntryWithIndent(VFC_COMPUTE_VCPU, "", TAB + TAB + TAB + TAB); + addEntryWithIndent(VFC_COMPUTE_CPU_OVER_SUBSCRIPTION, "", TAB + TAB + TAB + TAB); + addEntryWithIndent(VFC_COMPUTE_MEMORY, "", TAB + TAB + TAB + TAB); + addEntryWithIndent(VFC_COMPUTE_DISK, "", TAB + TAB + TAB + TAB); + addEntryWithIndent(HYPERVISOR_DETAILS, "", TAB + TAB + TAB); + Optional hypervisorOpt = Optional.of(componentQuestionnaire).map(ComponentQuestionnaire::getGeneral) + .map(org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.General::getHypervisor); + hypervisorOpt.ifPresent(hypervisor -> addEntryWithIndent(HYPERVISOR_DETAILS_NAME, hypervisor.getHypervisor(), TAB + TAB + TAB + TAB)); + hypervisorOpt.ifPresent(hypervisor -> addEntryWithIndent(HYPERVISOR_DETAILS_DRIVERS, hypervisor.getDrivers(), TAB + TAB + TAB + TAB)); + addEntryWithIndent(GUEST_OS_DETAILS, "", TAB + TAB + TAB); + Optional guestOSOptional = Optional.of(componentQuestionnaire).map(ComponentQuestionnaire::getCompute).map(Compute::getGuestOS); + guestOSOptional.ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_NAME, guestOs.getName(), TAB + TAB + TAB + TAB)); + guestOSOptional.ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_BIT_SIZE, String.valueOf(guestOs.getBitSize()), TAB + TAB + TAB + TAB)); + guestOSOptional.ifPresent(guestOs -> addEntryWithIndent(GUEST_OS_TOOLS, guestOs.getTools(), TAB + TAB + TAB + TAB)); + addEntryWithIndent(VFC_INSTANCE_NUMBER, "", TAB + TAB + TAB); + Optional numVmsOpt = Optional.of(componentQuestionnaire).map(ComponentQuestionnaire::getCompute).map(Compute::getNumOfVMs); + numVmsOpt.ifPresent(numVms -> addEntryWithIndent(VFC_INSTANCE_NUMBER_MIN, String.valueOf(numVms.getMinimum()), TAB + TAB + TAB + TAB)); + numVmsOpt.ifPresent(numVms -> addEntryWithIndent(VFC_INSTANCE_NUMBER_MAX, String.valueOf(numVms.getMaximum()), TAB + TAB + TAB + TAB)); + } + private void addListEntriesWithIndent(List fieldValues, String indent) { + int counter = 1; + if (fieldValues == null) { + return; + } + for (String fieldValue : fieldValues) { + textArtifact.append(indent).append(counter++).append(".").append(TAB).append(fieldValue).append(NL); + } + } - private void addEntryWithIndent(String fieldName, String fieldValue, String indent) { - textArtifact.append(indent).append(fieldName).append(SPACE).append(fieldValue).append(NL); - } + private void addEntryWithIndent(String fieldName, String fieldValue, String indent) { + textArtifact.append(indent).append(fieldName).append(SPACE).append(fieldValue).append(NL); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java index 3af6dfc598..0142091176 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java @@ -13,13 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.quiestionnaire; - +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.vendorsoftwareproduct.dao.*; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ComponentQuestionnaire; @@ -27,67 +37,47 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.NicQuesti import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.VspQuestionnaire; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - /** * Created by TALIO on 11/22/2016 */ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { - private static final ComponentDao componentDao = - ComponentDaoFactory.getInstance().createInterface(); - private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); - private static final VendorSoftwareProductInfoDao vspInfoDao = - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); - @Override - public InformationArtifactData generateQuestionnaireDataForInformationArtifact(String vspId, - Version version) { - VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - Collection componentEntities = componentDao.listQuestionnaires(vspId, version); - Collection nicEntities = nicDao.listByVsp(vspId, version); - VspQuestionnaire vspQuestionnaire = getVspQuestionnaireFromJson(vspId, version); - List componentQuestionnaireList = - getListOfComponentQuestionnaireFromJson(componentEntities); - List nicQuestionnaireList = getListOfNicQuestionnaireFromJson(nicEntities); - return new InformationArtifactData(vspDetails, vspQuestionnaire, componentQuestionnaireList, - nicQuestionnaireList); - } - - private VspQuestionnaire getVspQuestionnaireFromJson(String vspId, Version version) { - VspQuestionnaireEntity vspQuestionnaireEntity = - vspInfoDao.getQuestionnaire(vspId, version); - - if (vspQuestionnaireEntity == null) { - return null; + private static final ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); + private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); + private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); + + @Override + public InformationArtifactData generateQuestionnaireDataForInformationArtifact(String vspId, Version version) { + VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); + Collection componentEntities = componentDao.listQuestionnaires(vspId, version); + Collection nicEntities = nicDao.listByVsp(vspId, version); + VspQuestionnaire vspQuestionnaire = getVspQuestionnaireFromJson(vspId, version); + List componentQuestionnaireList = getListOfComponentQuestionnaireFromJson(componentEntities); + List nicQuestionnaireList = getListOfNicQuestionnaireFromJson(nicEntities); + return new InformationArtifactData(vspDetails, vspQuestionnaire, componentQuestionnaireList, nicQuestionnaireList); } - return JsonUtil - .json2Object(vspQuestionnaireEntity.getQuestionnaireData(), VspQuestionnaire.class); - } - - private List getListOfComponentQuestionnaireFromJson( - Collection entities) { - List componentQuestionnaireList = new ArrayList<>(); - - for (CompositionEntity componentEntity : entities) { - componentQuestionnaireList.add(JsonUtil - .json2Object(componentEntity.getQuestionnaireData(), ComponentQuestionnaire.class)); + private VspQuestionnaire getVspQuestionnaireFromJson(String vspId, Version version) { + VspQuestionnaireEntity vspQuestionnaireEntity = vspInfoDao.getQuestionnaire(vspId, version); + if (vspQuestionnaireEntity == null) { + return null; + } + return JsonUtil.json2Object(vspQuestionnaireEntity.getQuestionnaireData(), VspQuestionnaire.class); } - return componentQuestionnaireList; - } - - private List getListOfNicQuestionnaireFromJson(Collection entities) { - List nicQuestionnaireList = new ArrayList<>(); - - for (NicEntity nicEntity : entities) { - nicQuestionnaireList - .add(JsonUtil.json2Object(nicEntity.getQuestionnaireData(), NicQuestionnaire.class)); + private List getListOfComponentQuestionnaireFromJson(Collection entities) { + List componentQuestionnaireList = new ArrayList<>(); + for (CompositionEntity componentEntity : entities) { + componentQuestionnaireList.add(JsonUtil.json2Object(componentEntity.getQuestionnaireData(), ComponentQuestionnaire.class)); + } + return componentQuestionnaireList; } - return nicQuestionnaireList; - } - + private List getListOfNicQuestionnaireFromJson(Collection entities) { + List nicQuestionnaireList = new ArrayList<>(); + for (NicEntity nicEntity : entities) { + nicQuestionnaireList.add(JsonUtil.json2Object(nicEntity.getQuestionnaireData(), NicQuestionnaire.class)); + } + return nicQuestionnaireList; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java index dc60419973..f50c1339b3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java @@ -12,374 +12,355 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. -*/ - + */ package org.openecomp.sdc.vendorsoftwareproduct.services; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.generator.datatypes.tosca.*; +import org.openecomp.sdc.generator.datatypes.tosca.ComputeFlavor; +import org.openecomp.sdc.generator.datatypes.tosca.DeploymentFlavorModel; +import org.openecomp.sdc.generator.datatypes.tosca.LicenseFlavor; +import org.openecomp.sdc.generator.datatypes.tosca.MultiFlavorVfcImage; +import org.openecomp.sdc.generator.datatypes.tosca.VendorInfo; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupModel; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.*; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.*; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.*; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentComputeAssociation; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.DeploymentFlavor; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Image; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.Compute; import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.image.ImageDetails; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.*; - - public class ManualVspDataCollectionService { - private static final VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao = - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); - private static final DeploymentFlavorDao deploymentFlavorDao = - DeploymentFlavorDaoFactory.getInstance().createInterface(); - private static final ComputeDao computeDao = - ComputeDaoFactory.getInstance().createInterface(); - private static final ImageDao imageDao = - ImageDaoFactory.getInstance().createInterface(); - private static final ComponentDao componentDao = - ComponentDaoFactory.getInstance().createInterface(); - - private static final NicDao nicDao = - NicDaoFactory.getInstance().createInterface(); - private static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); - - private final Logger log = LoggerFactory.getLogger(this.getClass().getName()); - - /** - * Gets vendor name for the vsp. - * - * @param vspId the vsp id - * @param version the version - * @return the release vendor name - */ - public Optional getReleaseVendor(String vspId, Version version) { - String vendorName = null; - VspDetails vspDetails = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); - if (Objects.nonNull(vspDetails)) { - vendorName = vspDetails.getVendorName(); - } - return Optional.ofNullable(vendorName); - } - - /** - * Gets the deployment flavor data for manually onboarded VSPs. - * - * @param vspId the vsp id - * @param version the version - * @return the allowed flavors - */ - public Map getAllowedFlavors(String vspId, Version version) { - Map allowedFlavors = new HashMap<>(); - Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { - for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { - DeploymentFlavor deploymentFlavorCompositionData = - deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + private static final VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance() + .createInterface(); + private static final DeploymentFlavorDao deploymentFlavorDao = DeploymentFlavorDaoFactory.getInstance().createInterface(); + private static final ComputeDao computeDao = ComputeDaoFactory.getInstance().createInterface(); + private static final ImageDao imageDao = ImageDaoFactory.getInstance().createInterface(); + private static final ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); + private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); + private static final VendorLicenseFacade vendorLicenseFacade = VendorLicenseFacadeFactory.getInstance().createInterface(); + private final Logger log = LoggerFactory.getLogger(this.getClass().getName()); + /** + * Gets vendor name for the vsp. + * + * @param vspId the vsp id + * @param version the version + * @return the release vendor name + */ + public Optional getReleaseVendor(String vspId, Version version) { + String vendorName = null; VspDetails vspDetails = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); - String vspVlmId; - Version vlmVersion; if (Objects.nonNull(vspDetails)) { - vspVlmId = vspDetails.getVendorId(); - vlmVersion = vspDetails.getVlmVersion(); - if (StringUtils.isNotEmpty(vspVlmId)) { - DeploymentFlavorModel deploymentFlavorModel = new DeploymentFlavorModel(); - String featureGroupId = deploymentFlavorCompositionData.getFeatureGroupId(); - if (Objects.isNull(featureGroupId)) { - //No feature group associated with deployment flavor. So excluding this deployment - // flavor for Tosca model - continue; - } - //Gather and set License flavor info - LicenseFlavor licenseFlavor = getLicenseFlavor(featureGroupId); - deploymentFlavorModel.setLicense_flavor(licenseFlavor); - //Get sp_part_number - Optional partNumber = getPartNumber(vspVlmId, vlmVersion, featureGroupId); - partNumber.ifPresent(deploymentFlavorModel::setSp_part_number); - //Gather and set Vendor Info - String vendorModel = deploymentFlavorCompositionData.getModel(); - Optional vendorInfo = getVendorInfo(vspVlmId, vendorModel, vlmVersion, - featureGroupId); - vendorInfo.ifPresent(deploymentFlavorModel::setVendor_info); - //Gather and set Compute info - List componentComputeAssociations = - deploymentFlavorCompositionData.getComponentComputeAssociations(); - if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { - for (ComponentComputeAssociation componentComputeAssociation : - componentComputeAssociations) { - String componentId = componentComputeAssociation.getComponentId(); - String computeFlavorId = componentComputeAssociation.getComputeFlavorId(); - Optional computeFlavor = - getComputeFlavor(vspId, version, componentId, computeFlavorId); - computeFlavor.ifPresent(deploymentFlavorModel::setCompute_flavor); - } - } - partNumber.ifPresent(spPartNumber -> allowedFlavors.put(spPartNumber, - deploymentFlavorModel)); - } + vendorName = vspDetails.getVendorName(); } - } + return Optional.ofNullable(vendorName); } - return allowedFlavors; - } - /** - * Gets the component image data for manually onboarded VSPs. - * - * @param vspId the vsp id - * @param version the version - * @return the vsp component images - */ - public Map> getVspComponentImages(String vspId, - Version version) { - Map> vspComponentImages = new HashMap<>(); - Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { - DeploymentFlavor deploymentFlavorCompositionData = - deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + /** + * Gets the deployment flavor data for manually onboarded VSPs. + * + * @param vspId the vsp id + * @param version the version + * @return the allowed flavors + */ + public Map getAllowedFlavors(String vspId, Version version) { + Map allowedFlavors = new HashMap<>(); + Collection deploymentFlavorEntities = deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); + if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { + for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { + DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + VspDetails vspDetails = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); + String vspVlmId; + Version vlmVersion; + if (Objects.nonNull(vspDetails)) { + vspVlmId = vspDetails.getVendorId(); + vlmVersion = vspDetails.getVlmVersion(); + if (StringUtils.isNotEmpty(vspVlmId)) { + DeploymentFlavorModel deploymentFlavorModel = new DeploymentFlavorModel(); + String featureGroupId = deploymentFlavorCompositionData.getFeatureGroupId(); + if (Objects.isNull(featureGroupId)) { + //No feature group associated with deployment flavor. So excluding this deployment - List componentComputeAssociations = - deploymentFlavorCompositionData.getComponentComputeAssociations(); - if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { - for (ComponentComputeAssociation componentComputeAssociation : - componentComputeAssociations) { - String componentId = componentComputeAssociation.getComponentId(); - List componentImages = - getComponentImages(vspId, version, componentId); - if (CollectionUtils.isNotEmpty(componentImages)) { - vspComponentImages.put(componentId, componentImages); - } + // flavor for Tosca model + continue; + } + //Gather and set License flavor info + LicenseFlavor licenseFlavor = getLicenseFlavor(featureGroupId); + deploymentFlavorModel.setLicense_flavor(licenseFlavor); + //Get sp_part_number + Optional partNumber = getPartNumber(vspVlmId, vlmVersion, featureGroupId); + partNumber.ifPresent(deploymentFlavorModel::setSp_part_number); + //Gather and set Vendor Info + String vendorModel = deploymentFlavorCompositionData.getModel(); + Optional vendorInfo = getVendorInfo(vspVlmId, vendorModel, vlmVersion, featureGroupId); + vendorInfo.ifPresent(deploymentFlavorModel::setVendor_info); + //Gather and set Compute info + List componentComputeAssociations = deploymentFlavorCompositionData + .getComponentComputeAssociations(); + if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { + for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { + String componentId = componentComputeAssociation.getComponentId(); + String computeFlavorId = componentComputeAssociation.getComputeFlavorId(); + Optional computeFlavor = getComputeFlavor(vspId, version, componentId, computeFlavorId); + computeFlavor.ifPresent(deploymentFlavorModel::setCompute_flavor); + } + } + partNumber.ifPresent(spPartNumber -> allowedFlavors.put(spPartNumber, deploymentFlavorModel)); + } + } + } } - } + return allowedFlavors; } - return vspComponentImages; - } - /** - * Gets the component data for manually onboarded VSPs. - * - * @param vspId the vsp id - * @param version the version - * @return the vsp components - */ - public Map getVspComponents(String vspId, Version version) { - Map componentIdNameMap = new HashMap<>(); - Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { - DeploymentFlavor deploymentFlavorCompositionData = - deploymentFlavorEntity.getDeploymentFlavorCompositionData(); - - List componentComputeAssociations = - deploymentFlavorCompositionData.getComponentComputeAssociations(); - if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { - for (ComponentComputeAssociation componentComputeAssociation : - componentComputeAssociations) { - String componentId = componentComputeAssociation.getComponentId(); - Optional componentName = getComponentName(vspId, version, componentId); - componentName.ifPresent(name -> componentIdNameMap.put(componentId, name)); + /** + * Gets the component image data for manually onboarded VSPs. + * + * @param vspId the vsp id + * @param version the version + * @return the vsp component images + */ + public Map> getVspComponentImages(String vspId, Version version) { + Map> vspComponentImages = new HashMap<>(); + Collection deploymentFlavorEntities = deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); + for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { + DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + List componentComputeAssociations = deploymentFlavorCompositionData.getComponentComputeAssociations(); + if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { + for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { + String componentId = componentComputeAssociation.getComponentId(); + List componentImages = getComponentImages(vspId, version, componentId); + if (CollectionUtils.isNotEmpty(componentImages)) { + vspComponentImages.put(componentId, componentImages); + } + } + } } - } + return vspComponentImages; } - return componentIdNameMap; - } - /** - * Gets the NIC data for manually onboarded VSPs. - * - * @param vspId the vsp id - * @param version the version - * @return the vsp component nics - */ - public Map> getVspComponentNics(String vspId, Version version) { - Map> vspComponentNics = new HashMap<>(); - Collection deploymentFlavorEntities = - deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { - for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { - DeploymentFlavor deploymentFlavorCompositionData = - deploymentFlavorEntity.getDeploymentFlavorCompositionData(); - if (Objects.nonNull(deploymentFlavorCompositionData)) { - List componentComputeAssociations = - deploymentFlavorCompositionData.getComponentComputeAssociations(); - if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { - for (ComponentComputeAssociation componentComputeAssociation : - componentComputeAssociations) { - String componentId = componentComputeAssociation.getComponentId(); - List componentNics = getComponentNics(vspId, version, componentId); - if (CollectionUtils.isNotEmpty(componentNics)) { - vspComponentNics.put(componentId, componentNics); - } + /** + * Gets the component data for manually onboarded VSPs. + * + * @param vspId the vsp id + * @param version the version + * @return the vsp components + */ + public Map getVspComponents(String vspId, Version version) { + Map componentIdNameMap = new HashMap<>(); + Collection deploymentFlavorEntities = deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); + for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { + DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + List componentComputeAssociations = deploymentFlavorCompositionData.getComponentComputeAssociations(); + if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { + for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { + String componentId = componentComputeAssociation.getComponentId(); + Optional componentName = getComponentName(vspId, version, componentId); + componentName.ifPresent(name -> componentIdNameMap.put(componentId, name)); + } } - } } - } + return componentIdNameMap; } - return vspComponentNics; - } - private List getComponentNics(String vspId, Version version, String componentId) { - List componentNics = new ArrayList<>(); - Collection nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); - if (Objects.nonNull(nics)) { - for (NicEntity nic : nics) { - String nicId = nic.getId(); - NicEntity nicEntity = nicDao.get(new NicEntity(vspId, version, componentId, nicId)); - if (Objects.nonNull(nicEntity) - && Objects.nonNull(nicEntity.getCompositionData())) { - componentNics.add(nicEntity.getNicCompositionData()); + /** + * Gets the NIC data for manually onboarded VSPs. + * + * @param vspId the vsp id + * @param version the version + * @return the vsp component nics + */ + public Map> getVspComponentNics(String vspId, Version version) { + Map> vspComponentNics = new HashMap<>(); + Collection deploymentFlavorEntities = deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); + if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { + for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { + DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); + if (Objects.nonNull(deploymentFlavorCompositionData)) { + List componentComputeAssociations = deploymentFlavorCompositionData + .getComponentComputeAssociations(); + if (CollectionUtils.isNotEmpty(componentComputeAssociations)) { + for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { + String componentId = componentComputeAssociation.getComponentId(); + List componentNics = getComponentNics(vspId, version, componentId); + if (CollectionUtils.isNotEmpty(componentNics)) { + vspComponentNics.put(componentId, componentNics); + } + } + } + } + } } - } + return vspComponentNics; } - return componentNics; - } - private LicenseFlavor getLicenseFlavor(String featureGroupId) { - LicenseFlavor licenseFlavor = new LicenseFlavor(); - licenseFlavor.setFeature_group_uuid(featureGroupId); - return licenseFlavor; - } + private List getComponentNics(String vspId, Version version, String componentId) { + List componentNics = new ArrayList<>(); + Collection nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); + if (Objects.nonNull(nics)) { + for (NicEntity nic : nics) { + String nicId = nic.getId(); + NicEntity nicEntity = nicDao.get(new NicEntity(vspId, version, componentId, nicId)); + if (Objects.nonNull(nicEntity) && Objects.nonNull(nicEntity.getCompositionData())) { + componentNics.add(nicEntity.getNicCompositionData()); + } + } + } + return componentNics; + } - private Optional getPartNumber(String vlmId, Version version, - String featureGroupId) { - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); - if (Objects.nonNull(featureGroup)) { - return Optional.ofNullable(featureGroup.getFeatureGroup().getPartNumber()); + private LicenseFlavor getLicenseFlavor(String featureGroupId) { + LicenseFlavor licenseFlavor = new LicenseFlavor(); + licenseFlavor.setFeature_group_uuid(featureGroupId); + return licenseFlavor; } - return Optional.empty(); - } - private Optional getVendorInfo(String vlmId, String vendorModel, Version version, - String featureGroupId) { - VendorInfo vendorInfo = null; - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); - if (Objects.nonNull(featureGroup)) { - //Process Feature group to get Manufacturer ref no. - String manufacturerReferenceNumber = featureGroup.getEntityManufacturerReferenceNumber(); - vendorInfo = new VendorInfo(); - vendorInfo.setVendor_model(vendorModel); - if (Objects.nonNull(manufacturerReferenceNumber)) { - vendorInfo.setManufacturer_reference_number(manufacturerReferenceNumber); - } + private Optional getPartNumber(String vlmId, Version version, String featureGroupId) { + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); + if (Objects.nonNull(featureGroup)) { + return Optional.ofNullable(featureGroup.getFeatureGroup().getPartNumber()); + } + return Optional.empty(); } - return Optional.ofNullable(vendorInfo); - } - private Optional getComputeFlavor(String vspId, Version version, - String componentId, String computeFlavorId) { - ComputeFlavor computeFlavor = null; - ComputeEntity computeQuestionnaire; - try { - computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, - computeFlavorId); - } catch (Exception ex) { - log.warn("Failed to get QuestionnaireData from computeDao," + - " initializing computeQuestionnaire to null", ex); - computeQuestionnaire = null; + private Optional getVendorInfo(String vlmId, String vendorModel, Version version, String featureGroupId) { + VendorInfo vendorInfo = null; + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); + if (Objects.nonNull(featureGroup)) { + //Process Feature group to get Manufacturer ref no. + String manufacturerReferenceNumber = featureGroup.getEntityManufacturerReferenceNumber(); + vendorInfo = new VendorInfo(); + vendorInfo.setVendor_model(vendorModel); + if (Objects.nonNull(manufacturerReferenceNumber)) { + vendorInfo.setManufacturer_reference_number(manufacturerReferenceNumber); + } + } + return Optional.ofNullable(vendorInfo); } - if (Objects.nonNull(computeQuestionnaire)) { - String computeQuestionnaireData = computeQuestionnaire.getQuestionnaireData(); - if (Objects.nonNull(computeQuestionnaireData)) { - Compute compute; + + private Optional getComputeFlavor(String vspId, Version version, String componentId, String computeFlavorId) { + ComputeFlavor computeFlavor = null; + ComputeEntity computeQuestionnaire; try { - compute = JsonUtil.json2Object(computeQuestionnaireData, Compute.class); + computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, computeFlavorId); } catch (Exception ex) { - log.warn("Failed to convert json value to compute object," + - "initializing compute to null", ex); - compute = null; + log.warn("Failed to get QuestionnaireData from computeDao," + " initializing computeQuestionnaire to null", ex); + computeQuestionnaire = null; } - if (compute != null && Objects.nonNull(compute.getVmSizing())) { - computeFlavor = new ComputeFlavor(); - if (Objects.nonNull(compute.getVmSizing().getNumOfCPUs())) { - computeFlavor.setNum_cpus(compute.getVmSizing().getNumOfCPUs()); - } - if (Objects.nonNull(compute.getVmSizing().getFileSystemSizeGB())) { - computeFlavor.setDisk_size(compute.getVmSizing().getFileSystemSizeGB() + " GB"); - } - if (Objects.nonNull(compute.getVmSizing().getMemoryRAM())) { - computeFlavor.setMem_size(compute.getVmSizing().getMemoryRAM()); - } + if (Objects.nonNull(computeQuestionnaire)) { + String computeQuestionnaireData = computeQuestionnaire.getQuestionnaireData(); + if (Objects.nonNull(computeQuestionnaireData)) { + Compute compute; + try { + compute = JsonUtil.json2Object(computeQuestionnaireData, Compute.class); + } catch (Exception ex) { + log.warn("Failed to convert json value to compute object," + "initializing compute to null", ex); + compute = null; + } + if (compute != null && Objects.nonNull(compute.getVmSizing())) { + computeFlavor = new ComputeFlavor(); + if (Objects.nonNull(compute.getVmSizing().getNumOfCPUs())) { + computeFlavor.setNum_cpus(compute.getVmSizing().getNumOfCPUs()); + } + if (Objects.nonNull(compute.getVmSizing().getFileSystemSizeGB())) { + computeFlavor.setDisk_size(compute.getVmSizing().getFileSystemSizeGB() + " GB"); + } + if (Objects.nonNull(compute.getVmSizing().getMemoryRAM())) { + computeFlavor.setMem_size(compute.getVmSizing().getMemoryRAM()); + } + } + } } - } + return Optional.ofNullable(computeFlavor); } - return Optional.ofNullable(computeFlavor); - } - private FeatureGroupModel getFeatureGroup(String vlmId, Version version, String featureGroupId) { - FeatureGroupEntity fgInput = new FeatureGroupEntity(); - fgInput.setVendorLicenseModelId(vlmId); - fgInput.setVersion(version); - fgInput.setId(featureGroupId); - return vendorLicenseFacade.getFeatureGroupModel(fgInput); - } - - private Optional getComponentName(String vspId, Version version, String componentId) { + private FeatureGroupModel getFeatureGroup(String vlmId, Version version, String featureGroupId) { + FeatureGroupEntity fgInput = new FeatureGroupEntity(); + fgInput.setVendorLicenseModelId(vlmId); + fgInput.setVersion(version); + fgInput.setId(featureGroupId); + return vendorLicenseFacade.getFeatureGroupModel(fgInput); + } - ComponentEntity componentEntity = - componentDao.get(new ComponentEntity(vspId, version, componentId)); - if (Objects.nonNull(componentEntity) - && Objects.nonNull(componentEntity.getComponentCompositionData())) { - ComponentData componentCompositionData = componentEntity.getComponentCompositionData(); - return Optional.ofNullable(componentCompositionData.getDisplayName()); + private Optional getComponentName(String vspId, Version version, String componentId) { + ComponentEntity componentEntity = componentDao.get(new ComponentEntity(vspId, version, componentId)); + if (Objects.nonNull(componentEntity) && Objects.nonNull(componentEntity.getComponentCompositionData())) { + ComponentData componentCompositionData = componentEntity.getComponentCompositionData(); + return Optional.ofNullable(componentCompositionData.getDisplayName()); + } + return Optional.empty(); } - return Optional.empty(); - } - private List getComponentImages(String vspId, Version version, - String componentId) { - List multiFlavorVfcImages = new ArrayList<>(); - MultiFlavorVfcImage multiFlavorVfcImage; - Collection componentImages = - imageDao.list(new ImageEntity(vspId, version, componentId, null)); - if (Objects.nonNull(componentImages)) { - for (ImageEntity componentImage : componentImages) { - ImageEntity imageEntity = imageDao.get(componentImage); - ImageEntity imageQuestionnaireDataEntity = imageDao.getQuestionnaireData(vspId, version, - componentId, componentImage.getId()); - Image imageCompositionData = imageEntity.getImageCompositionData(); - if (Objects.nonNull(imageEntity) - && Objects.nonNull(imageQuestionnaireDataEntity) - && Objects.nonNull(imageCompositionData)) { - ImageDetails imageDetails; - try { - imageDetails = JsonUtil.json2Object(imageQuestionnaireDataEntity - .getQuestionnaireData(), ImageDetails.class); - } catch (Exception ex) { - log.warn("Failed to convert json value to ImageDetails object," + - "initializing imageDetails to null", ex); - imageDetails = null; - } - if (Objects.nonNull(imageDetails) - && Objects.nonNull(imageDetails.getVersion())) { - //Image version is used as a key for the image block - //So excluding the population if questionnaire data is absent or invalid - multiFlavorVfcImage = new MultiFlavorVfcImage(); - multiFlavorVfcImage.setSoftware_version(imageDetails.getVersion()); - if (Objects.nonNull(imageCompositionData.getFileName())) { - multiFlavorVfcImage.setFile_name(imageCompositionData.getFileName()); - } - if (Objects.nonNull(imageDetails.getMd5())) { - multiFlavorVfcImage.setFile_hash(imageDetails.getMd5()); + private List getComponentImages(String vspId, Version version, String componentId) { + List multiFlavorVfcImages = new ArrayList<>(); + MultiFlavorVfcImage multiFlavorVfcImage; + Collection componentImages = imageDao.list(new ImageEntity(vspId, version, componentId, null)); + if (Objects.nonNull(componentImages)) { + for (ImageEntity componentImage : componentImages) { + ImageEntity imageEntity = imageDao.get(componentImage); + ImageEntity imageQuestionnaireDataEntity = imageDao.getQuestionnaireData(vspId, version, componentId, componentImage.getId()); + Image imageCompositionData = imageEntity.getImageCompositionData(); + if (Objects.nonNull(imageEntity) && Objects.nonNull(imageQuestionnaireDataEntity) && Objects.nonNull(imageCompositionData)) { + ImageDetails imageDetails; + try { + imageDetails = JsonUtil.json2Object(imageQuestionnaireDataEntity.getQuestionnaireData(), ImageDetails.class); + } catch (Exception ex) { + log.warn("Failed to convert json value to ImageDetails object," + "initializing imageDetails to null", ex); + imageDetails = null; + } + if (Objects.nonNull(imageDetails) && Objects.nonNull(imageDetails.getVersion())) { + //Image version is used as a key for the image block + + //So excluding the population if questionnaire data is absent or invalid + multiFlavorVfcImage = new MultiFlavorVfcImage(); + multiFlavorVfcImage.setSoftware_version(imageDetails.getVersion()); + if (Objects.nonNull(imageCompositionData.getFileName())) { + multiFlavorVfcImage.setFile_name(imageCompositionData.getFileName()); + } + if (Objects.nonNull(imageDetails.getMd5())) { + multiFlavorVfcImage.setFile_hash(imageDetails.getMd5()); + } + multiFlavorVfcImage.setFile_hash_type("md5"); + multiFlavorVfcImages.add(multiFlavorVfcImage); + } + } } - multiFlavorVfcImage.setFile_hash_type("md5"); - multiFlavorVfcImages.add(multiFlavorVfcImage); - } } - } + return multiFlavorVfcImages; } - return multiFlavorVfcImages; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java index 00781c1512..15289025b1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java @@ -13,10 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl.composition; import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.onap.sdc.tosca.datatypes.model.NodeTemplate; @@ -27,7 +33,11 @@ import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.tosca.datatypes.*; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.errors.ToscaInvalidEntryNotFoundErrorBuilder; import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplateErrorBuilder; import org.openecomp.sdc.tosca.errors.ToscaMissingSubstitutionMappingForReqCapErrorBuilder; @@ -35,427 +45,343 @@ import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; -import org.openecomp.sdc.vendorsoftwareproduct.types.composition.*; - -import java.util.*; -import java.util.stream.Collectors; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Component; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComputeData; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ExtractCompositionDataContext; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Image; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Network; +import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; public class CompositionDataExtractorImpl implements CompositionDataExtractor { - protected static Logger logger; - private static ToscaAnalyzerService toscaAnalyzerService; - static { - logger = LoggerFactory.getLogger(CompositionDataExtractorImpl.class); - toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - } + protected static Logger logger; + private static ToscaAnalyzerService toscaAnalyzerService; - /** - * Extract service composition data composition data. - * - * @param toscaServiceModel the tosca service model - * @return the composition data - */ - public CompositionData extractServiceCompositionData(ToscaServiceModel toscaServiceModel) { - ExtractCompositionDataContext context = new ExtractCompositionDataContext(); - String entryDefinitionServiceTemplateFileName = - toscaServiceModel.getEntryDefinitionServiceTemplate(); - ServiceTemplate entryDefinitionServiceTemplate = - toscaServiceModel.getServiceTemplates().get(entryDefinitionServiceTemplateFileName); - extractServiceCompositionData(entryDefinitionServiceTemplateFileName, - entryDefinitionServiceTemplate, toscaServiceModel, context); - - CompositionData compositionData = new CompositionData(); - compositionData.setNetworks(context.getNetworks()); - compositionData.setComponents(context.getComponents()); - return compositionData; - } - - private void extractServiceCompositionData(String serviceTemplateFileName, - ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel, - ExtractCompositionDataContext context) { - if (context.getHandledServiceTemplates().contains(serviceTemplateFileName)) { - return; + static { + logger = LoggerFactory.getLogger(CompositionDataExtractorImpl.class); + toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); } - context.addNetworks(extractNetworks(serviceTemplate, toscaServiceModel)); - extractComponents(serviceTemplate, toscaServiceModel, context); - handleSubstitution(serviceTemplate, toscaServiceModel, context); - context.addHandledServiceTemplates(serviceTemplateFileName); - } - private void handleSubstitution(ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel, - ExtractCompositionDataContext context) { - Map substitutableNodeTemplates = - toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplate); - - if (substitutableNodeTemplates != null) { - for (String substitutableNodeTemplateId : substitutableNodeTemplates.keySet()) { - handleSubstitutableNodeTemplate(serviceTemplate, toscaServiceModel, - substitutableNodeTemplateId, - substitutableNodeTemplates.get(substitutableNodeTemplateId), context); - } + /** + * Extract service composition data composition data. + * + * @param toscaServiceModel the tosca service model + * @return the composition data + */ + public CompositionData extractServiceCompositionData(ToscaServiceModel toscaServiceModel) { + ExtractCompositionDataContext context = new ExtractCompositionDataContext(); + String entryDefinitionServiceTemplateFileName = toscaServiceModel.getEntryDefinitionServiceTemplate(); + ServiceTemplate entryDefinitionServiceTemplate = toscaServiceModel.getServiceTemplates().get(entryDefinitionServiceTemplateFileName); + extractServiceCompositionData(entryDefinitionServiceTemplateFileName, entryDefinitionServiceTemplate, toscaServiceModel, context); + CompositionData compositionData = new CompositionData(); + compositionData.setNetworks(context.getNetworks()); + compositionData.setComponents(context.getComponents()); + return compositionData; } - } - private void handleSubstitutableNodeTemplate(ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel, - String substitutableNodeTemplateId, - NodeTemplate substitutableNodeTemplate, - ExtractCompositionDataContext context) { - ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - Optional substituteServiceTemplateFileName = toscaAnalyzerService - .getSubstituteServiceTemplateName(substitutableNodeTemplateId, substitutableNodeTemplate); - if (!substituteServiceTemplateFileName.isPresent()) { - throw new CoreException( - new ToscaInvalidSubstituteNodeTemplateErrorBuilder(substitutableNodeTemplateId).build()); - } - if (context.getHandledServiceTemplates().contains(substituteServiceTemplateFileName.get())) { - //each substitution is should be handled once, and will get the connection to the upper - // service level according to the first one which was processed - return; - } - - ServiceTemplate substituteServiceTemplate = - toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateFileName.get()); - extractServiceCompositionData(substituteServiceTemplateFileName.get(), - substituteServiceTemplate, toscaServiceModel, context); - - List> substitutableRequirements = - substitutableNodeTemplate.getRequirements(); - - if (CollectionUtils.isEmpty(substitutableRequirements)) { - return; + private void extractServiceCompositionData(String serviceTemplateFileName, ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, + ExtractCompositionDataContext context) { + if (context.getHandledServiceTemplates().contains(serviceTemplateFileName)) { + return; + } + context.addNetworks(extractNetworks(serviceTemplate, toscaServiceModel)); + extractComponents(serviceTemplate, toscaServiceModel, context); + handleSubstitution(serviceTemplate, toscaServiceModel, context); + context.addHandledServiceTemplates(serviceTemplateFileName); } - for (Map substitutableReq : substitutableRequirements) { - substitutableReq.keySet().stream().filter(reqId -> { - RequirementAssignment reqAssignment = toscaExtensionYamlUtil - .yamlToObject(toscaExtensionYamlUtil.objectToYaml(substitutableReq.get(reqId)), - RequirementAssignment.class); - return isLinkToNetworkRequirementAssignment(reqAssignment); - }).forEach(reqId -> { - RequirementAssignment linkToNetworkRequirement = toscaExtensionYamlUtil - .yamlToObject(toscaExtensionYamlUtil.objectToYaml(substitutableReq.get(reqId)), - RequirementAssignment.class); - String connectedNodeId = linkToNetworkRequirement.getNode(); - Optional connectedNodeTemplate = - toscaAnalyzerService.getNodeTemplateById(serviceTemplate, connectedNodeId); - - if (connectedNodeTemplate.isPresent() && toscaAnalyzerService - .isTypeOf(connectedNodeTemplate.get(), ToscaNodeType.NATIVE_NETWORK, - serviceTemplate, toscaServiceModel)) { - Optional> mappedNodeTemplate = toscaAnalyzerService - .getSubstitutionMappedNodeTemplateByExposedReq( - substituteServiceTemplateFileName.get(), substituteServiceTemplate, reqId); - if (!mappedNodeTemplate.isPresent()) { - throw new CoreException(new ToscaMissingSubstitutionMappingForReqCapErrorBuilder( - ToscaMissingSubstitutionMappingForReqCapErrorBuilder.MappingExposedEntry - .REQUIREMENT, connectedNodeId).build()); - } - - if (toscaAnalyzerService.isTypeOf(mappedNodeTemplate.get().getValue(), - ToscaNodeType.NATIVE_NETWORK_PORT, serviceTemplate, - toscaServiceModel)) { - Nic port = context.getNics().get(mappedNodeTemplate.get().getKey()); - if (port != null) { - port.setNetworkName(connectedNodeId); - } else { - logger.warn( - "Different ports define for the same component which is used in different " - + "substitution service templates."); + private void handleSubstitution(ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, ExtractCompositionDataContext context) { + Map substitutableNodeTemplates = toscaAnalyzerService.getSubstitutableNodeTemplates(serviceTemplate); + if (substitutableNodeTemplates != null) { + for (String substitutableNodeTemplateId : substitutableNodeTemplates.keySet()) { + handleSubstitutableNodeTemplate(serviceTemplate, toscaServiceModel, substitutableNodeTemplateId, + substitutableNodeTemplates.get(substitutableNodeTemplateId), context); } - } - } else if (!connectedNodeTemplate.isPresent()) { - throw new CoreException( - new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", connectedNodeId).build()); } - }); } - } - private boolean isLinkToNetworkRequirementAssignment(RequirementAssignment requirement) { - return toscaAnalyzerService.isDesiredRequirementAssignment(requirement, - ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, null, - ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); - } - - - private void connectPortToNetwork(Nic port, NodeTemplate portNodeTemplate) { - List linkRequirementsToNetwork = - toscaAnalyzerService.getRequirements(portNodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID); + private void handleSubstitutableNodeTemplate(ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, + String substitutableNodeTemplateId, NodeTemplate substitutableNodeTemplate, + ExtractCompositionDataContext context) { + ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); + Optional substituteServiceTemplateFileName = toscaAnalyzerService + .getSubstituteServiceTemplateName(substitutableNodeTemplateId, substitutableNodeTemplate); + if (!substituteServiceTemplateFileName.isPresent()) { + throw new CoreException(new ToscaInvalidSubstituteNodeTemplateErrorBuilder(substitutableNodeTemplateId).build()); + } + if (context.getHandledServiceTemplates().contains(substituteServiceTemplateFileName.get())) { + //each substitution is should be handled once, and will get the connection to the upper - //port is connected to one network - for (RequirementAssignment linkRequirementToNetwork : linkRequirementsToNetwork) { - port.setNetworkName(linkRequirementToNetwork.getNode()); + // service level according to the first one which was processed + return; + } + ServiceTemplate substituteServiceTemplate = toscaServiceModel.getServiceTemplates().get(substituteServiceTemplateFileName.get()); + extractServiceCompositionData(substituteServiceTemplateFileName.get(), substituteServiceTemplate, toscaServiceModel, context); + List> substitutableRequirements = substitutableNodeTemplate.getRequirements(); + if (CollectionUtils.isEmpty(substitutableRequirements)) { + return; + } + for (Map substitutableReq : substitutableRequirements) { + substitutableReq.keySet().stream().filter(reqId -> { + RequirementAssignment reqAssignment = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(substitutableReq.get(reqId)), RequirementAssignment.class); + return isLinkToNetworkRequirementAssignment(reqAssignment); + }).forEach(reqId -> { + RequirementAssignment linkToNetworkRequirement = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(substitutableReq.get(reqId)), RequirementAssignment.class); + String connectedNodeId = linkToNetworkRequirement.getNode(); + Optional connectedNodeTemplate = toscaAnalyzerService.getNodeTemplateById(serviceTemplate, connectedNodeId); + if (connectedNodeTemplate.isPresent() && toscaAnalyzerService + .isTypeOf(connectedNodeTemplate.get(), ToscaNodeType.NATIVE_NETWORK, serviceTemplate, toscaServiceModel)) { + Optional> mappedNodeTemplate = toscaAnalyzerService + .getSubstitutionMappedNodeTemplateByExposedReq(substituteServiceTemplateFileName.get(), substituteServiceTemplate, reqId); + if (!mappedNodeTemplate.isPresent()) { + throw new CoreException(new ToscaMissingSubstitutionMappingForReqCapErrorBuilder( + ToscaMissingSubstitutionMappingForReqCapErrorBuilder.MappingExposedEntry.REQUIREMENT, connectedNodeId).build()); + } + if (toscaAnalyzerService + .isTypeOf(mappedNodeTemplate.get().getValue(), ToscaNodeType.NATIVE_NETWORK_PORT, serviceTemplate, toscaServiceModel)) { + Nic port = context.getNics().get(mappedNodeTemplate.get().getKey()); + if (port != null) { + port.setNetworkName(connectedNodeId); + } else { + logger.warn( + "Different ports define for the same component which is used in different " + "substitution service templates."); + } + } + } else if (!connectedNodeTemplate.isPresent()) { + throw new CoreException(new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", connectedNodeId).build()); + } + }); + } } - } - /* - return Map with key - compute node template id, value - list of connected port node template id - */ - private Map> getComputeToPortsConnection( - Map portNodeTemplates) { - Map> computeToPortConnection = new HashMap<>(); - if (MapUtils.isEmpty(portNodeTemplates)) { - return computeToPortConnection; + private boolean isLinkToNetworkRequirementAssignment(RequirementAssignment requirement) { + return toscaAnalyzerService.isDesiredRequirementAssignment(requirement, ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, null, + ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); } - for (String portId : portNodeTemplates.keySet()) { - List bindingRequirementsToCompute = toscaAnalyzerService - .getRequirements(portNodeTemplates.get(portId), ToscaConstants.BINDING_REQUIREMENT_ID); - for (RequirementAssignment bindingRequirementToCompute : bindingRequirementsToCompute) { - computeToPortConnection - .putIfAbsent(bindingRequirementToCompute.getNode(), new ArrayList<>()); - computeToPortConnection.get(bindingRequirementToCompute.getNode()).add(portId); - } - } - return computeToPortConnection; - } - private void extractComponents(ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel, - ExtractCompositionDataContext context) { - Map computeNodeTemplates = toscaAnalyzerService - .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_COMPUTE, - toscaServiceModel); - if (MapUtils.isEmpty(computeNodeTemplates)) { - return; + private void connectPortToNetwork(Nic port, NodeTemplate portNodeTemplate) { + List linkRequirementsToNetwork = toscaAnalyzerService + .getRequirements(portNodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID); + //port is connected to one network + for (RequirementAssignment linkRequirementToNetwork : linkRequirementsToNetwork) { + port.setNetworkName(linkRequirementToNetwork.getNode()); + } } - Map> imageNodeTemplates = getComponentImages(computeNodeTemplates, - toscaServiceModel); - Map> computeFlavorNodeTemplates = - getComponentComputeFlavor(computeNodeTemplates, toscaServiceModel); - Map portNodeTemplates = toscaAnalyzerService - .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_NETWORK_PORT, - toscaServiceModel); - Map> computeToPortsConnection = - getComputeToPortsConnection(portNodeTemplates); - Map> computesGroupedByType = - getNodeTemplatesGroupedByType(computeNodeTemplates); - computesGroupedByType.keySet() - .stream() - .filter(nodeType -> - !context.getCreatedComponents().contains(nodeType)) - .forEach(nodeType -> extractComponent(serviceTemplate, computeToPortsConnection, - computesGroupedByType, imageNodeTemplates, computeFlavorNodeTemplates, nodeType, - context)); - } - - private Map> getComponentImages(Map - computeNodeTemplates, - ToscaServiceModel toscaServiceModel) { - return getComponentProperty(ToscaConstants.COMPUTE_IMAGE, computeNodeTemplates, toscaServiceModel); - } - - private Map> getComponentComputeFlavor(Map - computeNodeTemplates, - ToscaServiceModel toscaServiceModel) { - return getComponentProperty(ToscaConstants.COMPUTE_FLAVOR, computeNodeTemplates, toscaServiceModel); - } - - private Map> getComponentProperty(String propertyName, - Map computeNodeTemplates, - ToscaServiceModel toscaServiceModel) { - Map> componentPropertyValues = new HashMap<>(); - for (String component : computeNodeTemplates.keySet()) { - List computes = new ArrayList<>(); - Map properties = computeNodeTemplates.get(component).getProperties(); - - if(MapUtils.isEmpty(properties)){ - continue; - } - - List computesList = properties.entrySet() - .stream() - .filter(map -> map.getKey().equals(propertyName)) - .map(Map.Entry::getValue) - .collect(Collectors.toList()); - for (Object obj : computesList) { - if (obj instanceof String) { - computes.add((String) obj); - } else { - Map objMap = new ObjectMapper().convertValue(obj, Map.class); - computes.add(getInputs(toscaServiceModel, objMap.get("get_input"))); + /* + return Map with key - compute node template id, value - list of connected port node template id + */ + private Map> getComputeToPortsConnection(Map portNodeTemplates) { + Map> computeToPortConnection = new HashMap<>(); + if (MapUtils.isEmpty(portNodeTemplates)) { + return computeToPortConnection; } - } - componentPropertyValues.put(component,computes); + for (String portId : portNodeTemplates.keySet()) { + List bindingRequirementsToCompute = toscaAnalyzerService + .getRequirements(portNodeTemplates.get(portId), ToscaConstants.BINDING_REQUIREMENT_ID); + for (RequirementAssignment bindingRequirementToCompute : bindingRequirementsToCompute) { + computeToPortConnection.putIfAbsent(bindingRequirementToCompute.getNode(), new ArrayList<>()); + computeToPortConnection.get(bindingRequirementToCompute.getNode()).add(portId); + } + } + return computeToPortConnection; } - return componentPropertyValues; - } - - private String getInputs(ToscaServiceModel toscaServiceModel, String inputValue) { - String mainTemplate = toscaServiceModel.getEntryDefinitionServiceTemplate(); - List toscaServiceTemplates = toscaServiceModel.getServiceTemplates().entrySet() - .stream() - .filter(map -> map.getKey().equals(mainTemplate)) - .map(Map.Entry::getValue) - .collect(Collectors.toList()); - ServiceTemplate serviceTemplate = toscaServiceTemplates.get(0); - if (Objects.nonNull(serviceTemplate.getTopology_template()) - && MapUtils.isNotEmpty(serviceTemplate.getTopology_template().getInputs())) { - for (Map.Entry inputEntry : serviceTemplate - .getTopology_template().getInputs().entrySet()) { - if (inputEntry.getKey().equals(inputValue)) { - String value; - try { - value= (String) inputEntry.getValue().get_default(); - } catch (Exception e) { - logger.debug(e.getMessage(), e); - value = inputEntry.getValue().get_default().toString(); - } - return value; + private void extractComponents(ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, ExtractCompositionDataContext context) { + Map computeNodeTemplates = toscaAnalyzerService + .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_COMPUTE, toscaServiceModel); + if (MapUtils.isEmpty(computeNodeTemplates)) { + return; } - } + Map> imageNodeTemplates = getComponentImages(computeNodeTemplates, toscaServiceModel); + Map> computeFlavorNodeTemplates = getComponentComputeFlavor(computeNodeTemplates, toscaServiceModel); + Map portNodeTemplates = toscaAnalyzerService + .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_NETWORK_PORT, toscaServiceModel); + Map> computeToPortsConnection = getComputeToPortsConnection(portNodeTemplates); + Map> computesGroupedByType = getNodeTemplatesGroupedByType(computeNodeTemplates); + computesGroupedByType.keySet().stream().filter(nodeType -> !context.getCreatedComponents().contains(nodeType)).forEach( + nodeType -> extractComponent(serviceTemplate, computeToPortsConnection, computesGroupedByType, imageNodeTemplates, + computeFlavorNodeTemplates, nodeType, context)); } - return inputValue; - } - - private void extractComponent(ServiceTemplate serviceTemplate, - Map> computeToPortsConnection, - Map> computesGroupedByType, - Map> imageList, - Map> computeFlavorNodeTemplates, - String computeNodeType, - ExtractCompositionDataContext context) { - ComponentData component = new ComponentData(); - component.setName(computeNodeType); - component.setDisplayName(getComponentDisplayName(component.getName())); - Component componentModel = new Component(); - componentModel.setData(component); - - String computeId = computesGroupedByType.get(computeNodeType).get(0); - List connectedPortIds = computeToPortsConnection.get(computeId); - List images = imageList.get(computeId); - List computeFlavors = computeFlavorNodeTemplates.get(computeId); - if (CollectionUtils.isNotEmpty(connectedPortIds)) { - componentModel.setNics(new ArrayList<>()); - componentModel.setImages(new ArrayList<>()); - componentModel.setCompute(new ArrayList<>()); - - connectedPortIds.forEach(portId -> { - Nic port = extractPort(serviceTemplate, portId); - componentModel.getNics().add(port); - context.addNic(portId, port); - }); - - if (CollectionUtils.isNotEmpty(images)) { - images.forEach(image -> { - Image img = new Image(image); - componentModel.getImages().add(img); - context.addImage(image, img); - }); - } - - if (CollectionUtils.isNotEmpty(computeFlavors)) { - computeFlavors.forEach(flavor -> { - ComputeData computeFlavor = new ComputeData(flavor); - componentModel.getCompute().add(computeFlavor); - context.addCompute(flavor, computeFlavor); - }); - } + private Map> getComponentImages(Map computeNodeTemplates, ToscaServiceModel toscaServiceModel) { + return getComponentProperty(ToscaConstants.COMPUTE_IMAGE, computeNodeTemplates, toscaServiceModel); } - context.addComponent(componentModel); - context.getCreatedComponents().add(computeNodeType); - } - private Nic extractPort(ServiceTemplate serviceTemplate, String portNodeTemplateId) { - Optional portNodeTemplate = - toscaAnalyzerService.getNodeTemplateById(serviceTemplate, portNodeTemplateId); - if (portNodeTemplate.isPresent()) { - Nic port = new Nic(); - port.setName(portNodeTemplateId); - connectPortToNetwork(port, portNodeTemplate.get()); - return port; - } else { - throw new CoreException( - new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", portNodeTemplateId).build()); + private Map> getComponentComputeFlavor(Map computeNodeTemplates, ToscaServiceModel toscaServiceModel) { + return getComponentProperty(ToscaConstants.COMPUTE_FLAVOR, computeNodeTemplates, toscaServiceModel); } - } - private Map> getNodeTemplatesGroupedByType( - Map nodeTemplates) { - Map> nodeTemplatesGrouped = - new HashMap<>(); //key - node type, value - list of node ids with this type - for (String nodeId : nodeTemplates.keySet()) { - String nodeType = nodeTemplates.get(nodeId).getType(); - nodeTemplatesGrouped.putIfAbsent(nodeType, new ArrayList<>()); - nodeTemplatesGrouped.get(nodeType).add(nodeId); + private Map> getComponentProperty(String propertyName, Map computeNodeTemplates, + ToscaServiceModel toscaServiceModel) { + Map> componentPropertyValues = new HashMap<>(); + for (String component : computeNodeTemplates.keySet()) { + List computes = new ArrayList<>(); + Map properties = computeNodeTemplates.get(component).getProperties(); + if (MapUtils.isEmpty(properties)) { + continue; + } + List computesList = properties.entrySet().stream().filter(map -> map.getKey().equals(propertyName)).map(Map.Entry::getValue) + .collect(Collectors.toList()); + for (Object obj : computesList) { + if (obj instanceof String) { + computes.add((String) obj); + } else { + Map objMap = new ObjectMapper().convertValue(obj, Map.class); + computes.add(getInputs(toscaServiceModel, objMap.get("get_input"))); + } + } + componentPropertyValues.put(component, computes); + } + return componentPropertyValues; } - return nodeTemplatesGrouped; - } - private List extractNetworks(ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel) { - List networks = new ArrayList<>(); - Map networkNodeTemplates = toscaAnalyzerService - .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_NETWORK, - toscaServiceModel); - if (MapUtils.isEmpty(networkNodeTemplates)) { - return networks; - } - for (String networkId : networkNodeTemplates.keySet()) { - Network network = new Network(); - network.setName(networkId); - Optional networkDhcpValue = - getNetworkDhcpValue(serviceTemplate, networkNodeTemplates.get(networkId)); - network.setDhcp(networkDhcpValue.orElse(true)); - networks.add(network); + private String getInputs(ToscaServiceModel toscaServiceModel, String inputValue) { + String mainTemplate = toscaServiceModel.getEntryDefinitionServiceTemplate(); + List toscaServiceTemplates = toscaServiceModel.getServiceTemplates().entrySet().stream() + .filter(map -> map.getKey().equals(mainTemplate)).map(Map.Entry::getValue).collect(Collectors.toList()); + ServiceTemplate serviceTemplate = toscaServiceTemplates.get(0); + if (Objects.nonNull(serviceTemplate.getTopology_template()) && MapUtils.isNotEmpty(serviceTemplate.getTopology_template().getInputs())) { + for (Map.Entry inputEntry : serviceTemplate.getTopology_template().getInputs().entrySet()) { + if (inputEntry.getKey().equals(inputValue)) { + String value; + try { + value = (String) inputEntry.getValue().get_default(); + } catch (Exception e) { + logger.debug(e.getMessage(), e); + value = inputEntry.getValue().get_default().toString(); + } + return value; + } + } + } + return inputValue; } - return networks; - } - //dhcp default value is true - private Optional getNetworkDhcpValue(ServiceTemplate serviceTemplate, - NodeTemplate networkNodeTemplate) { - if (networkNodeTemplate == null) { - return Optional.empty(); - } - if (networkNodeTemplate.getProperties() == null - || networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME) - == null) { - return Optional.of(true); + private void extractComponent(ServiceTemplate serviceTemplate, Map> computeToPortsConnection, + Map> computesGroupedByType, Map> imageList, + Map> computeFlavorNodeTemplates, String computeNodeType, + ExtractCompositionDataContext context) { + ComponentData component = new ComponentData(); + component.setName(computeNodeType); + component.setDisplayName(getComponentDisplayName(component.getName())); + Component componentModel = new Component(); + componentModel.setData(component); + String computeId = computesGroupedByType.get(computeNodeType).get(0); + List connectedPortIds = computeToPortsConnection.get(computeId); + List images = imageList.get(computeId); + List computeFlavors = computeFlavorNodeTemplates.get(computeId); + if (CollectionUtils.isNotEmpty(connectedPortIds)) { + componentModel.setNics(new ArrayList<>()); + componentModel.setImages(new ArrayList<>()); + componentModel.setCompute(new ArrayList<>()); + connectedPortIds.forEach(portId -> { + Nic port = extractPort(serviceTemplate, portId); + componentModel.getNics().add(port); + context.addNic(portId, port); + }); + if (CollectionUtils.isNotEmpty(images)) { + images.forEach(image -> { + Image img = new Image(image); + componentModel.getImages().add(img); + context.addImage(image, img); + }); + } + if (CollectionUtils.isNotEmpty(computeFlavors)) { + computeFlavors.forEach(flavor -> { + ComputeData computeFlavor = new ComputeData(flavor); + componentModel.getCompute().add(computeFlavor); + context.addCompute(flavor, computeFlavor); + }); + } + } + context.addComponent(componentModel); + context.getCreatedComponents().add(computeNodeType); } - Object dhcp = - networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME); - if (dhcp instanceof String) { - return Optional.of(Boolean.valueOf((String) dhcp)); - } else if (dhcp instanceof Boolean) { - return Optional.of((Boolean) dhcp); - } else if (dhcp instanceof Map) { - String inputParameterName = - (String) ((Map) dhcp).get(ToscaFunctions.GET_INPUT.getFunctionName()); - if (inputParameterName != null) { - ParameterDefinition inputParameterDefinition = - serviceTemplate.getTopology_template().getInputs().get(inputParameterName); - if (inputParameterDefinition != null) { - if (inputParameterDefinition.get_default() != null) { - return Optional.of(Boolean.valueOf(inputParameterDefinition.get_default().toString())); - } + private Nic extractPort(ServiceTemplate serviceTemplate, String portNodeTemplateId) { + Optional portNodeTemplate = toscaAnalyzerService.getNodeTemplateById(serviceTemplate, portNodeTemplateId); + if (portNodeTemplate.isPresent()) { + Nic port = new Nic(); + port.setName(portNodeTemplateId); + connectPortToNetwork(port, portNodeTemplate.get()); + return port; } else { - throw new CoreException( - new ToscaInvalidEntryNotFoundErrorBuilder("Input Parameter", inputParameterName) - .build()); + throw new CoreException(new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", portNodeTemplateId).build()); } - } } - return Optional.of(true); - } - @Override - public String getComponentDisplayName(String componentName) { - if (componentName == null) { - return null; + private Map> getNodeTemplatesGroupedByType(Map nodeTemplates) { + Map> nodeTemplatesGrouped = + new HashMap<>(); //key - node type, value - list of node ids with this type + for (String nodeId : nodeTemplates.keySet()) { + String nodeType = nodeTemplates.get(nodeId).getType(); + nodeTemplatesGrouped.putIfAbsent(nodeType, new ArrayList<>()); + nodeTemplatesGrouped.get(nodeType).add(nodeId); + } + return nodeTemplatesGrouped; } - String delimiterChar = "."; - if (componentName.contains(delimiterChar)) { - return componentName.substring(componentName.lastIndexOf(delimiterChar) + 1); + + private List extractNetworks(ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { + List networks = new ArrayList<>(); + Map networkNodeTemplates = toscaAnalyzerService + .getNodeTemplatesByType(serviceTemplate, ToscaNodeType.NATIVE_NETWORK, toscaServiceModel); + if (MapUtils.isEmpty(networkNodeTemplates)) { + return networks; + } + for (String networkId : networkNodeTemplates.keySet()) { + Network network = new Network(); + network.setName(networkId); + Optional networkDhcpValue = getNetworkDhcpValue(serviceTemplate, networkNodeTemplates.get(networkId)); + network.setDhcp(networkDhcpValue.orElse(true)); + networks.add(network); + } + return networks; } - return componentName; - } + //dhcp default value is true + private Optional getNetworkDhcpValue(ServiceTemplate serviceTemplate, NodeTemplate networkNodeTemplate) { + if (networkNodeTemplate == null) { + return Optional.empty(); + } + if (networkNodeTemplate.getProperties() == null + || networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME) == null) { + return Optional.of(true); + } + Object dhcp = networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME); + if (dhcp instanceof String) { + return Optional.of(Boolean.valueOf((String) dhcp)); + } else if (dhcp instanceof Boolean) { + return Optional.of((Boolean) dhcp); + } else if (dhcp instanceof Map) { + String inputParameterName = (String) ((Map) dhcp).get(ToscaFunctions.GET_INPUT.getFunctionName()); + if (inputParameterName != null) { + ParameterDefinition inputParameterDefinition = serviceTemplate.getTopology_template().getInputs().get(inputParameterName); + if (inputParameterDefinition != null) { + if (inputParameterDefinition.get_default() != null) { + return Optional.of(Boolean.valueOf(inputParameterDefinition.get_default().toString())); + } + } else { + throw new CoreException(new ToscaInvalidEntryNotFoundErrorBuilder("Input Parameter", inputParameterName).build()); + } + } + } + return Optional.of(true); + } + @Override + public String getComponentDisplayName(String componentName) { + if (componentName == null) { + return null; + } + String delimiterChar = "."; + if (componentName.contains(delimiterChar)) { + return componentName.substring(componentName.lastIndexOf(delimiterChar) + 1); + } + return componentName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIServiceImpl.java index 951cfc7d1f..258b058df7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/etsi/ETSIServiceImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl.etsi; import static org.openecomp.sdc.tosca.csar.CSARConstants.ARTIFACTS_FOLDER; @@ -63,7 +62,6 @@ import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; public class ETSIServiceImpl implements ETSIService { private static final Logger LOGGER = LoggerFactory.getLogger(ETSIServiceImpl.class); - private final NonManoConfiguration nonManoConfiguration; public ETSIServiceImpl() { @@ -99,25 +97,19 @@ public class ETSIServiceImpl implements ETSIService { .forEach(manifestNonManoSourceEntry -> { final NonManoFolderType nonManoFolderType = nonManoKeyFolderMapping.get(manifestNonManoSourceEntry.getKey()); final List nonManoFileList = manifestNonManoSourceEntry.getValue(); - final Map actualFromToPathMap = nonManoFileList.stream() - .map(nonManoFilePath -> { - final Path normalizedFilePath = resolveNonManoFilePath(originalManifestPath, nonManoFilePath); - final Optional changedPath = updateNonManoPathInHandler(handler, nonManoFolderType, normalizedFilePath); - if (changedPath.isPresent()) { - final Map fromAndToPathMap = new HashMap<>(); - fromAndToPathMap.put(nonManoFilePath, Paths.get(ARTIFACTS_FOLDER).resolve(changedPath.get())); - return fromAndToPathMap; - } - return null; - }) - .filter(Objects::nonNull) - .collect(Collectors.toMap( - fromToPathEntry -> fromToPathEntry.keySet().iterator().next(), - fromToPathEntry -> fromToPathEntry.values().iterator().next() - )); + final Map actualFromToPathMap = nonManoFileList.stream().map(nonManoFilePath -> { + final Path normalizedFilePath = resolveNonManoFilePath(originalManifestPath, nonManoFilePath); + final Optional changedPath = updateNonManoPathInHandler(handler, nonManoFolderType, normalizedFilePath); + if (changedPath.isPresent()) { + final Map fromAndToPathMap = new HashMap<>(); + fromAndToPathMap.put(nonManoFilePath, Paths.get(ARTIFACTS_FOLDER).resolve(changedPath.get())); + return fromAndToPathMap; + } + return null; + }).filter(Objects::nonNull).collect(Collectors.toMap(fromToPathEntry -> fromToPathEntry.keySet().iterator().next(), + fromToPathEntry -> fromToPathEntry.values().iterator().next())); fromToPathMap.putAll(actualFromToPathMap); }); - return MapUtils.isEmpty(fromToPathMap) ? Optional.empty() : Optional.of(fromToPathMap); } @@ -125,7 +117,7 @@ public class ETSIServiceImpl implements ETSIService { * Resolves the non mano file path based on the original manifest path of the onboarded package. * * @param originalManifestPath The original path from the onboarded package manifest - * @param nonManoFilePath The non mano file path defined in the manifest + * @param nonManoFilePath The non mano file path defined in the manifest * @return The resolved and normalized non mano path. */ private Path resolveNonManoFilePath(final Path originalManifestPath, final String nonManoFilePath) { @@ -135,8 +127,8 @@ public class ETSIServiceImpl implements ETSIService { /** * Updates the non mano file path in the package file handler based on the non mano type. * - * @param handler The package file handler - * @param nonManoFolderType The Non Mano type of the file to update + * @param handler The package file handler + * @param nonManoFolderType The Non Mano type of the file to update * @param nonManoOriginalFilePath The Non Mano file original path * @return The new file path if it was updated in the package file handler, otherwise empty. */ @@ -144,23 +136,22 @@ public class ETSIServiceImpl implements ETSIService { final Path nonManoOriginalFilePath) { final Path fixedSourcePath = fixNonManoPath(nonManoOriginalFilePath); if (handler.containsFile(fixedSourcePath.toString())) { - final Path newNonManoPath = Paths.get(nonManoFolderType.getType(), nonManoFolderType.getLocation() - , fixedSourcePath.getFileName().toString()); + final Path newNonManoPath = Paths + .get(nonManoFolderType.getType(), nonManoFolderType.getLocation(), fixedSourcePath.getFileName().toString()); if (!handler.containsFile(newNonManoPath.toString())) { handler.addFile(newNonManoPath.toString(), handler.remove(fixedSourcePath.toString())); return Optional.of(newNonManoPath); } } - return Optional.empty(); } /** * Fix the original non mano file path to the ONAP package file path. - * - * Non mano artifacts that were inside the {@link org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} path - * are not moved when parsed to ONAP package, but the Manifest declaration can still have the {@link - * org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} reference in it. If so, that reference is removed. + *

          + * Non mano artifacts that were inside the {@link org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} path are not moved when parsed to + * ONAP package, but the Manifest declaration can still have the {@link org.openecomp.sdc.tosca.csar.CSARConstants#ARTIFACTS_FOLDER} reference in + * it. If so, that reference is removed. * * @param nonManoOriginalFilePath The original non mano file path * @return The non mano fixed path to ONAP package structure. @@ -174,28 +165,22 @@ public class ETSIServiceImpl implements ETSIService { if (nonManoOriginalFilePath.startsWith(relativeArtifactsPath)) { return relativeArtifactsPath.relativize(nonManoOriginalFilePath); } - return nonManoOriginalFilePath; } @Override - public void updateMainDescriptorPaths(final ToscaServiceModel toscaServiceModel, - final Map fromToMovedArtifactMap) { - final ServiceTemplate entryDefinition = toscaServiceModel.getServiceTemplates() - .get(toscaServiceModel.getEntryDefinitionServiceTemplate()); + public void updateMainDescriptorPaths(final ToscaServiceModel toscaServiceModel, final Map fromToMovedArtifactMap) { + final ServiceTemplate entryDefinition = toscaServiceModel.getServiceTemplates().get(toscaServiceModel.getEntryDefinitionServiceTemplate()); final YamlUtil yamlUtil = new YamlUtil(); final String[] entryDefinitionYaml = {yamlUtil.objectToYaml(entryDefinition)}; - fromToMovedArtifactMap.forEach((fromPath, toPath) -> entryDefinitionYaml[0] = entryDefinitionYaml[0] - .replaceAll(fromPath, toPath.toString())); - - toscaServiceModel.addServiceTemplate(toscaServiceModel.getEntryDefinitionServiceTemplate() - , yamlUtil.yamlToObject(entryDefinitionYaml[0], ServiceTemplate.class)); + fromToMovedArtifactMap.forEach((fromPath, toPath) -> entryDefinitionYaml[0] = entryDefinitionYaml[0].replaceAll(fromPath, toPath.toString())); + toscaServiceModel.addServiceTemplate(toscaServiceModel.getEntryDefinitionServiceTemplate(), + yamlUtil.yamlToObject(entryDefinitionYaml[0], ServiceTemplate.class)); } private boolean hasMetaMandatoryEntries(final ToscaMetadata toscaMetadata) { final Map metaDataEntries = toscaMetadata.getMetaEntries(); - return metaDataEntries.containsKey(ENTRY_DEFINITIONS.getName()) && metaDataEntries - .containsKey(ETSI_ENTRY_MANIFEST.getName()) + return metaDataEntries.containsKey(ENTRY_DEFINITIONS.getName()) && metaDataEntries.containsKey(ETSI_ENTRY_MANIFEST.getName()) && metaDataEntries.containsKey(ETSI_ENTRY_CHANGE_LOG.getName()); } @@ -204,23 +189,21 @@ public class ETSIServiceImpl implements ETSIService { try { Map metadata = getManifest(handler).getMetadata(); if (metadata.containsKey(COMPATIBLE_SPECIFICATION_VERSIONS.getToken())) { - return Arrays.asList(metadata.get(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()).split(",")) - .stream().map(Semver::new).max((v1, v2) -> v1.compareTo(v2)) - .orElse(new Semver(ETSI_VERSION_2_6_1)); + return Arrays.asList(metadata.get(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()).split(",")).stream().map(Semver::new) + .max((v1, v2) -> v1.compareTo(v2)).orElse(new Semver(ETSI_VERSION_2_6_1)); } } catch (Exception ex) { LOGGER.error("An error occurred while getting highest compatible version from manifest file", ex); } return new Semver(ETSI_VERSION_2_6_1); - } @Override public boolean hasCnfEnhancements(final FileContentHandler fileContentHandler) throws IOException { final Manifest manifest = loadManifest(fileContentHandler); return manifest.getNonManoSources().entrySet().stream() - .filter(manifestNonManoSourceEntry -> NonManoArtifactType.ONAP_CNF_HELM.getType() - .equalsIgnoreCase(manifestNonManoSourceEntry.getKey())).findFirst().isPresent(); + .filter(manifestNonManoSourceEntry -> NonManoArtifactType.ONAP_CNF_HELM.getType().equalsIgnoreCase(manifestNonManoSourceEntry.getKey())) + .findFirst().isPresent(); } private Manifest loadManifest(final FileContentHandler handler) throws IOException { @@ -248,9 +231,10 @@ public class ETSIServiceImpl implements ETSIService { public ResourceTypeEnum getResourceType(Manifest manifest) { // Valid manifest should contain whether vnf or pnf related metadata data exclusively in SOL004 standard, + // validation of manifest done during package upload stage - if (manifest != null && !manifest.getMetadata().isEmpty() - && MANIFEST_PNF_METADATA.stream().anyMatch(e -> manifest.getMetadata().containsKey(e))) { + if (manifest != null && !manifest.getMetadata().isEmpty() && MANIFEST_PNF_METADATA.stream() + .anyMatch(e -> manifest.getMetadata().containsKey(e))) { return ResourceTypeEnum.PNF; } // VNF is default resource type @@ -280,11 +264,9 @@ public class ETSIServiceImpl implements ETSIService { private ToscaMetadata getMetadata(FileContentHandler handler) throws IOException { ToscaMetadata metadata; if (handler.containsFile(TOSCA_META_PATH_FILE_NAME)) { - metadata = OnboardingToscaMetadata - .parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); + metadata = OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); } else if (handler.containsFile(TOSCA_META_ORIG_PATH_FILE_NAME)) { - metadata = OnboardingToscaMetadata - .parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME)); + metadata = OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME)); } else { throw new IOException("TOSCA.meta file not found!"); } @@ -293,8 +275,7 @@ public class ETSIServiceImpl implements ETSIService { private ToscaMetadata getOriginalMetadata(final FileContentHandler handler) throws IOException { if (handler.containsFile(TOSCA_META_ORIG_PATH_FILE_NAME)) { - return OnboardingToscaMetadata - .parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME)); + return OnboardingToscaMetadata.parseToscaMetadataFile(handler.getFileContentAsStream(TOSCA_META_ORIG_PATH_FILE_NAME)); } else { throw new IOException(String.format("%s file not found", TOSCA_META_ORIG_PATH_FILE_NAME)); } @@ -307,7 +288,6 @@ public class ETSIServiceImpl implements ETSIService { } else { io = handler.getFileContentAsStream(manifestLocation); } - if (io == null) { throw new IOException("Manifest file not found!"); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java index 7c11fb65ab..7ba8732091 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremodule; import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; @@ -72,578 +71,491 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CandidateServiceImpl implements CandidateService { - private static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); - private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); - private ManifestCreator manifestCreator; - private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; - - public CandidateServiceImpl(ManifestCreator manifestCreator, - OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao) { - this.manifestCreator = manifestCreator; - this.orchestrationTemplateCandidateDao = orchestrationTemplateCandidateDao; - } - - public CandidateServiceImpl() { - } - - @Override - public Optional validateNonEmptyFileToUpload(InputStream fileToUpload, - String fileSuffix) { - String errorMessage = - getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), - fileSuffix); - - if (Objects.isNull(fileToUpload)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - errorMessage)); - } else { - try { - int available = fileToUpload.available(); - if (available == 0) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - errorMessage)); + + private static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); + private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); + private ManifestCreator manifestCreator; + private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; + + public CandidateServiceImpl(ManifestCreator manifestCreator, OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao) { + this.manifestCreator = manifestCreator; + this.orchestrationTemplateCandidateDao = orchestrationTemplateCandidateDao; + } + + public CandidateServiceImpl() { + } + + @Override + public Optional validateNonEmptyFileToUpload(InputStream fileToUpload, String fileSuffix) { + String errorMessage = getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), fileSuffix); + if (Objects.isNull(fileToUpload)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, errorMessage)); + } else { + try { + int available = fileToUpload.available(); + if (available == 0) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, errorMessage)); + } + } catch (IOException e) { + logger.debug(e.getMessage(), e); + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, errorMessage)); + } } - } catch (IOException e) { - logger.debug(e.getMessage(), e); - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - errorMessage)); - } - } - return Optional.empty(); - } - - @Override - public Optional validateRawZipData(String fileSuffix, - byte[] uploadedFileData) { - if (Objects.isNull(uploadedFileData)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), - fileSuffix))); - } - return Optional.empty(); - } - - private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, - FileContentHandler zipContentMap, - Map> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - FilesDataStructure structure = new FilesDataStructure(); - Set usedEnvFiles = new HashSet<>(); - addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, - analyzedZipHeatFiles); - handleOtherResources(tree, usedEnvFiles, structure); - FilesDataStructure fileDataStructureFromManifest = - createFileDataStructureFromManifest(zipContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)); - List structureArtifacts = structure.getArtifacts(); - structureArtifacts.addAll(fileDataStructureFromManifest.getArtifacts().stream().filter - (artifact -> isNotStrctureArtifact(structureArtifacts, artifact)) - .collect(Collectors.toList())); - handleArtifactsFromTree(tree, structure); - - return JsonUtil.object2Json(structure); - } - - private boolean isNotStrctureArtifact(List structureArtifacts, String artifact) { - return !structureArtifacts.contains(artifact); - } - - @Override - public OrchestrationTemplateCandidateData createCandidateDataEntity( - CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - FileContentHandler zipContentMap = candidateDataEntityTo.getContentMap(); - FilesDataStructure filesDataStructure; - String dataStructureJson; - - if (zipFileManifest != null) { - // create data structure from manifest - filesDataStructure = createFileDataStructureFromManifest(zipFileManifest); - Set zipFileList = zipContentMap.getFileList(); - balanceManifestFilesWithZipFiles(filesDataStructure, - zipContentMap, analyzedZipHeatFiles); - Set filesDataStructureFiles = getFlatFileNames(filesDataStructure); - filesDataStructure.getUnassigned().addAll(zipFileList.stream() - .filter(fileName -> (!filesDataStructureFiles.contains(fileName) - && !filesDataStructure.getNested().contains(fileName) - && !fileName.equals(SdcCommon.MANIFEST_NAME))) - .collect(Collectors.toList())); - dataStructureJson = JsonUtil.object2Json(filesDataStructure); - } else { - // create data structure from based on naming convention - dataStructureJson = - heatStructureTreeToFileDataStructure(candidateDataEntityTo.getTree(), zipContentMap, - candidateDataEntityTo.getErrors(), analyzedZipHeatFiles); - } - - OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); - candidateData.setContentData(ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData())); - candidateData.setFilesDataStructure(dataStructureJson); - return candidateData; - } - - private void balanceManifestFilesWithZipFiles( - FilesDataStructure filesDataStructure, - FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) { - Set zipFileList = fileContentHandler.getFileList(); - filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles()); - List modules = filesDataStructure.getModules(); - if (CollectionUtils.isEmpty(modules)) { - return; - } - - for (int i = 0; i < modules.size(); i++) { - Module module = modules.get(i); - if (!isFileExistInZipContains(zipFileList, module.getYaml())) { - addFileToUnassigned(filesDataStructure, zipFileList, module.getEnv()); - addFileToUnassigned(filesDataStructure, zipFileList, module.getVol()); - addFileToUnassigned(filesDataStructure, zipFileList, module.getVolEnv()); - modules.remove(i--); - } else if (Objects.nonNull(module.getVol()) && !zipFileList.contains(module.getVol())) { - module.setVol(null); - CollectionUtils - .addIgnoreNull(filesDataStructure.getUnassigned(), module.getVolEnv()); - } else { - if (filesDataStructure.getNested().contains(module.getYaml())) { - moveModuleFileToNested(filesDataStructure, i--, module); + return Optional.empty(); + } + + @Override + public Optional validateRawZipData(String fileSuffix, byte[] uploadedFileData) { + if (Objects.isNull(uploadedFileData)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), fileSuffix))); } - } - } - } - - private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set zipFileList, - String fileName) { - if (isFileExistInZipContains(zipFileList, fileName)) { - filesDataStructure.getUnassigned().add(fileName); - } - } - - private boolean isFileExistInZipContains(Set zipFileList, String fileName) { - return Objects.nonNull(fileName) && zipFileList.contains(fileName); - } - - private void moveModuleFileToNested(FilesDataStructure filesDataStructure, int i, - Module module) { - if (!filesDataStructure.getNested().contains(module.getYaml())) { - filesDataStructure.getNested().add(module.getYaml()); - } - if (Objects.nonNull(module.getEnv())) { - filesDataStructure.getNested().add(module.getEnv()); - } - if (Objects.nonNull(module.getVol())) { - filesDataStructure.getNested().add(module.getVol()); - } - if (Objects.nonNull(module.getVolEnv())) { - filesDataStructure.getNested().add(module.getVolEnv()); - } - filesDataStructure.getModules().remove(i); - } - - private Set getFlatFileNames(FilesDataStructure filesDataStructure) { - Set fileNames = new HashSet<>(); - if (!CollectionUtils.isEmpty(filesDataStructure.getModules())) { - for (Module module : filesDataStructure.getModules()) { - CollectionUtils.addIgnoreNull(fileNames, module.getEnv()); - CollectionUtils.addIgnoreNull(fileNames, module.getVol()); - CollectionUtils.addIgnoreNull(fileNames, module.getVolEnv()); - CollectionUtils.addIgnoreNull(fileNames, module.getYaml()); - } - } - fileNames.addAll(filesDataStructure.getArtifacts()); - fileNames.addAll(filesDataStructure.getNested()); - fileNames.addAll(filesDataStructure.getUnassigned()); - - return fileNames; - } - - private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { - ManifestContent manifestContent = - JsonUtil.json2Object(isManifestContent, ManifestContent.class); - FilesDataStructure structure = new FilesDataStructure(); - for (FileData fileData : manifestContent.getData()) { - if (Objects.nonNull(fileData.getType()) && - fileData.getType().equals(FileData.Type.HEAT)) { - Module module = new Module(); - module.setType(FileData.Type.HEAT); - module.setYaml(fileData.getFile()); - module.setIsBase(fileData.getBase()); - addHeatDependenciesToModule(module, fileData.getData()); - structure.getModules().add(module); - }else if (Objects.nonNull(fileData.getType()) && - fileData.getType().equals(FileData.Type.HELM)) { - Module module = new Module(); - module.setType(FileData.Type.HELM); - module.setYaml(fileData.getFile()); - module.setIsBase(fileData.getBase()); - structure.getModules().add(module); - } - else if (HeatFileAnalyzer.isYamlOrEnvFile(fileData.getFile()) && - !FileData.Type.isArtifact(fileData.getType())) { - structure.getUnassigned().add(fileData.getFile()); - } else { - structure.getArtifacts().add(fileData.getFile()); - } - } - return structure; - } - - private void addHeatDependenciesToModule(Module module, List data) { - if (CollectionUtils.isEmpty(data)) { - return; - } - - for (FileData fileData : data) { - if (fileData.getType().equals(FileData.Type.HEAT_ENV)) { - module.setEnv(fileData.getFile()); - } else if (fileData.getType().equals(FileData.Type.HEAT_VOL)) { // must be volume - module.setVol(fileData.getFile()); - if (!CollectionUtils.isEmpty(fileData.getData())) { - FileData volEnv = fileData.getData().get(0); - if (volEnv.getType().equals(FileData.Type.HEAT_ENV)) { - module.setVolEnv(volEnv.getFile()); - } else { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.ILLEGAL_MANIFEST.getErrorMessage()) - .withId(Messages.ILLEGAL_MANIFEST.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); - } + return Optional.empty(); + } + + private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, FileContentHandler zipContentMap, + Map> uploadErrors, AnalyzedZipHeatFiles analyzedZipHeatFiles) { + FilesDataStructure structure = new FilesDataStructure(); + Set usedEnvFiles = new HashSet<>(); + addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, analyzedZipHeatFiles); + handleOtherResources(tree, usedEnvFiles, structure); + FilesDataStructure fileDataStructureFromManifest = createFileDataStructureFromManifest( + zipContentMap.getFileContentAsStream(SdcCommon.MANIFEST_NAME)); + List structureArtifacts = structure.getArtifacts(); + structureArtifacts.addAll( + fileDataStructureFromManifest.getArtifacts().stream().filter(artifact -> isNotStrctureArtifact(structureArtifacts, artifact)) + .collect(Collectors.toList())); + handleArtifactsFromTree(tree, structure); + return JsonUtil.object2Json(structure); + } + + private boolean isNotStrctureArtifact(List structureArtifacts, String artifact) { + return !structureArtifacts.contains(artifact); + } + + @Override + public OrchestrationTemplateCandidateData createCandidateDataEntity(CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles) { + FileContentHandler zipContentMap = candidateDataEntityTo.getContentMap(); + FilesDataStructure filesDataStructure; + String dataStructureJson; + if (zipFileManifest != null) { + // create data structure from manifest + filesDataStructure = createFileDataStructureFromManifest(zipFileManifest); + Set zipFileList = zipContentMap.getFileList(); + balanceManifestFilesWithZipFiles(filesDataStructure, zipContentMap, analyzedZipHeatFiles); + Set filesDataStructureFiles = getFlatFileNames(filesDataStructure); + filesDataStructure.getUnassigned().addAll(zipFileList.stream().filter( + fileName -> (!filesDataStructureFiles.contains(fileName) && !filesDataStructure.getNested().contains(fileName) && !fileName + .equals(SdcCommon.MANIFEST_NAME))).collect(Collectors.toList())); + dataStructureJson = JsonUtil.object2Json(filesDataStructure); + } else { + // create data structure from based on naming convention + dataStructureJson = heatStructureTreeToFileDataStructure(candidateDataEntityTo.getTree(), zipContentMap, + candidateDataEntityTo.getErrors(), analyzedZipHeatFiles); } - } else { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) - .withId(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); - } - } - } - - @Override - public void updateCandidateUploadData(final String vspId, final Version version, - final OrchestrationTemplateCandidateData uploadData) { - orchestrationTemplateCandidateDao.update(vspId, version, uploadData); - } - - @Override - public Optional getOrchestrationTemplateCandidateFileDataStructure( - String vspId, Version version) { - Optional jsonFileDataStructure = - orchestrationTemplateCandidateDao.getStructure(vspId, version); - - if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) { - return Optional - .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); - } else { - return Optional.empty(); - } - } - - @Override - public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure) { - OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface() - .updateStructure(vspId, version, fileDataStructure); - } - - @Override - public Optional getOrchestrationTemplateCandidate(String vspId, - Version version) { - return orchestrationTemplateCandidateDao.get(vspId, version); - } - - @Override - public Optional getOrchestrationTemplateCandidateInfo( - String vspId, - Version version) { - return orchestrationTemplateCandidateDao.getInfo(vspId, version); - } - - @Override - public String createManifest(VspDetails vspDetails, FilesDataStructure structure) { - return JsonUtil.object2Json(manifestCreator.createManifest(vspDetails, structure) - .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()).build()))); - } - - @Override - public String createManifestFromExisting(VspDetails vspDetails, FilesDataStructure structure, ManifestContent existingManifest) { - return JsonUtil.object2Json(manifestCreator.createManifestFromExisting(vspDetails, structure, existingManifest) - .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()).build()))); - } - - @Override - public Optional createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, + OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); + candidateData.setContentData(ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData())); + candidateData.setFilesDataStructure(dataStructureJson); + return candidateData; + } + + private void balanceManifestFilesWithZipFiles(FilesDataStructure filesDataStructure, FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) { - return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); - } - - @Override - public Optional fetchZipFileByteArrayInputStream(String vspId, - OrchestrationTemplateCandidateData candidateDataEntity, - String manifest, - OnboardingTypesEnum type, - Map> uploadErrors) { - byte[] file; - ByteArrayInputStream byteArrayInputStream = null; - try { - file = replaceManifestInZip(candidateDataEntity.getContentData(), manifest, type); - byteArrayInputStream = new ByteArrayInputStream( - Objects.isNull(file) ? candidateDataEntity.getContentData().array() - : file); - } catch (IOException e) { - ErrorMessage errorMessage = - new ErrorMessage(ErrorLevel.ERROR, - Messages.CANDIDATE_PROCESS_FAILED.getErrorMessage()); - logger.error(errorMessage.getMessage(), e); - ErrorsUtil - .addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, errorMessage, uploadErrors); - } - return Optional.ofNullable(byteArrayInputStream); - } - - @Override - public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, - OnboardingTypesEnum type) - throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (final ZipOutputStream zos = new ZipOutputStream(baos); - ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(contentData.array()))) { - ZipEntry zipEntry; - boolean manifestWritten = false; - while ((zipEntry = zipStream.getNextEntry()) != null) { - if (!zipEntry.getName().equalsIgnoreCase(SdcCommon.MANIFEST_NAME)) { - ZipEntry loc_ze = new ZipEntry(zipEntry.getName()); - zos.putNextEntry(loc_ze); - byte[] buf = new byte[1024]; - int len; - while ((len = zipStream.read(buf)) > 0) { - zos.write(buf, 0, (len < buf.length) ? len : buf.length); - } + Set zipFileList = fileContentHandler.getFileList(); + filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles()); + List modules = filesDataStructure.getModules(); + if (CollectionUtils.isEmpty(modules)) { + return; + } + for (int i = 0; i < modules.size(); i++) { + Module module = modules.get(i); + if (!isFileExistInZipContains(zipFileList, module.getYaml())) { + addFileToUnassigned(filesDataStructure, zipFileList, module.getEnv()); + addFileToUnassigned(filesDataStructure, zipFileList, module.getVol()); + addFileToUnassigned(filesDataStructure, zipFileList, module.getVolEnv()); + modules.remove(i--); + } else if (Objects.nonNull(module.getVol()) && !zipFileList.contains(module.getVol())) { + module.setVol(null); + CollectionUtils.addIgnoreNull(filesDataStructure.getUnassigned(), module.getVolEnv()); + } else { + if (filesDataStructure.getNested().contains(module.getYaml())) { + moveModuleFileToNested(filesDataStructure, i--, module); + } + } + } + } + + private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set zipFileList, String fileName) { + if (isFileExistInZipContains(zipFileList, fileName)) { + filesDataStructure.getUnassigned().add(fileName); + } + } + + private boolean isFileExistInZipContains(Set zipFileList, String fileName) { + return Objects.nonNull(fileName) && zipFileList.contains(fileName); + } + + private void moveModuleFileToNested(FilesDataStructure filesDataStructure, int i, Module module) { + if (!filesDataStructure.getNested().contains(module.getYaml())) { + filesDataStructure.getNested().add(module.getYaml()); + } + if (Objects.nonNull(module.getEnv())) { + filesDataStructure.getNested().add(module.getEnv()); + } + if (Objects.nonNull(module.getVol())) { + filesDataStructure.getNested().add(module.getVol()); + } + if (Objects.nonNull(module.getVolEnv())) { + filesDataStructure.getNested().add(module.getVolEnv()); + } + filesDataStructure.getModules().remove(i); + } + + private Set getFlatFileNames(FilesDataStructure filesDataStructure) { + Set fileNames = new HashSet<>(); + if (!CollectionUtils.isEmpty(filesDataStructure.getModules())) { + for (Module module : filesDataStructure.getModules()) { + CollectionUtils.addIgnoreNull(fileNames, module.getEnv()); + CollectionUtils.addIgnoreNull(fileNames, module.getVol()); + CollectionUtils.addIgnoreNull(fileNames, module.getVolEnv()); + CollectionUtils.addIgnoreNull(fileNames, module.getYaml()); + } + } + fileNames.addAll(filesDataStructure.getArtifacts()); + fileNames.addAll(filesDataStructure.getNested()); + fileNames.addAll(filesDataStructure.getUnassigned()); + return fileNames; + } + + private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { + ManifestContent manifestContent = JsonUtil.json2Object(isManifestContent, ManifestContent.class); + FilesDataStructure structure = new FilesDataStructure(); + for (FileData fileData : manifestContent.getData()) { + if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HEAT)) { + Module module = new Module(); + module.setType(FileData.Type.HEAT); + module.setYaml(fileData.getFile()); + module.setIsBase(fileData.getBase()); + addHeatDependenciesToModule(module, fileData.getData()); + structure.getModules().add(module); + } else if (Objects.nonNull(fileData.getType()) && fileData.getType().equals(FileData.Type.HELM)) { + Module module = new Module(); + module.setType(FileData.Type.HELM); + module.setYaml(fileData.getFile()); + module.setIsBase(fileData.getBase()); + structure.getModules().add(module); + } else if (HeatFileAnalyzer.isYamlOrEnvFile(fileData.getFile()) && !FileData.Type.isArtifact(fileData.getType())) { + structure.getUnassigned().add(fileData.getFile()); + } else { + structure.getArtifacts().add(fileData.getFile()); + } + } + return structure; + } + + private void addHeatDependenciesToModule(Module module, List data) { + if (CollectionUtils.isEmpty(data)) { + return; + } + for (FileData fileData : data) { + if (fileData.getType().equals(FileData.Type.HEAT_ENV)) { + module.setEnv(fileData.getFile()); + } else if (fileData.getType().equals(FileData.Type.HEAT_VOL)) { // must be volume + module.setVol(fileData.getFile()); + if (!CollectionUtils.isEmpty(fileData.getData())) { + FileData volEnv = fileData.getData().get(0); + if (volEnv.getType().equals(FileData.Type.HEAT_ENV)) { + module.setVolEnv(volEnv.getFile()); + } else { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(Messages.ILLEGAL_MANIFEST.getErrorMessage()) + .withId(Messages.ILLEGAL_MANIFEST.getErrorMessage()).withCategory(ErrorCategory.APPLICATION).build()); + } + } + } else { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) + .withId(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()).withCategory(ErrorCategory.APPLICATION).build()); + } + } + } + + @Override + public void updateCandidateUploadData(final String vspId, final Version version, final OrchestrationTemplateCandidateData uploadData) { + orchestrationTemplateCandidateDao.update(vspId, version, uploadData); + } + + @Override + public Optional getOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version) { + Optional jsonFileDataStructure = orchestrationTemplateCandidateDao.getStructure(vspId, version); + if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) { + return Optional.of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); } else { - manifestWritten = true; - writeManifest(manifest, type, zos); + return Optional.empty(); } - zos.closeEntry(); - } - if (!manifestWritten) { - writeManifest(manifest, type, zos); - zos.closeEntry(); - } - } - return baos.toByteArray(); - } - - @Override - public byte[] getZipData(ByteBuffer contentData) - throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (final ZipOutputStream zos = new ZipOutputStream(baos); - ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(contentData.array()))) { - ZipEntry zipEntry; - while ((zipEntry = zipStream.getNextEntry()) != null) { + } + + @Override + public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface().updateStructure(vspId, version, fileDataStructure); + } + + @Override + public Optional getOrchestrationTemplateCandidate(String vspId, Version version) { + return orchestrationTemplateCandidateDao.get(vspId, version); + } + + @Override + public Optional getOrchestrationTemplateCandidateInfo(String vspId, Version version) { + return orchestrationTemplateCandidateDao.getInfo(vspId, version); + } + + @Override + public String createManifest(VspDetails vspDetails, FilesDataStructure structure) { + return JsonUtil.object2Json(manifestCreator.createManifest(vspDetails, structure).orElseThrow( + () -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()).build()))); + } + + @Override + public String createManifestFromExisting(VspDetails vspDetails, FilesDataStructure structure, ManifestContent existingManifest) { + return JsonUtil.object2Json(manifestCreator.createManifestFromExisting(vspDetails, structure, existingManifest).orElseThrow( + () -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()).build()))); + } + + @Override + public Optional createManifest(VspDetails vspDetails, FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles) { + return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + } + + @Override + public Optional fetchZipFileByteArrayInputStream(String vspId, OrchestrationTemplateCandidateData candidateDataEntity, + String manifest, OnboardingTypesEnum type, + Map> uploadErrors) { + byte[] file; + ByteArrayInputStream byteArrayInputStream = null; try { - ZipUtils.checkForZipSlipInRead(zipEntry); - } catch (ZipSlipException e) { - throw new IOException(e); + file = replaceManifestInZip(candidateDataEntity.getContentData(), manifest, type); + byteArrayInputStream = new ByteArrayInputStream(Objects.isNull(file) ? candidateDataEntity.getContentData().array() : file); + } catch (IOException e) { + ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, Messages.CANDIDATE_PROCESS_FAILED.getErrorMessage()); + logger.error(errorMessage.getMessage(), e); + ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, errorMessage, uploadErrors); } - ZipEntry locZipEntry = new ZipEntry(zipEntry.getName()); - zos.putNextEntry(locZipEntry); - byte[] buf = new byte[1024]; - int len; - while ((len = zipStream.read(buf)) > 0) { - zos.write(buf, 0, (len < buf.length) ? len : buf.length); + return Optional.ofNullable(byteArrayInputStream); + } + + @Override + public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, OnboardingTypesEnum type) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (final ZipOutputStream zos = new ZipOutputStream(baos); ZipInputStream zipStream = new ZipInputStream( + new ByteArrayInputStream(contentData.array()))) { + ZipEntry zipEntry; + boolean manifestWritten = false; + while ((zipEntry = zipStream.getNextEntry()) != null) { + if (!zipEntry.getName().equalsIgnoreCase(SdcCommon.MANIFEST_NAME)) { + ZipEntry loc_ze = new ZipEntry(zipEntry.getName()); + zos.putNextEntry(loc_ze); + byte[] buf = new byte[1024]; + int len; + while ((len = zipStream.read(buf)) > 0) { + zos.write(buf, 0, (len < buf.length) ? len : buf.length); + } + } else { + manifestWritten = true; + writeManifest(manifest, type, zos); + } + zos.closeEntry(); + } + if (!manifestWritten) { + writeManifest(manifest, type, zos); + zos.closeEntry(); + } } - zos.closeEntry(); - } + return baos.toByteArray(); } - return baos.toByteArray(); - } - @Override - public Optional> validateFileDataStructure( - FilesDataStructure filesDataStructure) { - return candidateServiceValidator.validateFileDataStructure(filesDataStructure); - } + @Override + public byte[] getZipData(ByteBuffer contentData) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (final ZipOutputStream zos = new ZipOutputStream(baos); ZipInputStream zipStream = new ZipInputStream( + new ByteArrayInputStream(contentData.array()))) { + ZipEntry zipEntry; + while ((zipEntry = zipStream.getNextEntry()) != null) { + try { + ZipUtils.checkForZipSlipInRead(zipEntry); + } catch (ZipSlipException e) { + throw new IOException(e); + } + ZipEntry locZipEntry = new ZipEntry(zipEntry.getName()); + zos.putNextEntry(locZipEntry); + byte[] buf = new byte[1024]; + int len; + while ((len = zipStream.read(buf)) > 0) { + zos.write(buf, 0, (len < buf.length) ? len : buf.length); + } + zos.closeEntry(); + } + } + return baos.toByteArray(); + } - @Override - public void deleteOrchestrationTemplateCandidate(String vspId, Version versionId) { - orchestrationTemplateCandidateDao.delete(vspId, versionId); - } + @Override + public Optional> validateFileDataStructure(FilesDataStructure filesDataStructure) { + return candidateServiceValidator.validateFileDataStructure(filesDataStructure); + } - @Override - public void updateValidationData(String vspId, Version version, ValidationStructureList - validationData) { - orchestrationTemplateCandidateDao.updateValidationData(vspId, version, validationData); - } + @Override + public void deleteOrchestrationTemplateCandidate(String vspId, Version versionId) { + orchestrationTemplateCandidateDao.delete(vspId, versionId); + } - private void writeManifest(String manifest, - OnboardingTypesEnum type, - ZipOutputStream zos) throws IOException { + @Override + public void updateValidationData(String vspId, Version version, ValidationStructureList validationData) { + orchestrationTemplateCandidateDao.updateValidationData(vspId, version, validationData); + } - if (isManifestNeedsToGetWritten(type)) { - return; + private void writeManifest(String manifest, OnboardingTypesEnum type, ZipOutputStream zos) throws IOException { + if (isManifestNeedsToGetWritten(type)) { + return; + } + zos.putNextEntry(new ZipEntry(SdcCommon.MANIFEST_NAME)); + try (InputStream manifestStream = new ByteArrayInputStream(manifest.getBytes(StandardCharsets.UTF_8))) { + byte[] buf = new byte[1024]; + int len; + while ((len = (manifestStream.read(buf))) > 0) { + zos.write(buf, 0, (len < buf.length) ? len : buf.length); + } + } } - zos.putNextEntry(new ZipEntry(SdcCommon.MANIFEST_NAME)); - try (InputStream manifestStream = new ByteArrayInputStream( - manifest.getBytes(StandardCharsets.UTF_8))) { - byte[] buf = new byte[1024]; - int len; - while ((len = (manifestStream.read(buf))) > 0) { - zos.write(buf, 0, (len < buf.length) ? len : buf.length); - } + private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) { + return type.equals(OnboardingTypesEnum.CSAR); } - } - private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) { - return type.equals(OnboardingTypesEnum.CSAR); - } + private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) { + if (Objects.isNull(tree) || Objects.isNull(tree.getArtifacts())) { + return; + } + if (CollectionUtils.isNotEmpty(tree.getArtifacts())) { + structure.getArtifacts().addAll( + tree.getArtifacts().stream().map(Artifact::getFileName).filter(fileName -> !structure.getArtifacts().contains(fileName)) + .collect(Collectors.toList())); + } + } + + private void handleOtherResources(HeatStructureTree tree, Set usedEnvFiles, FilesDataStructure structure) { + Set others = tree.getOther(); + if (Objects.isNull(others)) { + return; + } + List artifacts = new ArrayList<>(); + List unassigned = new ArrayList<>(); + for (HeatStructureTree other : others) { + if (HeatFileAnalyzer.isYamlOrEnvFile(other.getFileName())) { + if (isEnvFileUsedByHeatFile(usedEnvFiles, other)) { + continue; + } + unassigned.add(other.getFileName()); + } else { + artifacts.add(other.getFileName()); + } + handleArtifactsFromTree(other, structure); + } + structure.getArtifacts().addAll(artifacts); + structure.getUnassigned().addAll(unassigned); + } - private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) { + private boolean isEnvFileUsedByHeatFile(Set usedEnvFiles, HeatStructureTree other) { + return HeatFileAnalyzer.isEnvFile(other.getFileName()) && usedEnvFiles.contains(other.getFileName()); + } - if (Objects.isNull(tree) || Objects.isNull(tree.getArtifacts())) { - return; + private void addHeatsToFileDataStructure(HeatStructureTree tree, Set usedEnvFiles, FilesDataStructure structure, + Map> uploadErrors, AnalyzedZipHeatFiles analyzedZipHeatFiles) { + List modules = new ArrayList<>(); + Set heatsSet = tree.getHeat(); + if (Objects.isNull(heatsSet)) { + return; + } + for (HeatStructureTree heat : heatsSet) { + if (isFileBaseFile(heat.getFileName())) { + handleSingleHeat(structure, modules, heat, uploadErrors); + } else if (isFileModuleFile(heat.getFileName(), analyzedZipHeatFiles.getModuleFiles())) { + handleSingleHeat(structure, modules, heat, uploadErrors); + } else { + structure.getUnassigned().add(heat.getFileName()); + addNestedToFileDataStructure(heat, structure); + } + if (!Objects.isNull(heat.getEnv())) { + usedEnvFiles.add(heat.getEnv() == null ? null : heat.getEnv().getFileName()); + } + } + structure.setModules(modules); } - if (CollectionUtils.isNotEmpty(tree.getArtifacts())) { - structure.getArtifacts().addAll( - tree.getArtifacts() - .stream() - .map(Artifact::getFileName) - .filter(fileName -> !structure.getArtifacts().contains(fileName)) - .collect(Collectors.toList())); + private boolean isFileModuleFile(String fileName, Set modulesFileNames) { + return modulesFileNames.contains(fileName); } - } - private void handleOtherResources(HeatStructureTree tree, Set usedEnvFiles, - FilesDataStructure structure) { - Set others = tree.getOther(); - if (Objects.isNull(others)) { - return; + private boolean isFileBaseFile(String fileName) { + return manifestCreator.isFileBaseFile(fileName); } - List artifacts = new ArrayList<>(); - List unassigned = new ArrayList<>(); - for (HeatStructureTree other : others) { - if (HeatFileAnalyzer.isYamlOrEnvFile(other.getFileName())) { - if (isEnvFileUsedByHeatFile(usedEnvFiles, other)) { - continue; - } - unassigned.add(other.getFileName()); - } else { - artifacts.add(other.getFileName()); - } - handleArtifactsFromTree(other, structure); - } - structure.getArtifacts().addAll(artifacts); - structure.getUnassigned().addAll(unassigned); - } - - private boolean isEnvFileUsedByHeatFile(Set usedEnvFiles, HeatStructureTree other) { - return HeatFileAnalyzer.isEnvFile(other.getFileName()) && - usedEnvFiles.contains(other.getFileName()); - } - - private void addHeatsToFileDataStructure(HeatStructureTree tree, Set usedEnvFiles, - FilesDataStructure structure, - Map> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - List modules = new ArrayList<>(); - Set heatsSet = tree.getHeat(); - if (Objects.isNull(heatsSet)) { - return; - } - for (HeatStructureTree heat : heatsSet) { - if (isFileBaseFile(heat.getFileName())) { - handleSingleHeat(structure, modules, heat, uploadErrors); - } else if (isFileModuleFile(heat.getFileName(), - analyzedZipHeatFiles.getModuleFiles())) { - handleSingleHeat(structure, modules, heat, uploadErrors); - } else { - structure.getUnassigned().add(heat.getFileName()); + private void handleSingleHeat(FilesDataStructure structure, List modules, HeatStructureTree heat, + Map> uploadErrors) { + Module module = new Module(); + module.setYaml(heat.getFileName()); + module.setIsBase(heat.getBase()); addNestedToFileDataStructure(heat, structure); - } - if (!Objects.isNull(heat.getEnv())) { - usedEnvFiles.add(heat.getEnv() == null ? null : heat.getEnv().getFileName()); - } - } - structure.setModules(modules); - - } - - private boolean isFileModuleFile(String fileName, Set modulesFileNames) { - return modulesFileNames.contains(fileName); - } - - private boolean isFileBaseFile(String fileName) { - return manifestCreator.isFileBaseFile(fileName); - } - - private void handleSingleHeat(FilesDataStructure structure, List modules, - HeatStructureTree heat, - Map> uploadErrors) { - Module module = new Module(); - module.setYaml(heat.getFileName()); - module.setIsBase(heat.getBase()); - addNestedToFileDataStructure(heat, structure); - Set volumeSet = heat.getVolume(); - int inx = 0; - if (Objects.nonNull(volumeSet)) { - handleVolumes(module, volumeSet, structure, inx, uploadErrors); - } - handleEnv(module, heat, false, structure); - modules.add(module); - } - - private void handleVolumes(Module module, Set volumeSet, - FilesDataStructure structure, int inx, - Map> uploadErrors) { - for (HeatStructureTree volume : volumeSet) { - Objects.requireNonNull(volume, "volume cannot be null!"); - if (inx++ > 0) { - ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.WARNING, - Messages.MORE_THEN_ONE_VOL_FOR_HEAT.getErrorMessage()), uploadErrors); - break; - } - handleArtifactsFromTree(volume, structure); - module.setVol(volume.getFileName()); - handleEnv(module, volume, true, structure); - addNestedToFileDataStructure(volume, structure); - } - } - - private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv, - FilesDataStructure structure) { - if (Objects.nonNull(tree.getEnv())) { - if (isVolEnv) { - module.setVolEnv(tree.getEnv().getFileName()); - } else { - module.setEnv(tree.getEnv().getFileName()); - } - handleArtifactsFromTree(tree.getEnv(), structure); - } - } - - private void addNestedToFileDataStructure(HeatStructureTree heat, - FilesDataStructure structure) { - Set nestedSet = heat.getNested(); - if (Objects.isNull(nestedSet)) { - return; - } - for (HeatStructureTree nested : nestedSet) { - if (structure.getNested().contains(nested.getFileName())) { - continue; - } - structure.getNested().add(nested.getFileName()); - if (CollectionUtils.isNotEmpty(nested.getArtifacts())) { - handleArtifactsFromTree(nested, structure); - } - addNestedToFileDataStructure(nested, structure); - } - } + Set volumeSet = heat.getVolume(); + int inx = 0; + if (Objects.nonNull(volumeSet)) { + handleVolumes(module, volumeSet, structure, inx, uploadErrors); + } + handleEnv(module, heat, false, structure); + modules.add(module); + } + + private void handleVolumes(Module module, Set volumeSet, FilesDataStructure structure, int inx, + Map> uploadErrors) { + for (HeatStructureTree volume : volumeSet) { + Objects.requireNonNull(volume, "volume cannot be null!"); + if (inx++ > 0) { + ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, + new ErrorMessage(ErrorLevel.WARNING, Messages.MORE_THEN_ONE_VOL_FOR_HEAT.getErrorMessage()), uploadErrors); + break; + } + handleArtifactsFromTree(volume, structure); + module.setVol(volume.getFileName()); + handleEnv(module, volume, true, structure); + addNestedToFileDataStructure(volume, structure); + } + } + + private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv, FilesDataStructure structure) { + if (Objects.nonNull(tree.getEnv())) { + if (isVolEnv) { + module.setVolEnv(tree.getEnv().getFileName()); + } else { + module.setEnv(tree.getEnv().getFileName()); + } + handleArtifactsFromTree(tree.getEnv(), structure); + } + } + + private void addNestedToFileDataStructure(HeatStructureTree heat, FilesDataStructure structure) { + Set nestedSet = heat.getNested(); + if (Objects.isNull(nestedSet)) { + return; + } + for (HeatStructureTree nested : nestedSet) { + if (structure.getNested().contains(nested.getFileName())) { + continue; + } + structure.getNested().add(nested.getFileName()); + if (CollectionUtils.isNotEmpty(nested.getArtifacts())) { + handleArtifactsFromTree(nested, structure); + } + addNestedToFileDataStructure(nested, structure); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java index 54cc1fbf1c..f935318d01 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java @@ -14,9 +14,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.vendorsoftwareproduct.services.impl.filedatastructuremodule; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -31,322 +40,278 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.*; -import java.util.regex.Pattern; - public class ManifestCreatorNamingConventionImpl implements ManifestCreator { - protected static final Logger logger = - LoggerFactory.getLogger(ManifestCreatorNamingConventionImpl.class); - - private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech"; - private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */ - {"charts", "day0", "configtemplate"} /*cloud specific sub type*/}; - private static final String CONTROLLER_BLUEPRINT_ARCHIVE_FIXED_KEY_WORD = "CBA"; - private static final String HELM_KEY_WORD = "HELM"; - @Override - public Optional createManifest( - VspDetails vspDetails, FilesDataStructure filesDataStructure) { - if (Objects.isNull(filesDataStructure)) { - return Optional.empty(); + protected static final Logger logger = LoggerFactory.getLogger(ManifestCreatorNamingConventionImpl.class); + private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech"; + private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */ + {"charts", "day0", "configtemplate"} /*cloud specific sub type*/}; + private static final String CONTROLLER_BLUEPRINT_ARCHIVE_FIXED_KEY_WORD = "CBA"; + private static final String HELM_KEY_WORD = "HELM"; + + @Override + public Optional createManifest(VspDetails vspDetails, FilesDataStructure filesDataStructure) { + if (Objects.isNull(filesDataStructure)) { + return Optional.empty(); + } + List fileDataList = new ArrayList<>(); + addModulesToManifestFileDataList(filesDataStructure, fileDataList); + addNestedToManifest(filesDataStructure, fileDataList); + addArtifactsToManifestFileDataList(filesDataStructure, fileDataList); + ManifestContent manifestContent = createManifest(vspDetails, fileDataList); + return Optional.of(manifestContent); } - List fileDataList = new ArrayList<>(); - addModulesToManifestFileDataList(filesDataStructure, fileDataList); - addNestedToManifest(filesDataStructure, fileDataList); - addArtifactsToManifestFileDataList(filesDataStructure, fileDataList); - - ManifestContent manifestContent = createManifest(vspDetails, fileDataList); - return Optional.of(manifestContent); - } - - @Override - public Optional createManifestFromExisting(VspDetails vspDetails, FilesDataStructure filesDataStructure, ManifestContent existingManifest) { - if (Objects.isNull(filesDataStructure)) { - return Optional.empty(); + @Override + public Optional createManifestFromExisting(VspDetails vspDetails, FilesDataStructure filesDataStructure, + ManifestContent existingManifest) { + if (Objects.isNull(filesDataStructure)) { + return Optional.empty(); + } + List fileDataList = new ArrayList<>(); + addModulesToManifestFileDataList(filesDataStructure, fileDataList); + addNestedToManifest(filesDataStructure, fileDataList); + addArtifactsToManifestFileDataList(filesDataStructure, fileDataList, existingManifest); + ManifestContent manifestContent = createManifest(vspDetails, fileDataList); + return Optional.of(manifestContent); } - List fileDataList = new ArrayList<>(); - addModulesToManifestFileDataList(filesDataStructure, fileDataList); - addNestedToManifest(filesDataStructure, fileDataList); - addArtifactsToManifestFileDataList(filesDataStructure, fileDataList, existingManifest); - - ManifestContent manifestContent = createManifest(vspDetails, fileDataList); - return Optional.of(manifestContent); - } - - private void addArtifactsToManifestFileDataList(FilesDataStructure filesDataStructure, List fileDataList, ManifestContent existingManifest) { - Collection forArtifacts = CollectionUtils - .union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); - if (CollectionUtils.isNotEmpty(forArtifacts)) { - for (String artifact : forArtifacts) { - if (isCloudSpecificArtifact(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, artifact)); - } else if (isControllerBlueprintArchive(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.CONTROLLER_BLUEPRINT_ARCHIVE, artifact)); - } else if (isHelm(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.HELM, artifact)); - } else if (isPmDictionary(artifact, existingManifest)) { - fileDataList.add(createBaseFileData(FileData.Type.PM_DICTIONARY, artifact)); + private void addArtifactsToManifestFileDataList(FilesDataStructure filesDataStructure, List fileDataList, + ManifestContent existingManifest) { + Collection forArtifacts = CollectionUtils.union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); + if (CollectionUtils.isNotEmpty(forArtifacts)) { + for (String artifact : forArtifacts) { + if (isCloudSpecificArtifact(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, artifact)); + } else if (isControllerBlueprintArchive(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.CONTROLLER_BLUEPRINT_ARCHIVE, artifact)); + } else if (isHelm(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.HELM, artifact)); + } else if (isPmDictionary(artifact, existingManifest)) { + fileDataList.add(createBaseFileData(FileData.Type.PM_DICTIONARY, artifact)); + } else { + fileDataList.add(createBaseFileData(FileData.Type.OTHER, artifact)); + } + } } - else { - fileDataList.add(createBaseFileData(FileData.Type.OTHER, artifact)); - } - } } - } - private boolean isPmDictionary(String artifact, ManifestContent existingManifest) { - return existingManifest.getData() - .stream() - .filter(fileData -> fileData.getType() - .equals(FileData.Type.PM_DICTIONARY)) - .map(FileData::getFile) + private boolean isPmDictionary(String artifact, ManifestContent existingManifest) { + return existingManifest.getData().stream().filter(fileData -> fileData.getType().equals(FileData.Type.PM_DICTIONARY)).map(FileData::getFile) .anyMatch(pmDictionaryFile -> pmDictionaryFile.equals(artifact)); - } - - private void addNestedToManifest( - FilesDataStructure filesDataStructure, List fileDataList) { - if (CollectionUtils.isNotEmpty(filesDataStructure.getNested())) { - for (String nested : filesDataStructure.getNested()) { - fileDataList.add(createBaseFileData(FileData.Type.HEAT, nested)); - } } - } - @Override - public Optional createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - logger.info("Trying to generate manifest"); - if (Objects.isNull(fileContentHandler) - || CollectionUtils.isEmpty(fileContentHandler.getFileList())) { - logger.info("fileContentHandler or filesList is empty. ManifestContent will not be created"); - return Optional.empty(); + private void addNestedToManifest(FilesDataStructure filesDataStructure, List fileDataList) { + if (CollectionUtils.isNotEmpty(filesDataStructure.getNested())) { + for (String nested : filesDataStructure.getNested()) { + fileDataList.add(createBaseFileData(FileData.Type.HEAT, nested)); + } + } } - Map files = fileContentHandler.getFiles(); + @Override + public Optional createManifest(VspDetails vspDetails, FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles) { + logger.info("Trying to generate manifest"); + if (Objects.isNull(fileContentHandler) || CollectionUtils.isEmpty(fileContentHandler.getFileList())) { + logger.info("fileContentHandler or filesList is empty. ManifestContent will not be created"); + return Optional.empty(); + } + Map files = fileContentHandler.getFiles(); + List fileDataList = createFileDataListFromZipFiles(fileContentHandler, files, analyzedZipHeatFiles.getFilesNotEligbleForModules()); + ManifestContent manifestContent = createManifest(vspDetails, fileDataList); + return Optional.of(manifestContent); + } - List fileDataList = - createFileDataListFromZipFiles(fileContentHandler, files, - analyzedZipHeatFiles.getFilesNotEligbleForModules()); - ManifestContent manifestContent = createManifest(vspDetails, fileDataList); + private ManifestContent createManifest(VspDetails vspDetails, List fileDataList) { + ManifestContent manifestContent = new ManifestContent(); + manifestContent.setName(vspDetails.getName()); + manifestContent.setDescription(vspDetails.getDescription()); + manifestContent.setVersion(vspDetails.getVersion() == null ? null : vspDetails.getVersion().toString()); + // vsp version, need to check in confluence + manifestContent.setData(fileDataList); + return manifestContent; + } - return Optional.of(manifestContent); - } + private List createFileDataListFromZipFiles(FileContentHandler fileContentHandler, Map files, + Collection filesNotEligibleForModules) { + Set processedFiles = new HashSet<>(); + List fileDataList = new ArrayList<>(); + for (String fileName : files.keySet()) { + if (processedFiles.contains(fileName)) { + continue; + } + if (isFileBaseFile(fileName)) { + fileDataList.add(createModuleFileData(fileName, true, processedFiles, fileContentHandler.getFileList(), fileDataList)); + } else if (isFileModuleFile(fileName, filesNotEligibleForModules)) { + fileDataList.add(createModuleFileData(fileName, false, processedFiles, fileContentHandler.getFileList(), fileDataList)); + } else { + if (HeatFileAnalyzer.isYamlFile(fileName)) { + fileDataList.add(createBasicFileData(fileName, FileData.Type.HEAT, null)); + } else if (HeatFileAnalyzer.isEnvFile(fileName)) { + fileDataList.add(createBasicFileData(fileName, FileData.Type.HEAT_ENV, null)); + } else { + fileDataList.add(createBasicFileData(fileName, FileData.Type.OTHER, null)); + } + } + } + return fileDataList; + } - private ManifestContent createManifest(VspDetails vspDetails, List fileDataList) { - ManifestContent manifestContent = new ManifestContent(); - manifestContent.setName(vspDetails.getName()); - manifestContent.setDescription(vspDetails.getDescription()); - manifestContent - .setVersion(vspDetails.getVersion() == null ? null : vspDetails.getVersion().toString()); - // vsp version, need to check in confluence - manifestContent.setData(fileDataList); - return manifestContent; - } + private boolean isFileModuleFile(String fileName, Collection filesCannotBeModule) { + return !filesCannotBeModule.contains(fileName); + } - private List createFileDataListFromZipFiles(FileContentHandler fileContentHandler, - Map files, - Collection filesNotEligibleForModules) { + @Override + public boolean isFileBaseFile(String fileName) { + return Pattern.matches(Constants.BASE_HEAT_REGEX, fileName) && !isVolFile(fileName); + } - Set processedFiles = new HashSet<>(); - List fileDataList = new ArrayList<>(); - for (String fileName : files.keySet()) { - if (processedFiles.contains(fileName)) { - continue; - } - if (isFileBaseFile(fileName)) { - fileDataList - .add(createModuleFileData( - fileName, true, processedFiles, fileContentHandler.getFileList(), fileDataList)); - } else if (isFileModuleFile(fileName, filesNotEligibleForModules)) { - fileDataList - .add(createModuleFileData( - fileName, false, processedFiles, fileContentHandler.getFileList(), fileDataList)); - } else { - if (HeatFileAnalyzer.isYamlFile(fileName)) { - fileDataList.add(createBasicFileData(fileName, FileData.Type.HEAT, null)); - } else if (HeatFileAnalyzer.isEnvFile(fileName)) { - fileDataList.add(createBasicFileData(fileName, FileData.Type.HEAT_ENV, null)); + protected boolean isCloudSpecificArtifact(String artifact) { + if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) { + for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) { + if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) { + return false; + } + } + return true; } else { - fileDataList.add(createBasicFileData(fileName, FileData.Type.OTHER, null)); + return false; } - } } - return fileDataList; - } - - private boolean isFileModuleFile(String fileName, Collection filesCannotBeModule) { - return !filesCannotBeModule.contains(fileName); - } - @Override - public boolean isFileBaseFile(String fileName) { - return Pattern.matches(Constants.BASE_HEAT_REGEX, fileName) && !isVolFile(fileName); - } - - protected boolean isCloudSpecificArtifact(String artifact) { - if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) { - for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) { - if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) { - return false; - } - } - return true; - } else { - return false; - } - } - - private boolean isControllerBlueprintArchive(String artifact) { - return artifact.toUpperCase().contains(CONTROLLER_BLUEPRINT_ARCHIVE_FIXED_KEY_WORD); - } + private boolean isControllerBlueprintArchive(String artifact) { + return artifact.toUpperCase().contains(CONTROLLER_BLUEPRINT_ARCHIVE_FIXED_KEY_WORD); + } - private boolean isHelm(String artifact) { - return artifact.toUpperCase().contains(HELM_KEY_WORD); - } + private boolean isHelm(String artifact) { + return artifact.toUpperCase().contains(HELM_KEY_WORD); + } - private void addArtifactsToManifestFileDataList( - FilesDataStructure filesDataStructure, List fileDataList) { - Collection forArtifacts = CollectionUtils - .union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); - if (CollectionUtils.isNotEmpty(forArtifacts)) { - for (String artifact : forArtifacts) { - if (isCloudSpecificArtifact(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, artifact)); - } else if (isControllerBlueprintArchive(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.CONTROLLER_BLUEPRINT_ARCHIVE, artifact)); - } else if (isHelm(artifact)) { - fileDataList.add(createBaseFileData(FileData.Type.HELM, artifact)); - } else { - fileDataList.add(createBaseFileData(FileData.Type.OTHER, artifact)); + private void addArtifactsToManifestFileDataList(FilesDataStructure filesDataStructure, List fileDataList) { + Collection forArtifacts = CollectionUtils.union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); + if (CollectionUtils.isNotEmpty(forArtifacts)) { + for (String artifact : forArtifacts) { + if (isCloudSpecificArtifact(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT, artifact)); + } else if (isControllerBlueprintArchive(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.CONTROLLER_BLUEPRINT_ARCHIVE, artifact)); + } else if (isHelm(artifact)) { + fileDataList.add(createBaseFileData(FileData.Type.HELM, artifact)); + } else { + fileDataList.add(createBaseFileData(FileData.Type.OTHER, artifact)); + } + } } - } } - } - private void addModulesToManifestFileDataList( - FilesDataStructure filesDataStructure, List fileDataList) { - if (CollectionUtils.isNotEmpty(filesDataStructure.getModules())) { - for (Module module : filesDataStructure.getModules()) { - FileData.Type type = module.getType(); - if (type == null) { - type = FileData.Type.HEAT; + private void addModulesToManifestFileDataList(FilesDataStructure filesDataStructure, List fileDataList) { + if (CollectionUtils.isNotEmpty(filesDataStructure.getModules())) { + for (Module module : filesDataStructure.getModules()) { + FileData.Type type = module.getType(); + if (type == null) { + type = FileData.Type.HEAT; + } + FileData fileData = createBaseFileData(type, module.getYaml()); + fileData.setBase(module.getIsBase()); + addEnv(module, fileData); + addVolume(module, fileData); + fileDataList.add(fileData); + } } - FileData fileData = createBaseFileData(type, module.getYaml()); - fileData.setBase(module.getIsBase()); - addEnv(module, fileData); - addVolume(module, fileData); - fileDataList.add(fileData); - } } - } - private void addEnv(Module module, FileData fileData) { - if (Objects.nonNull(module.getEnv())) { - FileData env = createBaseFileData(FileData.Type.HEAT_ENV, module.getEnv()); - fileData.addFileData(env); + private void addEnv(Module module, FileData fileData) { + if (Objects.nonNull(module.getEnv())) { + FileData env = createBaseFileData(FileData.Type.HEAT_ENV, module.getEnv()); + fileData.addFileData(env); + } } - } - private void addVolume(Module module, FileData fileData) { - String volModule = module.getVol(); - if (Objects.nonNull(volModule)) { - FileData vol = createBaseFileData(FileData.Type.HEAT_VOL, volModule); - if (Objects.nonNull(module.getVolEnv())) { - vol.addFileData(createBaseFileData(FileData.Type.HEAT_ENV, module.getVolEnv())); - } - fileData.addFileData(vol); + private void addVolume(Module module, FileData fileData) { + String volModule = module.getVol(); + if (Objects.nonNull(volModule)) { + FileData vol = createBaseFileData(FileData.Type.HEAT_VOL, volModule); + if (Objects.nonNull(module.getVolEnv())) { + vol.addFileData(createBaseFileData(FileData.Type.HEAT_ENV, module.getVolEnv())); + } + fileData.addFileData(vol); + } } - } - - private FileData createBaseFileData(FileData.Type heat, String yaml) { - FileData fileData = new FileData(); - fileData.setType(heat); - fileData.setFile(yaml); - return fileData; - } - - private FileData createModuleFileData( - String moduleFileName, boolean isBase, Set processedFiles, - Set fileNames, List fileDataList) { - FileData moduleFileData = createBasicFileData(moduleFileName, FileData.Type.HEAT, isBase); - Optional volFile = fetchRelatedVolume(moduleFileName, fileNames); - volFile.ifPresent(vol -> { - markFileAsProcessed(vol, processedFiles); - removeFromFileDataListIfAlreadyProcessed(fileDataList, vol); - FileData volFileData = createBasicFileData(vol, FileData.Type.HEAT_VOL, null); - Optional envFile = fetchRelatedEnv(vol, fileNames); - envFile.ifPresent(env -> { - markFileAsProcessed(env, processedFiles); - removeFromFileDataListIfAlreadyProcessed(fileDataList, env); - FileData envFileData = createBasicFileData(env, FileData.Type.HEAT_ENV, null); - volFileData.addFileData(envFileData); - }); - moduleFileData.addFileData(volFileData); - }); - Optional envFile = fetchRelatedEnv(moduleFileName, fileNames); - envFile.ifPresent(env -> { - markFileAsProcessed(env, processedFiles); - FileData envFileData = createBasicFileData(env, FileData.Type.HEAT_ENV, null); - moduleFileData.addFileData(envFileData); - }); - return moduleFileData; - } - private void removeFromFileDataListIfAlreadyProcessed(List fileDataList, String vol) { - fileDataList.removeIf(fileData -> fileData.getFile().equals(vol)); - } - - private FileData createBasicFileData(String fileName, FileData.Type type, Boolean isBase) { - FileData fileData = new FileData(); - if (isBase != null) { - fileData.setBase(isBase); + private FileData createBaseFileData(FileData.Type heat, String yaml) { + FileData fileData = new FileData(); + fileData.setType(heat); + fileData.setFile(yaml); + return fileData; } - fileData.setType(type); - fileData.setFile(fileName); - return fileData; - } - - private Optional fetchRelatedEnv(String fileName, Set fileNames) { - String envFileName - = fileName.substring(0, fileName.lastIndexOf(".")) + Constants.ENV_FILE_EXTENSION; - return fileNames.contains(envFileName) ? Optional.of(envFileName) : Optional.empty(); - } - private Optional fetchRelatedVolume(String fileName, Set fileNames) { - - String volFile1stExt = - extractVolFileName(fileName, ".yaml"); - String volFile2ndExt = - extractVolFileName(fileName, ".yml"); + private FileData createModuleFileData(String moduleFileName, boolean isBase, Set processedFiles, Set fileNames, + List fileDataList) { + FileData moduleFileData = createBasicFileData(moduleFileName, FileData.Type.HEAT, isBase); + Optional volFile = fetchRelatedVolume(moduleFileName, fileNames); + volFile.ifPresent(vol -> { + markFileAsProcessed(vol, processedFiles); + removeFromFileDataListIfAlreadyProcessed(fileDataList, vol); + FileData volFileData = createBasicFileData(vol, FileData.Type.HEAT_VOL, null); + Optional envFile = fetchRelatedEnv(vol, fileNames); + envFile.ifPresent(env -> { + markFileAsProcessed(env, processedFiles); + removeFromFileDataListIfAlreadyProcessed(fileDataList, env); + FileData envFileData = createBasicFileData(env, FileData.Type.HEAT_ENV, null); + volFileData.addFileData(envFileData); + }); + moduleFileData.addFileData(volFileData); + }); + Optional envFile = fetchRelatedEnv(moduleFileName, fileNames); + envFile.ifPresent(env -> { + markFileAsProcessed(env, processedFiles); + FileData envFileData = createBasicFileData(env, FileData.Type.HEAT_ENV, null); + moduleFileData.addFileData(envFileData); + }); + return moduleFileData; + } - if (fileNames.contains(volFile1stExt)) { - return Optional.of(volFile1stExt); + private void removeFromFileDataListIfAlreadyProcessed(List fileDataList, String vol) { + fileDataList.removeIf(fileData -> fileData.getFile().equals(vol)); } - if (fileNames.contains(volFile2ndExt)) { - return Optional.of(volFile2ndExt); + + private FileData createBasicFileData(String fileName, FileData.Type type, Boolean isBase) { + FileData fileData = new FileData(); + if (isBase != null) { + fileData.setBase(isBase); + } + fileData.setType(type); + fileData.setFile(fileName); + return fileData; } - return Optional.empty(); - } - private String extractVolFileName(String fileName, String fileExt) { - return fileName.substring( - 0, fileName.lastIndexOf(".")) - + Constants.VOL_FILE_NAME_SUFFIX + fileExt; - } + private Optional fetchRelatedEnv(String fileName, Set fileNames) { + String envFileName = fileName.substring(0, fileName.lastIndexOf(".")) + Constants.ENV_FILE_EXTENSION; + return fileNames.contains(envFileName) ? Optional.of(envFileName) : Optional.empty(); + } + private Optional fetchRelatedVolume(String fileName, Set fileNames) { + String volFile1stExt = extractVolFileName(fileName, ".yaml"); + String volFile2ndExt = extractVolFileName(fileName, ".yml"); + if (fileNames.contains(volFile1stExt)) { + return Optional.of(volFile1stExt); + } + if (fileNames.contains(volFile2ndExt)) { + return Optional.of(volFile2ndExt); + } + return Optional.empty(); + } - private boolean isVolFile(String fileName) { - return fileName - .endsWith( - Constants.VOL_FILE_NAME_SUFFIX + ".yaml") - || fileName.endsWith(Constants.VOL_FILE_NAME_SUFFIX + ".yml"); - } + private String extractVolFileName(String fileName, String fileExt) { + return fileName.substring(0, fileName.lastIndexOf(".")) + Constants.VOL_FILE_NAME_SUFFIX + fileExt; + } + private boolean isVolFile(String fileName) { + return fileName.endsWith(Constants.VOL_FILE_NAME_SUFFIX + ".yaml") || fileName.endsWith(Constants.VOL_FILE_NAME_SUFFIX + ".yml"); + } - private void markFileAsProcessed(String fileName, Set processedFiles) { - processedFiles.add(fileName); - } + private void markFileAsProcessed(String fileName, Set processedFiles) { + processedFiles.add(fileName); + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateServiceValidator.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateServiceValidator.java index c366b7f4b9..a3d2e65889 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateServiceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateServiceValidator.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.vendorsoftwareproduct.services.utils; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; @@ -29,48 +33,41 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.Module; -import java.util.*; - /** * Created by Talio on 12/6/2016. */ public class CandidateServiceValidator { - public Optional> validateFileDataStructure( - FilesDataStructure filesDataStructure) { - if (Objects.isNull(filesDataStructure)) { - return Optional.empty(); - } - if (validateAtLeaseOneModuleExist(filesDataStructure)) { - return Optional.of(Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, Messages - .NO_MODULES_IN_MANIFEST.getErrorMessage()))); - } - List errors = new ArrayList<>(); - for (Module module : filesDataStructure.getModules()) { - validateModuleHaveYaml(errors, module); - validateNoVolEnvWithoutVol(errors, module); + public Optional> validateFileDataStructure(FilesDataStructure filesDataStructure) { + if (Objects.isNull(filesDataStructure)) { + return Optional.empty(); + } + if (validateAtLeaseOneModuleExist(filesDataStructure)) { + return Optional.of(Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, Messages.NO_MODULES_IN_MANIFEST.getErrorMessage()))); + } + List errors = new ArrayList<>(); + for (Module module : filesDataStructure.getModules()) { + validateModuleHaveYaml(errors, module); + validateNoVolEnvWithoutVol(errors, module); + } + return Optional.of(errors); } - return Optional.of(errors); - } - - private boolean validateAtLeaseOneModuleExist(FilesDataStructure filesDataStructure) { - return CollectionUtils.isEmpty(filesDataStructure.getModules()); - } + private boolean validateAtLeaseOneModuleExist(FilesDataStructure filesDataStructure) { + return CollectionUtils.isEmpty(filesDataStructure.getModules()); + } - private void validateNoVolEnvWithoutVol(List errors, Module module) { - if (StringUtils.isEmpty(module.getVol()) && StringUtils.isNotEmpty(module.getVolEnv())) { - errors.add(new ErrorMessage(ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MODULE_IN_MANIFEST_VOL_ENV_NO_VOL.getErrorMessage(), - module.getName()))); + private void validateNoVolEnvWithoutVol(List errors, Module module) { + if (StringUtils.isEmpty(module.getVol()) && StringUtils.isNotEmpty(module.getVolEnv())) { + errors.add(new ErrorMessage(ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(Messages.MODULE_IN_MANIFEST_VOL_ENV_NO_VOL.getErrorMessage(), module.getName()))); + } } - } - private void validateModuleHaveYaml(List errors, Module module) { - if (StringUtils.isEmpty(module.getYaml())) { - errors.add(new ErrorMessage(ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MODULE_IN_MANIFEST_NO_YAML.getErrorMessage(), - module.getName()))); + private void validateModuleHaveYaml(List errors, Module module) { + if (StringUtils.isEmpty(module.getYaml())) { + errors.add(new ErrorMessage(ErrorLevel.ERROR, + ErrorMessagesFormatBuilder.getErrorWithParameters(Messages.MODULE_IN_MANIFEST_NO_YAML.getErrorMessage(), module.getName()))); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManager.java index 4f3a756baf..5c27ef3fbf 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManager.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManager.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; +import java.util.List; +import java.util.Map; import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionCreationMethod; @@ -23,54 +24,45 @@ import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; -import java.util.List; -import java.util.Map; - public interface ActionVersioningManager { - void register(String entityType, VersionableEntityMetadata entityMetadata); - - Version create(String entityType, String entityId, String user); - - void delete(String entityType, String entityId, String user); + void register(String entityType, VersionableEntityMetadata entityMetadata); - void undoDelete(String entityType, String entityId, String user); + Version create(String entityType, String entityId, String user); - Version checkout(String entityType, String entityId, String user); + void delete(String entityType, String entityId, String user); - Version undoCheckout(String entityType, String entityId, String user); + void undoDelete(String entityType, String entityId, String user); - Version checkin(String entityType, String entityId, String user, String checkinDescription); + Version checkout(String entityType, String entityId, String user); - Version submit(String entityType, String entityId, String user, String submitDescription); + Version undoCheckout(String entityType, String entityId, String user); - VersionInfo getEntityVersionInfo(String entityType, String entityId, String user, - VersionableEntityAction action); + Version checkin(String entityType, String entityId, String user, String checkinDescription); - Map listEntitiesVersionInfo(String entityType, String user, - VersionableEntityAction action); + Version submit(String entityType, String entityId, String user, String submitDescription); - Map listDeletedEntitiesVersionInfo(String entityType, String user, - VersionableEntityAction action); + VersionInfo getEntityVersionInfo(String entityType, String entityId, String user, VersionableEntityAction action); + Map listEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action); - List list(String itemId); // TODO: 5/24/2017 filter (by status for example) + Map listDeletedEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action); - Version get(String itemId, Version version); + List list(String itemId); // TODO: 5/24/2017 filter (by status for example) - Version create(String itemId, Version version, - VersionCreationMethod creationMethod); + Version get(String itemId, Version version); - void submit(String itemId, Version version, String submitDescription); + Version create(String itemId, Version version, VersionCreationMethod creationMethod); - void publish(String itemId, Version version, String message); + void submit(String itemId, Version version, String submitDescription); - void sync(String itemId, Version version); + void publish(String itemId, Version version, String message); - void forceSync(String itemId, Version version); + void sync(String itemId, Version version); - void revert(String itemId, Version version, String revisionId); + void forceSync(String itemId, Version version); - List listRevisions(String itemId, Version version); + void revert(String itemId, Version version, String revisionId); + List listRevisions(String itemId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManagerFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManagerFactory.java index 4ab659ac11..7fd8ba2d19 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ActionVersioningManagerFactory.java @@ -13,16 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class ActionVersioningManagerFactory extends - AbstractComponentFactory { +public abstract class ActionVersioningManagerFactory extends AbstractComponentFactory { - public static ActionVersioningManagerFactory getInstance() { - return AbstractFactory.getInstance(ActionVersioningManagerFactory.class); - } + public static ActionVersioningManagerFactory getInstance() { + return AbstractFactory.getInstance(ActionVersioningManagerFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManager.java index ad3d1f304c..0762be259e 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManager.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManager.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; public interface AsdcItemManager extends ItemManager { diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManagerFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManagerFactory.java index a2095b8663..4deae0058a 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/AsdcItemManagerFactory.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -21,7 +20,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class AsdcItemManagerFactory extends AbstractComponentFactory { - public static AsdcItemManagerFactory getInstance() { - return AbstractFactory.getInstance(AsdcItemManagerFactory.class); - } + public static AsdcItemManagerFactory getInstance() { + return AbstractFactory.getInstance(AsdcItemManagerFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java index 1ab6b4fc08..3e0005d6ce 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java @@ -13,33 +13,30 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.Item; - import java.util.Collection; import java.util.function.Predicate; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; public interface ItemManager { - Collection list(Predicate predicate); + Collection list(Predicate predicate); - Item get(String itemId); + Item get(String itemId); - Item create(Item item); + Item create(Item item); - void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, - VersionStatus removedVersionStatus); + void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, VersionStatus removedVersionStatus); - void archive(Item item); + void archive(Item item); - void restore(Item item); + void restore(Item item); - void delete(Item item); + void delete(Item item); - void updateName(String itemId, String name); + void updateName(String itemId, String name); - void update(Item item); + void update(Item item); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java index 314ffceadb..fd55b0490c 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ItemManagerFactory extends AbstractComponentFactory { - public static ItemManagerFactory getInstance() { - return AbstractFactory.getInstance(ItemManagerFactory.class); - } + public static ItemManagerFactory getInstance() { + return AbstractFactory.getInstance(ItemManagerFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java index 8d96297380..4e764dd411 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java @@ -13,37 +13,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning; +import java.util.List; import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionCreationMethod; -import java.util.List; - public interface VersioningManager { - List list(String itemId); // TODO: 5/24/2017 filter (by status for example) + List list(String itemId); // TODO: 5/24/2017 filter (by status for example) - Version get(String itemId, Version version); + Version get(String itemId, Version version); - Version create(String itemId, Version version, - VersionCreationMethod creationMethod); + Version create(String itemId, Version version, VersionCreationMethod creationMethod); - void submit(String itemId, Version version, String submitDescription); + void submit(String itemId, Version version, String submitDescription); - void publish(String itemId, Version version, String message); + void publish(String itemId, Version version, String message); - void sync(String itemId, Version version); + void sync(String itemId, Version version); - void forceSync(String itemId, Version version); + void forceSync(String itemId, Version version); - void revert(String itemId, Version version, String revisionId); + void revert(String itemId, Version version, String revisionId); - List listRevisions(String itemId, Version version); + List listRevisions(String itemId, Version version); - void updateVersion(String itemId, Version version); + void updateVersion(String itemId, Version version); - void clean(String itemId, Version version); + void clean(String itemId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManagerFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManagerFactory.java index 089777bbe6..b0cf94355c 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManagerFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManagerFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class VersioningManagerFactory extends AbstractComponentFactory { - public static VersioningManagerFactory getInstance() { - return AbstractFactory.getInstance(VersioningManagerFactory.class); - } + public static VersioningManagerFactory getInstance() { + return AbstractFactory.getInstance(VersioningManagerFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java index 1e5efb244e..27219ce1a4 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java @@ -24,6 +24,7 @@ package org.openecomp.sdc.versioning; * @since July 10, 2017 */ public class VersioningNotificationConstansts { + public static final String ITEM_NAME = "itemName"; public static final String ITEM_ID = "itemId"; public static final String SUBMIT_DESCRIPTION = "description"; diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningUtil.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningUtil.java index 7411edec08..52da00c0d1 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningUtil.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.versioning.dao.types.Version; @@ -29,168 +32,136 @@ import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder; import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder; import org.openecomp.sdc.versioning.types.VersionInfo; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - /** * The type Versioning util. */ public class VersioningUtil { - private VersioningUtil() { - // prevent instantiation - } - - /** - * Validate entity existence. - * - * @param the type parameter - * @param retrievedEntity the retrieved entity - * @param inputEntity the input entity - * @param firstClassCitizenType the first class citizen type - */ - public static void validateEntityExistence(Object retrievedEntity, - T inputEntity, - String firstClassCitizenType) { - if (retrievedEntity == null) { - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - inputEntity.getEntityType(), - inputEntity.getId(), - firstClassCitizenType, - inputEntity.getFirstClassCitizenId(), - inputEntity.getVersion()).build()); + private VersioningUtil() { + // prevent instantiation } - } - /** - * Validate entities existence. - * - * @param the type parameter - * @param the type parameter - * @param entityIds the entity ids - * @param entity the entity - * @param entityDao the entity dao - * @param firstClassCitizenType the first class citizen type - */ - public static > void validateEntitiesExistence( - Set entityIds, T entity, D entityDao, String firstClassCitizenType) { - if (entityIds == null) { - return; - } - - List nonExistingIds = new ArrayList<>(); - for (String entityId : entityIds) { - entity.setId(entityId); - if (entityDao.get(entity) == null) { - nonExistingIds.add(entityId); - } - } - - if (!nonExistingIds.isEmpty()) { - if (nonExistingIds.size() == 1) { - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - entity.getEntityType(), - nonExistingIds.get(0), - firstClassCitizenType, - entity.getFirstClassCitizenId(), - entity.getVersion()).build()); - } - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - entity.getEntityType(), - nonExistingIds, - firstClassCitizenType, - entity.getFirstClassCitizenId(), - entity.getVersion()).build()); + /** + * Validate entity existence. + * + * @param the type parameter + * @param retrievedEntity the retrieved entity + * @param inputEntity the input entity + * @param firstClassCitizenType the first class citizen type + */ + public static void validateEntityExistence(Object retrievedEntity, T inputEntity, String firstClassCitizenType) { + if (retrievedEntity == null) { + throw new CoreException( + new VersionableSubEntityNotFoundErrorBuilder(inputEntity.getEntityType(), inputEntity.getId(), firstClassCitizenType, + inputEntity.getFirstClassCitizenId(), inputEntity.getVersion()).build()); + } } - } - /** - * Validate contained entities existence. - * - * @param the type parameter - * @param containedEntityType the contained entity type - * @param inputContainedEntityIds the input contained entity ids - * @param containingEntity the containing entity - * @param retrievedContainedEntityIds the retrieved contained entity ids - */ - public static void validateContainedEntitiesExistence( - String containedEntityType, Set inputContainedEntityIds, T containingEntity, - Set retrievedContainedEntityIds) { - if (inputContainedEntityIds == null) { - return; + /** + * Validate entities existence. + * + * @param the type parameter + * @param the type parameter + * @param entityIds the entity ids + * @param entity the entity + * @param entityDao the entity dao + * @param firstClassCitizenType the first class citizen type + */ + public static > void validateEntitiesExistence(Set entityIds, T entity, D entityDao, + String firstClassCitizenType) { + if (entityIds == null) { + return; + } + List nonExistingIds = new ArrayList<>(); + for (String entityId : entityIds) { + entity.setId(entityId); + if (entityDao.get(entity) == null) { + nonExistingIds.add(entityId); + } + } + if (!nonExistingIds.isEmpty()) { + if (nonExistingIds.size() == 1) { + throw new CoreException( + new VersionableSubEntityNotFoundErrorBuilder(entity.getEntityType(), nonExistingIds.get(0), firstClassCitizenType, + entity.getFirstClassCitizenId(), entity.getVersion()).build()); + } + throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder(entity.getEntityType(), nonExistingIds, firstClassCitizenType, + entity.getFirstClassCitizenId(), entity.getVersion()).build()); + } } - List nonExistingIds = inputContainedEntityIds.stream() - .filter(entityId -> !retrievedContainedEntityIds.contains(entityId)) - .collect(Collectors.toList()); - - if (!nonExistingIds.isEmpty()) { - if (nonExistingIds.size() == 1) { - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - containedEntityType, - nonExistingIds.get(0), - containingEntity.getEntityType(), - containingEntity.getId(), - containingEntity.getVersion()).build()); - } - throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder( - containedEntityType, - nonExistingIds, - containingEntity.getEntityType(), - containingEntity.getId(), - containingEntity.getVersion()).build()); + /** + * Validate contained entities existence. + * + * @param the type parameter + * @param containedEntityType the contained entity type + * @param inputContainedEntityIds the input contained entity ids + * @param containingEntity the containing entity + * @param retrievedContainedEntityIds the retrieved contained entity ids + */ + public static void validateContainedEntitiesExistence(String containedEntityType, + Set inputContainedEntityIds, T containingEntity, + Set retrievedContainedEntityIds) { + if (inputContainedEntityIds == null) { + return; + } + List nonExistingIds = inputContainedEntityIds.stream().filter(entityId -> !retrievedContainedEntityIds.contains(entityId)) + .collect(Collectors.toList()); + if (!nonExistingIds.isEmpty()) { + if (nonExistingIds.size() == 1) { + throw new CoreException( + new VersionableSubEntityNotFoundErrorBuilder(containedEntityType, nonExistingIds.get(0), containingEntity.getEntityType(), + containingEntity.getId(), containingEntity.getVersion()).build()); + } + throw new CoreException( + new VersionableSubEntityNotFoundErrorBuilder(containedEntityType, nonExistingIds, containingEntity.getEntityType(), + containingEntity.getId(), containingEntity.getVersion()).build()); + } } - } - /** - * Resolve version version. - * - * @param requestedVersion the requested version - * @param versionInfo the version info - * @param finalOnly the final only - * @return the version - */ - public static Version resolveVersion(Version requestedVersion, VersionInfo versionInfo, - boolean finalOnly) { - if (requestedVersion == null) { - if (finalOnly) { - if (versionInfo.getLatestFinalVersion() == null) { - throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + /** + * Resolve version version. + * + * @param requestedVersion the requested version + * @param versionInfo the version info + * @param finalOnly the final only + * @return the version + */ + public static Version resolveVersion(Version requestedVersion, VersionInfo versionInfo, boolean finalOnly) { + if (requestedVersion == null) { + if (finalOnly) { + if (versionInfo.getLatestFinalVersion() == null) { + throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + } + requestedVersion = versionInfo.getLatestFinalVersion(); + } else { + requestedVersion = versionInfo.getActiveVersion(); + } + } else { + if ((finalOnly && !requestedVersion.isFinal()) || !versionInfo.getViewableVersions().contains(requestedVersion)) { + throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + } } - requestedVersion = versionInfo.getLatestFinalVersion(); - } else { - requestedVersion = versionInfo.getActiveVersion(); - } - } else { - if ((finalOnly && !requestedVersion.isFinal()) - || !versionInfo.getViewableVersions().contains(requestedVersion)) { - throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); - } + return requestedVersion; } - return requestedVersion; - } - /** - * Resolve version. - * - * @param requestedVersion the requested version - * @param versionInfo the version info - * @return the version - */ - public static Version resolveVersion(Version requestedVersion, VersionInfo versionInfo, - String user) { - if (requestedVersion == null) { - requestedVersion = versionInfo.getActiveVersion(); - } - if (versionInfo.getActiveVersion().equals(requestedVersion) - && user.equals(versionInfo.getLockingUser())) { - requestedVersion.setStatus(VersionStatus.Locked); - } - if (!versionInfo.getViewableVersions().contains(requestedVersion)) { - throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + /** + * Resolve version. + * + * @param requestedVersion the requested version + * @param versionInfo the version info + * @return the version + */ + public static Version resolveVersion(Version requestedVersion, VersionInfo versionInfo, String user) { + if (requestedVersion == null) { + requestedVersion = versionInfo.getActiveVersion(); + } + if (versionInfo.getActiveVersion().equals(requestedVersion) && user.equals(versionInfo.getLockingUser())) { + requestedVersion.setStatus(VersionStatus.Locked); + } + if (!versionInfo.getViewableVersions().contains(requestedVersion)) { + throw new CoreException(new RequestedVersionInvalidErrorBuilder().build()); + } + return requestedVersion; } - return requestedVersion; - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java index d1db91d670..17b047cdca 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java @@ -19,18 +19,18 @@ */ package org.openecomp.sdc.versioning.dao; -import org.openecomp.sdc.versioning.types.Item; - import java.util.Collection; +import org.openecomp.sdc.versioning.types.Item; public interface ItemDao { - Collection list(); - Item get(Item item); + Collection list(); + + Item get(Item item); - Item create(Item item); + Item create(Item item); - void delete(Item item); + void delete(Item item); - void update(Item item); + void update(Item item); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java index 36edaa9aa9..69f6c03575 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java @@ -17,14 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class ItemDaoFactory extends AbstractComponentFactory { - public static ItemDaoFactory getInstance() { - return AbstractFactory.getInstance(ItemDaoFactory.class); - } + + public static ItemDaoFactory getInstance() { + return AbstractFactory.getInstance(ItemDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java index cac4c4e939..46a6a36e59 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java @@ -25,25 +25,26 @@ import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; public interface VersionDao { - List list(String itemId); - void create(String itemId, Version version); + List list(String itemId); - void update(String itemId, Version version); + void create(String itemId, Version version); - Optional get(String itemId, Version version); + void update(String itemId, Version version); - void delete(String itemId, Version version); + Optional get(String itemId, Version version); - void publish(String itemId, Version version, String message); + void delete(String itemId, Version version); - void sync(String itemId, Version version); + void publish(String itemId, Version version, String message); - void forceSync(String itemId, Version version); + void sync(String itemId, Version version); - void clean(String itemId, Version version); + void forceSync(String itemId, Version version); - void revert(String itemId, Version version, String revisionId); + void clean(String itemId, Version version); - List listRevisions(String itemId, Version version); + void revert(String itemId, Version version, String revisionId); + + List listRevisions(String itemId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java index 845b248d7e..89e2c56813 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java @@ -17,14 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class VersionDaoFactory extends AbstractComponentFactory { - public static VersionDaoFactory getInstance() { - return AbstractFactory.getInstance(VersionDaoFactory.class); - } + + public static VersionDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDao.java index 260214eb07..2d33fc1eb4 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.dao.BaseDao; diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDaoFactory.java index ebdb1a590b..2593cc5491 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; public abstract class VersionInfoDaoFactory extends AbstractComponentFactory { - public static VersionInfoDaoFactory getInstance() { - return AbstractFactory.getInstance(VersionInfoDaoFactory.class); - } + + public static VersionInfoDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionInfoDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDao.java index ca09cdb532..3d52f6dc81 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.dao.BaseDao; diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDaoFactory.java index d14cbfeb0b..bf0c23f5a7 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionInfoDeletedDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; - import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class VersionInfoDeletedDaoFactory - extends AbstractComponentFactory { - public static VersionInfoDeletedDaoFactory getInstance() { - return AbstractFactory.getInstance(VersionInfoDeletedDaoFactory.class); - } +public abstract class VersionInfoDeletedDaoFactory extends AbstractComponentFactory { + + public static VersionInfoDeletedDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionInfoDeletedDaoFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableDao.java index 12cef62f44..3f1bdf2a81 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; public interface VersionableDao { - void registerVersioning(String versionableEntityType); + + void registerVersioning(String versionableEntityType); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDao.java index 9ba042ba27..24d091a934 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDao.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.sdc.versioning.dao.types.Version; @@ -25,12 +24,9 @@ import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; public interface VersionableEntityDao { - void initVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version baseVersion, Version newVersion); + void initVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version baseVersion, Version newVersion); - void deleteVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version versionToDelete, Version backToVersion); + void deleteVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version versionToDelete, Version backToVersion); - void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version versionToClose); + void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version versionToClose); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDaoFactory.java index 870a7892ac..6b4d4de13f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionableEntityDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; -public abstract class VersionableEntityDaoFactory - extends AbstractComponentFactory { - public static VersionableEntityDaoFactory getInstance() { - return AbstractFactory.getInstance(VersionableEntityDaoFactory.class); - } +public abstract class VersionableEntityDaoFactory extends AbstractComponentFactory { + + public static VersionableEntityDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionableEntityDaoFactory.class); + } - public abstract VersionableEntityDao createInterface(VersionableEntityStoreType storeType); + public abstract VersionableEntityDao createInterface(VersionableEntityStoreType storeType); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java index d0997cf16e..418ec4c741 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java @@ -19,15 +19,16 @@ */ package org.openecomp.sdc.versioning.dao.types; +import java.util.Date; import lombok.Getter; import lombok.Setter; -import java.util.Date; @Getter @Setter public class Revision { - private String id; - private String message; - private Date time; - private String user; + + private String id; + private String message; + private Date time; + private String user; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java index ed33a39b00..95b71dc514 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java @@ -20,17 +20,14 @@ package org.openecomp.sdc.versioning.dao.types; public enum SynchronizationState { - UpToDate("Up to date"), - OutOfSync("Out of sync"), - Merging("Merging"); + UpToDate("Up to date"), OutOfSync("Out of sync"), Merging("Merging"); + private String displayName; - private String displayName; + SynchronizationState(String displayName) { + this.displayName = displayName; + } - SynchronizationState(String displayName) { - this.displayName = displayName; - } - - public String toString() { - return this.displayName; - } + public String toString() { + return this.displayName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/UserCandidateVersion.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/UserCandidateVersion.java index 9dfab56b6d..8d863076e0 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/UserCandidateVersion.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/UserCandidateVersion.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.Frozen; @@ -33,8 +32,8 @@ import lombok.Setter; @AllArgsConstructor @NoArgsConstructor public class UserCandidateVersion { - private String user; - @Frozen - private Version version; -} + private String user; + @Frozen + private Version version; +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java index d0efcf93fe..b75967f711 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,141 +17,138 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.Transient; import com.datastax.driver.mapping.annotations.UDT; +import java.util.Date; +import java.util.Map; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.Date; -import java.util.Map; - @UDT(name = "version", keyspace = "dox") @Getter @Setter @NoArgsConstructor public class Version { - public static final String VERSION_STRING_VIOLATION_MSG = - "Version string must be in the format of: {integer}.{integer}"; - - @Transient - private String id; - private int major; // TODO: 6/7/2017 remove! - private int minor; // TODO: 6/7/2017 remove! - @Transient - private String name; - @Transient - private String description; - @Transient - private String baseId; - @Transient - private Date creationTime; - @Transient - private Date modificationTime; - @Transient - private VersionStatus status = VersionStatus.Draft; - @Transient - private VersionState state; - @Transient - private Map additionalInfo; - - public Version(String id) { - this.id = id; - } - @Deprecated - public Version(int major, int minor) { - this.major = major; - this.minor = minor; - } - - /** - * Value of version. - * - * @param versionString the version string - * @return the version - */ - public static Version valueOf(String versionString) { - if (versionString == null) { - return null; - } - String[] versionLevels = versionString.split("\\."); - Version version; - if (versionLevels.length != 2) { - throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); - } - try { - version = new Version(Integer.parseInt(versionLevels[0]), Integer.parseInt(versionLevels[1])); - } catch (Exception ex) { - throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + public static final String VERSION_STRING_VIOLATION_MSG = "Version string must be in the format of: {integer}.{integer}"; + @Transient + private String id; + private int major; // TODO: 6/7/2017 remove! + + private int minor; // TODO: 6/7/2017 remove! + @Transient + private String name; + @Transient + private String description; + @Transient + private String baseId; + @Transient + private Date creationTime; + @Transient + private Date modificationTime; + @Transient + private VersionStatus status = VersionStatus.Draft; + @Transient + private VersionState state; + @Transient + private Map additionalInfo; + + public Version(String id) { + this.id = id; } - return version; - } - public Version calculateNextCandidate() { - return new Version(major, minor + 1); - } + @Deprecated + public Version(int major, int minor) { + this.major = major; + this.minor = minor; + } - public Version calculateNextFinal() { - return new Version(major + 1, 0); - } + /** + * Value of version. + * + * @param versionString the version string + * @return the version + */ + public static Version valueOf(String versionString) { + if (versionString == null) { + return null; + } + String[] versionLevels = versionString.split("\\."); + Version version; + if (versionLevels.length != 2) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + try { + version = new Version(Integer.parseInt(versionLevels[0]), Integer.parseInt(versionLevels[1])); + } catch (Exception ex) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + return version; + } - @Transient - public boolean isFinal() { - return major != 0 && minor == 0; - } + public Version calculateNextCandidate() { + return new Version(major, minor + 1); + } - @Override - public int hashCode() { - int result = major; - result = 31 * result + minor; - return result; - } + public Version calculateNextFinal() { + return new Version(major + 1, 0); + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; + @Transient + public boolean isFinal() { + return major != 0 && minor == 0; } - if (obj == null || getClass() != obj.getClass()) { - return false; + + @Override + public int hashCode() { + int result = major; + result = 31 * result + minor; + return result; } - Version version = (Version) obj; - return major == version.major && minor == version.minor; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null || getClass() != obj.getClass()) { + return false; + } + Version version = (Version) obj; + return major == version.major && minor == version.minor; + } - public int compareTo(Version other){ - if (this.major>other.major) { - return 1; - } else if(this.major other.major) { + return 1; + } else if (this.major < other.major) { + return -1; + } else if (this.major == other.major) { + return Integer.compare(this.minor, other.minor); + } + return 0; } - return 0; - } - @Override - public String toString() { - return name != null ? name : major + "." + minor; - } + @Override + public String toString() { + return name != null ? name : major + "." + minor; + } - @Override - public Version clone() { - Version version = new Version(); - version.setStatus(this.getStatus()); - version.setCreationTime(this.getCreationTime()); - version.setName(this.getName()); - version.setBaseId(this.getBaseId()); - version.setMajor(this.major); - version.setMinor(this.minor); - version.setModificationTime(this.getModificationTime()); - version.setDescription(this.description); - version.setId(this.getId()); - return version; - } -} \ No newline at end of file + @Override + public Version clone() { + Version version = new Version(); + version.setStatus(this.getStatus()); + version.setCreationTime(this.getCreationTime()); + version.setName(this.getName()); + version.setBaseId(this.getBaseId()); + version.setMajor(this.major); + version.setMinor(this.minor); + version.setModificationTime(this.getModificationTime()); + version.setDescription(this.description); + version.setId(this.getId()); + return version; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionHistoryEntity.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionHistoryEntity.java index b382ce5401..8b6e9e34fa 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionHistoryEntity.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionHistoryEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.Column; @@ -34,20 +33,18 @@ import lombok.Setter; @NoArgsConstructor public class VersionHistoryEntity { - @PartitionKey - @Column(name = "entity_id") - @Frozen - private VersionableEntityId entityId; - - @Column(name = "active_version") - @Frozen - private Version version; - - private String user; - private String description; - private VersionType type; + @PartitionKey + @Column(name = "entity_id") + @Frozen + private VersionableEntityId entityId; + @Column(name = "active_version") + @Frozen + private Version version; + private String user; + private String description; + private VersionType type; - public VersionHistoryEntity(VersionableEntityId entityId) { - this.entityId = entityId; - } + public VersionHistoryEntity(VersionableEntityId entityId) { + this.entityId = entityId; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoDeletedEntity.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoDeletedEntity.java index 12b82f7aed..06164f60f6 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoDeletedEntity.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoDeletedEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -26,47 +25,39 @@ import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.FrozenValue; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.util.HashSet; +import java.util.Set; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.HashSet; -import java.util.Set; - @Table(keyspace = "dox", name = "version_info_deleted") @Getter @Setter @NoArgsConstructor public class VersionInfoDeletedEntity { - @PartitionKey - @Column(name = "entity_type") - private String entityType; - - @ClusteringColumn - @Column(name = "entity_id") - private String entityId; - - @Column(name = "active_version") - @Frozen - private Version activeVersion; - - private VersionStatus status; - - @Frozen - private UserCandidateVersion candidate; - - @Column(name = "viewable_versions") - @FrozenValue - private Set viewableVersions = new HashSet<>(); - - @Column(name = "latest_final_version") - @Frozen - private Version latestFinalVersion; - - public VersionInfoDeletedEntity(String entityType, String entityId) { - this.entityType = entityType; - this.entityId = entityId; - } - + @PartitionKey + @Column(name = "entity_type") + private String entityType; + @ClusteringColumn + @Column(name = "entity_id") + private String entityId; + @Column(name = "active_version") + @Frozen + private Version activeVersion; + private VersionStatus status; + @Frozen + private UserCandidateVersion candidate; + @Column(name = "viewable_versions") + @FrozenValue + private Set viewableVersions = new HashSet<>(); + @Column(name = "latest_final_version") + @Frozen + private Version latestFinalVersion; + + public VersionInfoDeletedEntity(String entityType, String entityId) { + this.entityType = entityType; + this.entityId = entityId; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoEntity.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoEntity.java index 84444a30c6..4f3811b25a 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoEntity.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionInfoEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.ClusteringColumn; @@ -26,46 +25,39 @@ import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.FrozenValue; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import java.util.HashSet; +import java.util.Set; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import java.util.HashSet; -import java.util.Set; - @Table(keyspace = "dox", name = "version_info") @Getter @Setter @NoArgsConstructor public class VersionInfoEntity { - @PartitionKey - @Column(name = "entity_type") - private String entityType; - - @ClusteringColumn - @Column(name = "entity_id") - private String entityId; - - @Column(name = "active_version") - @Frozen - private Version activeVersion; - - private VersionStatus status; - - @Frozen - private UserCandidateVersion candidate; - - @Column(name = "viewable_versions") - @FrozenValue - private Set viewableVersions = new HashSet<>(); - - @Column(name = "latest_final_version") - @Frozen - private Version latestFinalVersion; - - public VersionInfoEntity(String entityType, String entityId) { - this.entityType = entityType; - this.entityId = entityId; - } + @PartitionKey + @Column(name = "entity_type") + private String entityType; + @ClusteringColumn + @Column(name = "entity_id") + private String entityId; + @Column(name = "active_version") + @Frozen + private Version activeVersion; + private VersionStatus status; + @Frozen + private UserCandidateVersion candidate; + @Column(name = "viewable_versions") + @FrozenValue + private Set viewableVersions = new HashSet<>(); + @Column(name = "latest_final_version") + @Frozen + private Version latestFinalVersion; + + public VersionInfoEntity(String entityType, String entityId) { + this.entityType = entityType; + this.entityId = entityId; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java index b4099e9409..f2abf695a1 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java @@ -25,6 +25,7 @@ import lombok.Setter; @Getter @Setter public class VersionState { - private SynchronizationState synchronizationState; - private boolean dirty; + + private SynchronizationState synchronizationState; + private boolean dirty; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java index 6cf662c37a..86bbc5eb45 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.dao.types; public enum VersionStatus { - Draft, - Locked, /* todo remove!!*/ - Certified, - Deprecated, - Deleted + Draft, + Locked, /* todo remove!!*/ + Certified, + Deprecated, + Deleted } + diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionType.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionType.java index befbae6631..b4a5a9b467 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionType.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionType.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; -public enum VersionType { - Draft, - Finalized; -} +public enum VersionType {Draft, Finalized;} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntity.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntity.java index d909af86a3..c45cdce21a 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntity.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,27 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; public interface VersionableEntity { - String getEntityType(); + String getEntityType(); - String getFirstClassCitizenId(); + String getFirstClassCitizenId(); - String getId(); + String getId(); - void setId(String id); + void setId(String id); - Version getVersion(); + Version getVersion(); - void setVersion(Version version); + void setVersion(Version version); - default String getVersionUuId() { - return ""; - } + default String getVersionUuId() { + return ""; + } - default void setVersionUuId(String uuId) { - } + default void setVersionUuId(String uuId) { + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntityId.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntityId.java index 690b7b3689..0a3f172d77 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntityId.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionableEntityId.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.UDT; @@ -32,6 +31,7 @@ import lombok.Setter; @NoArgsConstructor @AllArgsConstructor public class VersionableEntityId { - private String type; - private String id; + + private String type; + private String id; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnEntityLockedByOtherErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnEntityLockedByOtherErrorBuilder.java index b46deeae87..8f5c1dc230 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnEntityLockedByOtherErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnEntityLockedByOtherErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,22 +27,19 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class CheckinOnEntityLockedByOtherErrorBuilder extends BaseErrorBuilder { - static final String CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = - "Can not check in versionable entity %s with id %s since it is checked out by other " - + "user: %s."; + static final String CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = + "Can not check in versionable entity %s with id %s since it is checked out by other " + "user: %s."; - /** - * Instantiates a new Checkin on entity locked by other error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public CheckinOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, - String lockingUser) { - getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, lockingUser)); - } + /** + * Instantiates a new Checkin on entity locked by other error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public CheckinOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnUnlockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnUnlockedEntityErrorBuilder.java index 1ed8476534..e88a1ee5ef 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnUnlockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckinOnUnlockedEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,19 +27,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class CheckinOnUnlockedEntityErrorBuilder extends BaseErrorBuilder { - static final String CHECKIN_ON_UNLOCKED_ENTITY_MSG = - "Can not check in versionable entity %s with id %s since it is not checked out."; + static final String CHECKIN_ON_UNLOCKED_ENTITY_MSG = "Can not check in versionable entity %s with id %s since it is not checked out."; - /** - * Instantiates a new Checkin on unlocked entity error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public CheckinOnUnlockedEntityErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKIN_ON_UNLOCKED_ENTITY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(CHECKIN_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); - } + /** + * Instantiates a new Checkin on unlocked entity error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public CheckinOnUnlockedEntityErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKIN_ON_UNLOCKED_ENTITY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(CHECKIN_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckoutOnLockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckoutOnLockedEntityErrorBuilder.java index c56b08f9f7..50682dae79 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckoutOnLockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/CheckoutOnLockedEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,24 +27,19 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class CheckoutOnLockedEntityErrorBuilder extends BaseErrorBuilder { - static final String CHECKOT_ON_LOCKED_ENTITY_MSG = - "Can not check out versionable entity %s with id %s since it is checked out by " - + "other user: %s."; - - /** - * Instantiates a new Checkout on locked entity error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public CheckoutOnLockedEntityErrorBuilder(String entityType, String entityId, - String lockingUser) { - getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(CHECKOT_ON_LOCKED_ENTITY_MSG, entityType, entityId, lockingUser)); - } - + static final String CHECKOT_ON_LOCKED_ENTITY_MSG = + "Can not check out versionable entity %s with id %s since it is checked out by " + "other user: %s."; + /** + * Instantiates a new Checkout on locked entity error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public CheckoutOnLockedEntityErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.CHECKOT_ON_LOCKED_ENTITY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(CHECKOT_ON_LOCKED_ENTITY_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/DeleteOnLockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/DeleteOnLockedEntityErrorBuilder.java index da181ceb77..0d3a7a1736 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/DeleteOnLockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/DeleteOnLockedEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,22 +27,18 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class DeleteOnLockedEntityErrorBuilder extends BaseErrorBuilder { - static final String DELETE_ON_LOCKED_ENTITY_MSG = - "Can not delete versionable entity %s with id %s since it is checked out by other user: %s."; - - /** - * Instantiates a new Delete on locked entity error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public DeleteOnLockedEntityErrorBuilder(String entityType, String entityId, String lockingUser) { - getErrorCodeBuilder().withId(VersioningErrorCodes.DELETE_ON_LOCKED_ENTITY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(DELETE_ON_LOCKED_ENTITY_MSG, entityType, entityId, lockingUser)); - } - + static final String DELETE_ON_LOCKED_ENTITY_MSG = "Can not delete versionable entity %s with id %s since it is checked out by other user: %s."; + /** + * Instantiates a new Delete on locked entity error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public DeleteOnLockedEntityErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.DELETE_ON_LOCKED_ENTITY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(DELETE_ON_LOCKED_ENTITY_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnEntityLockedByOtherErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnEntityLockedByOtherErrorBuilder.java index bfebfd2c31..615cf1ee9d 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnEntityLockedByOtherErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnEntityLockedByOtherErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,23 +27,18 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class EditOnEntityLockedByOtherErrorBuilder extends BaseErrorBuilder { - static final String EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = - "Versionable entity %s with id %s can not be edited since it is locked by other user %s."; - - /** - * Instantiates a new Edit on entity locked by other error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public EditOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, - String lockingUser) { - getErrorCodeBuilder().withId(VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, lockingUser)); - } - + static final String EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = "Versionable entity %s with id %s can not be edited since it is locked by other user %s."; + /** + * Instantiates a new Edit on entity locked by other error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public EditOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java index c5ba6d84af..36d16af381 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,34 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; +import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY; + import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; -import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY; - /** * The type Edit on unlocked entity error builder. */ public class EditOnUnlockedEntityErrorBuilder extends BaseErrorBuilder { - static final String EDIT_ON_UNLOCKED_ENTITY_MSG = - "Can not edit versionable entity %s with id %s since it is not checked out."; - - /** - * Instantiates a new Edit on unlocked entity error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public EditOnUnlockedEntityErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(EDIT_ON_UNLOCKED_ENTITY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(EDIT_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); - } - - + static final String EDIT_ON_UNLOCKED_ENTITY_MSG = "Can not edit versionable entity %s with id %s since it is not checked out."; + + /** + * Instantiates a new Edit on unlocked entity error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public EditOnUnlockedEntityErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(EDIT_ON_UNLOCKED_ENTITY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(EDIT_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyExistErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyExistErrorBuilder.java index 0e591598f7..c6e080540c 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyExistErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyExistErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,19 +27,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class EntityAlreadyExistErrorBuilder extends BaseErrorBuilder { - static final String VERSIONABLE_ENTITY_ALREADY_EXIST_MSG = - "Versionable entity %s with id %s already exist."; + static final String VERSIONABLE_ENTITY_ALREADY_EXIST_MSG = "Versionable entity %s with id %s already exist."; - /** - * Instantiates a new Entity already exist error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public EntityAlreadyExistErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_ENTITY_ALREADY_EXIST); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(VERSIONABLE_ENTITY_ALREADY_EXIST_MSG, entityType, entityId)); - } + /** + * Instantiates a new Entity already exist error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public EntityAlreadyExistErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_ENTITY_ALREADY_EXIST); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(VERSIONABLE_ENTITY_ALREADY_EXIST_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyFinalizedErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyFinalizedErrorBuilder.java index 7cd97216eb..d4989c4dc7 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyFinalizedErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityAlreadyFinalizedErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,21 +27,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class EntityAlreadyFinalizedErrorBuilder extends BaseErrorBuilder { - static final String SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED_MSG = - "Versionable entity %s with id %s can not be submitted since it is already final."; - - /** - * Instantiates a new Entity already finalized error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public EntityAlreadyFinalizedErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(VersioningErrorCodes.SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED_MSG, entityType, entityId)); - } - + static final String SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED_MSG = "Versionable entity %s with id %s can not be submitted since it is already final."; + /** + * Instantiates a new Entity already finalized error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public EntityAlreadyFinalizedErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(VersioningErrorCodes.SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityNotExistErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityNotExistErrorBuilder.java index 2eab4b5dac..16c9949970 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityNotExistErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EntityNotExistErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,19 +27,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class EntityNotExistErrorBuilder extends BaseErrorBuilder { - static final String VERSIONABLE_ENTITY_NOT_EXIST_MSG = - "Versionable entity %s with id %s does not exist."; + static final String VERSIONABLE_ENTITY_NOT_EXIST_MSG = "Versionable entity %s with id %s does not exist."; - /** - * Instantiates a new Entity not exist error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public EntityNotExistErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(VERSIONABLE_ENTITY_NOT_EXIST_MSG, entityType, entityId)); - } + /** + * Instantiates a new Entity not exist error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public EntityNotExistErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_ENTITY_NOT_EXIST); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(VERSIONABLE_ENTITY_NOT_EXIST_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RequestedVersionInvalidErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RequestedVersionInvalidErrorBuilder.java index aba3b8a17a..d49d0fb72b 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RequestedVersionInvalidErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RequestedVersionInvalidErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -27,17 +26,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; * The type Requested version invalid error builder. */ public class RequestedVersionInvalidErrorBuilder extends BaseErrorBuilder { - static final String REQUESTED_VERSION_INVALID_MSG = "Invalid requested version."; - /** - * Instantiates a new Requested version invalid error builder. - */ - public RequestedVersionInvalidErrorBuilder() { - getErrorCodeBuilder().withId(VersioningErrorCodes.REQUESTED_VERSION_INVALID); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(REQUESTED_VERSION_INVALID_MSG); - } + static final String REQUESTED_VERSION_INVALID_MSG = "Invalid requested version."; + /** + * Instantiates a new Requested version invalid error builder. + */ + public RequestedVersionInvalidErrorBuilder() { + getErrorCodeBuilder().withId(VersioningErrorCodes.REQUESTED_VERSION_INVALID); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(REQUESTED_VERSION_INVALID_MSG); + } /* private static List toStringList(Set versions) { List versionStrings = new ArrayList<>(versions.size()); for (Version version : versions) { @@ -45,4 +44,4 @@ public class RequestedVersionInvalidErrorBuilder extends BaseErrorBuilder { } return versionStrings; }*/ -} +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java index 4ec51297a6..7a41864dcd 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,17 +27,14 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class RevisionIdNotFoundErrorBuilder extends BaseErrorBuilder { - static final String REVISION_ID_NOT_FOUND_MSG = - "Mandatory field revision id missing"; - - /** - * Instantiates a new Versionable sub entity not found error builder. - */ - public RevisionIdNotFoundErrorBuilder() { - getErrorCodeBuilder().withId(VersioningErrorCodes.MANDATORY_FIELD_REVISION_ID_MISSING); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(REVISION_ID_NOT_FOUND_MSG); - } - + static final String REVISION_ID_NOT_FOUND_MSG = "Mandatory field revision id missing"; + /** + * Instantiates a new Versionable sub entity not found error builder. + */ + public RevisionIdNotFoundErrorBuilder() { + getErrorCodeBuilder().withId(VersioningErrorCodes.MANDATORY_FIELD_REVISION_ID_MISSING); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(REVISION_ID_NOT_FOUND_MSG); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/SubmitLockedEntityNotAllowedErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/SubmitLockedEntityNotAllowedErrorBuilder.java index 0bd1cb91ee..b801134fb9 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/SubmitLockedEntityNotAllowedErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/SubmitLockedEntityNotAllowedErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,22 +27,19 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class SubmitLockedEntityNotAllowedErrorBuilder extends BaseErrorBuilder { - static final String SUBMIT_LOCKED_ENTITY_NOT_ALLOWED_MSG = - "Versionable entity %s with id %s can not be submitted since it is currently" - + " locked by user %s."; + static final String SUBMIT_LOCKED_ENTITY_NOT_ALLOWED_MSG = + "Versionable entity %s with id %s can not be submitted since it is currently" + " locked by user %s."; - /** - * Instantiates a new Submit locked entity not allowed error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public SubmitLockedEntityNotAllowedErrorBuilder(String entityType, String entityId, - String lockingUser) { - getErrorCodeBuilder().withId(VersioningErrorCodes.SUBMIT_LOCKED_ENTITY_NOT_ALLOWED); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage( - String.format(SUBMIT_LOCKED_ENTITY_NOT_ALLOWED_MSG, entityType, entityId, lockingUser)); - } + /** + * Instantiates a new Submit locked entity not allowed error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public SubmitLockedEntityNotAllowedErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.SUBMIT_LOCKED_ENTITY_NOT_ALLOWED); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(SUBMIT_LOCKED_ENTITY_NOT_ALLOWED_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnEntityLockedByOtherErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnEntityLockedByOtherErrorBuilder.java index 3ec4b6d40b..598425127e 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnEntityLockedByOtherErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnEntityLockedByOtherErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,24 +27,19 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class UndoCheckoutOnEntityLockedByOtherErrorBuilder extends BaseErrorBuilder { - static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = - "Can not undo checkout on versionable entity %s with id %s since it is checked " - + "out by other user: %s."; + static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG = + "Can not undo checkout on versionable entity %s with id %s since it is checked " + "out by other user: %s."; - /** - * Instantiates a new Undo checkout on entity locked by other error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param lockingUser the locking user - */ - public UndoCheckoutOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, - String lockingUser) { - getErrorCodeBuilder().withId( - VersioningErrorCodes.UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, - lockingUser)); - } + /** + * Instantiates a new Undo checkout on entity locked by other error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param lockingUser the locking user + */ + public UndoCheckoutOnEntityLockedByOtherErrorBuilder(String entityType, String entityId, String lockingUser) { + getErrorCodeBuilder().withId(VersioningErrorCodes.UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER_MSG, entityType, entityId, lockingUser)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnUnlockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnUnlockedEntityErrorBuilder.java index 12771efc85..3e6b9cf81e 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnUnlockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/UndoCheckoutOnUnlockedEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -28,19 +27,17 @@ import org.openecomp.sdc.common.errors.ErrorCategory; */ public class UndoCheckoutOnUnlockedEntityErrorBuilder extends BaseErrorBuilder { - static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG = - "Can not undo checkout on versionable entity %s with id %s since it is not checked out."; + static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG = "Can not undo checkout on versionable entity %s with id %s since it is not checked out."; - /** - * Instantiates a new Undo checkout on unlocked entity error builder. - * - * @param entityType the entity type - * @param entityId the entity id - */ - public UndoCheckoutOnUnlockedEntityErrorBuilder(String entityType, String entityId) { - getErrorCodeBuilder().withId(VersioningErrorCodes.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder() - .withMessage(String.format(UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); - } + /** + * Instantiates a new Undo checkout on unlocked entity error builder. + * + * @param entityType the entity type + * @param entityId the entity id + */ + public UndoCheckoutOnUnlockedEntityErrorBuilder(String entityType, String entityId) { + getErrorCodeBuilder().withId(VersioningErrorCodes.UNDO_CHECKOUT_ON_UNLOCKED_ENTITY); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String.format(UNDO_CHECKOUT_ON_UNLOCKED_ENTITY_MSG, entityType, entityId)); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java index 2fbb880cf8..d80c44e9d4 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,61 +17,54 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; +import java.util.List; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; - /** * The type Versionable sub entity not found error builder. */ public class VersionableSubEntityNotFoundErrorBuilder extends BaseErrorBuilder { - static final String SUB_ENTITY_NOT_FOUND_MSG = - "%s with Id %s does not exist for %s with id %s and version %s"; - static final String SUB_ENTITIES_NOT_FOUND_MSG = - "%ss with Ids %s do not exist for %s with id %s and version %s"; + static final String SUB_ENTITY_NOT_FOUND_MSG = "%s with Id %s does not exist for %s with id %s and version %s"; + static final String SUB_ENTITIES_NOT_FOUND_MSG = "%ss with Ids %s do not exist for %s with id %s and version %s"; - /** - * Instantiates a new Versionable sub entity not found error builder. - * - * @param entityType the entity type - * @param entityId the entity id - * @param containingEntityType the containing entity type - * @param containingEntityId the containing entity id - * @param version the version - */ - public VersionableSubEntityNotFoundErrorBuilder(String entityType, String entityId, - String containingEntityType, - String containingEntityId, Version version) { - getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String - .format(SUB_ENTITY_NOT_FOUND_MSG, entityType, entityId, containingEntityType, - containingEntityId, version.getId())); - } + /** + * Instantiates a new Versionable sub entity not found error builder. + * + * @param entityType the entity type + * @param entityId the entity id + * @param containingEntityType the containing entity type + * @param containingEntityId the containing entity id + * @param version the version + */ + public VersionableSubEntityNotFoundErrorBuilder(String entityType, String entityId, String containingEntityType, String containingEntityId, + Version version) { + getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder() + .withMessage(String.format(SUB_ENTITY_NOT_FOUND_MSG, entityType, entityId, containingEntityType, containingEntityId, version.getId())); + } - /** - * Instantiates a new Versionable sub entity not found error builder. - * - * @param entityType the entity type - * @param entityIds the entity ids - * @param containingEntityType the containing entity type - * @param containingEntityId the containing entity id - * @param version the version - */ - public VersionableSubEntityNotFoundErrorBuilder(String entityType, List entityIds, - String containingEntityType, - String containingEntityId, Version version) { - getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(String.format(SUB_ENTITIES_NOT_FOUND_MSG, entityType, - CommonMethods.listToSeparatedString(entityIds, ','), containingEntityType, - containingEntityId, version.toString())); - } + /** + * Instantiates a new Versionable sub entity not found error builder. + * + * @param entityType the entity type + * @param entityIds the entity ids + * @param containingEntityType the containing entity type + * @param containingEntityId the containing entity id + * @param version the version + */ + public VersionableSubEntityNotFoundErrorBuilder(String entityType, List entityIds, String containingEntityType, String containingEntityId, + Version version) { + getErrorCodeBuilder().withId(VersioningErrorCodes.VERSIONABLE_SUB_ENTITY_NOT_FOUND); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(String + .format(SUB_ENTITIES_NOT_FOUND_MSG, entityType, CommonMethods.listToSeparatedString(entityIds, ','), containingEntityType, + containingEntityId, version.toString())); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java index 3dd87d5a3f..984c3bfd2c 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,33 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.errors; public class VersioningErrorCodes { - public static final String REQUESTED_VERSION_INVALID = "REQUESTED_VERSION_INVALID"; - public static final String CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER = - "CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER"; - public static final String CHECKIN_ON_UNLOCKED_ENTITY = "CHECKIN_ON_UNLOCKED_ENTITY"; - public static final String CHECKOT_ON_LOCKED_ENTITY = "CHECKOT_ON_LOCKED_ENTITY"; - public static final String DELETE_ON_LOCKED_ENTITY = "DELETE_ON_LOCKED_ENTITY"; - public static final String EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER = - "EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER"; - public static final String EDIT_ON_UNLOCKED_ENTITY = "EDIT_ON_UNLOCKED_ENTITY"; - public static final String VERSIONABLE_ENTITY_ALREADY_EXIST = "VERSIONABLE_ENTITY_ALREADY_EXIST"; - public static final String SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED = - "SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED"; - public static final String VERSIONABLE_ENTITY_NOT_EXIST = "VERSIONABLE_ENTITY_NOT_EXIST"; - public static final String VERSIONABLE_SUB_ENTITY_NOT_FOUND = "VERSIONABLE_SUB_ENTITY_NOT_FOUND"; - public static final String SUBMIT_LOCKED_ENTITY_NOT_ALLOWED = "SUBMIT_LOCKED_ENTITY_NOT_ALLOWED"; - public static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER = - "UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER"; - public static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY = "UNDO_CHECKOUT_ON_UNLOCKED_ENTITY"; - public static final String MANDATORY_FIELD_REVISION_ID_MISSING = - "MANDATORY_FIELD_REVISION_ID_MISSING"; - - - - + public static final String REQUESTED_VERSION_INVALID = "REQUESTED_VERSION_INVALID"; + public static final String CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER = "CHECKIN_ON_ENTITY_LOCKED_BY_OTHER_USER"; + public static final String CHECKIN_ON_UNLOCKED_ENTITY = "CHECKIN_ON_UNLOCKED_ENTITY"; + public static final String CHECKOT_ON_LOCKED_ENTITY = "CHECKOT_ON_LOCKED_ENTITY"; + public static final String DELETE_ON_LOCKED_ENTITY = "DELETE_ON_LOCKED_ENTITY"; + public static final String EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER = "EDIT_ON_ENTITY_LOCKED_BY_OTHER_USER"; + public static final String EDIT_ON_UNLOCKED_ENTITY = "EDIT_ON_UNLOCKED_ENTITY"; + public static final String VERSIONABLE_ENTITY_ALREADY_EXIST = "VERSIONABLE_ENTITY_ALREADY_EXIST"; + public static final String SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED = "SUBMIT_FINALIZED_ENTITY_NOT_ALLOWED"; + public static final String VERSIONABLE_ENTITY_NOT_EXIST = "VERSIONABLE_ENTITY_NOT_EXIST"; + public static final String VERSIONABLE_SUB_ENTITY_NOT_FOUND = "VERSIONABLE_SUB_ENTITY_NOT_FOUND"; + public static final String SUBMIT_LOCKED_ENTITY_NOT_ALLOWED = "SUBMIT_LOCKED_ENTITY_NOT_ALLOWED"; + public static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER = "UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER"; + public static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY = "UNDO_CHECKOUT_ON_UNLOCKED_ENTITY"; + public static final String MANDATORY_FIELD_REVISION_ID_MISSING = "MANDATORY_FIELD_REVISION_ID_MISSING"; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java index 154bc40dad..62d21676f2 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java @@ -17,47 +17,46 @@ */ package org.openecomp.sdc.versioning.types; -import lombok.Getter; -import lombok.Setter; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; - import java.util.Date; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; +import lombok.Getter; +import lombok.Setter; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; @Getter @Setter public class Item { - private String id; - private String type; - private String name; - private String owner; - private ItemStatus status; - private String description; - private Map properties = new HashMap<>(); - private Map versionStatusCounters = new EnumMap<>(VersionStatus.class); - private Date creationTime; - private Date modificationTime; - public void addProperty(String key, Object value) { - properties.put(key, value); - } + private String id; + private String type; + private String name; + private String owner; + private ItemStatus status; + private String description; + private Map properties = new HashMap<>(); + private Map versionStatusCounters = new EnumMap<>(VersionStatus.class); + private Date creationTime; + private Date modificationTime; - public void addVersionStatus(VersionStatus versionStatus) { - Integer counter = versionStatusCounters.get(versionStatus); - versionStatusCounters - .put(versionStatus, counter == null ? 1 : counter + 1); - } + public void addProperty(String key, Object value) { + properties.put(key, value); + } + + public void addVersionStatus(VersionStatus versionStatus) { + Integer counter = versionStatusCounters.get(versionStatus); + versionStatusCounters.put(versionStatus, counter == null ? 1 : counter + 1); + } - public void removeVersionStatus(VersionStatus versionStatus) { - Integer counter = versionStatusCounters.get(versionStatus); - if (counter != null) { - if (counter == 1) { - versionStatusCounters.remove(versionStatus); - } else { - versionStatusCounters.put(versionStatus, counter - 1); - } + public void removeVersionStatus(VersionStatus versionStatus) { + Integer counter = versionStatusCounters.get(versionStatus); + if (counter != null) { + if (counter == 1) { + versionStatusCounters.remove(versionStatus); + } else { + versionStatusCounters.put(versionStatus, counter - 1); + } + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/ItemStatus.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/ItemStatus.java index 4322aee856..775eef69af 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/ItemStatus.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/ItemStatus.java @@ -19,7 +19,4 @@ */ package org.openecomp.sdc.versioning.types; -public enum ItemStatus { - ACTIVE, - ARCHIVED -} +public enum ItemStatus {ACTIVE, ARCHIVED} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java index 3e443e6533..9d6a45ba36 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java @@ -29,11 +29,6 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum NotificationEventTypes { - SUBMIT("submit"), - DELETE("delete"), - ARCHIVE("archive"), - RESTORE("restore"), - COMMIT("commit"); - + SUBMIT("submit"), DELETE("delete"), ARCHIVE("archive"), RESTORE("restore"), COMMIT("commit"); private final String eventName; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/UniqueValueMetadata.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/UniqueValueMetadata.java index e12a42e2c4..ab4465fb61 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/UniqueValueMetadata.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/UniqueValueMetadata.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.types; +import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -import java.util.List; @Getter @Setter @AllArgsConstructor public class UniqueValueMetadata { - private String type; - private List uniqueConstraintIdentifiers; + + private String type; + private List uniqueConstraintIdentifiers; } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java index 1d1af6c306..66947316ee 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java @@ -20,8 +20,8 @@ package org.openecomp.sdc.versioning.types; public enum VersionCreationMethod { - /*parent_level, - same_level, - sub_level*/ - major,minor + /*parent_level, + same_level, + sub_level*/ + major, minor } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionInfo.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionInfo.java index a56c73d356..ad05688987 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionInfo.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionInfo.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,37 +17,36 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.types; +import java.util.ArrayList; +import java.util.List; import lombok.Getter; import lombok.Setter; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import java.util.ArrayList; -import java.util.List; - @Getter @Setter public class VersionInfo { - private Version activeVersion; - private Version latestFinalVersion; - private List viewableVersions = new ArrayList<>(); - private List finalVersions = new ArrayList<>(); - private VersionStatus status; - private String lockingUser; - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("VersionInfo{"); - sb.append("activeVersion=").append(activeVersion); - sb.append(", latestFinalVersion=").append(latestFinalVersion); - sb.append(", viewableVersions=").append(viewableVersions); - sb.append(", finalVersions=").append(finalVersions); - sb.append(", status=").append(status); - sb.append(", lockingUser='").append(lockingUser).append('\''); - sb.append('}'); - return sb.toString(); - } + private Version activeVersion; + private Version latestFinalVersion; + private List viewableVersions = new ArrayList<>(); + private List finalVersions = new ArrayList<>(); + private VersionStatus status; + private String lockingUser; + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("VersionInfo{"); + sb.append("activeVersion=").append(activeVersion); + sb.append(", latestFinalVersion=").append(latestFinalVersion); + sb.append(", viewableVersions=").append(viewableVersions); + sb.append(", finalVersions=").append(finalVersions); + sb.append(", status=").append(status); + sb.append(", lockingUser='").append(lockingUser).append('\''); + sb.append('}'); + return sb.toString(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityAction.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityAction.java index ef9fef2bda..45bce35174 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityAction.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityAction.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.types; -public enum VersionableEntityAction { - Read, - Write; -} +public enum VersionableEntityAction {Read, Write;} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityMetadata.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityMetadata.java index fcc02afd52..84495f6c35 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityMetadata.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityMetadata.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,35 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.types; -import lombok.Getter; -import lombok.Setter; import java.util.ArrayList; import java.util.List; +import lombok.Getter; +import lombok.Setter; @Getter @Setter public class VersionableEntityMetadata { - private VersionableEntityStoreType storeType; - private String name; - private String identifierName; - private String versionIdentifierName; - private List uniqueValuesMetadata = new ArrayList<>(); - - public VersionableEntityMetadata(String name, String identifierName, - String versionIdentifierName) { - this(VersionableEntityStoreType.Cassandra, name, identifierName, versionIdentifierName); - } + private VersionableEntityStoreType storeType; + private String name; + private String identifierName; + private String versionIdentifierName; + private List uniqueValuesMetadata = new ArrayList<>(); - public VersionableEntityMetadata(VersionableEntityStoreType storeType, String name, - String identifierName, String versionIdentifierName) { - this.storeType = storeType; - this.name = name; - this.identifierName = identifierName; - this.versionIdentifierName = versionIdentifierName; - } + public VersionableEntityMetadata(String name, String identifierName, String versionIdentifierName) { + this(VersionableEntityStoreType.Cassandra, name, identifierName, versionIdentifierName); + } + public VersionableEntityMetadata(VersionableEntityStoreType storeType, String name, String identifierName, String versionIdentifierName) { + this.storeType = storeType; + this.name = name; + this.identifierName = identifierName; + this.versionIdentifierName = versionIdentifierName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityStoreType.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityStoreType.java index 6d420100cc..4dfba514e2 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityStoreType.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionableEntityStoreType.java @@ -19,7 +19,4 @@ */ package org.openecomp.sdc.versioning.types; -public enum VersionableEntityStoreType { - Cassandra, - Zusammen -} +public enum VersionableEntityStoreType {Cassandra, Zusammen} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java index 2d64355d48..445632af3f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java @@ -19,13 +19,13 @@ */ package org.openecomp.sdc.versioning; +import java.util.Set; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionCreationMethod; -import java.util.Set; - public interface VersionCalculator { - String calculate(String baseVersion, VersionCreationMethod creationMethod); - void injectAdditionalInfo(Version version, Set existingVersions); + String calculate(String baseVersion, VersionCreationMethod creationMethod); + + void injectAdditionalInfo(Version version, Set existingVersions); } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java index 85f02cd267..0e6558564e 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -25,7 +24,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class VersionCalculatorFactory extends AbstractComponentFactory { - public static VersionCalculatorFactory getInstance() { - return AbstractFactory.getInstance(VersionCalculatorFactory.class); - } + public static VersionCalculatorFactory getInstance() { + return AbstractFactory.getInstance(VersionCalculatorFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java index 0f9c9065d4..d75cc35050 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.versioning.dao.ItemDaoFactory; import org.openecomp.sdc.versioning.dao.impl.zusammen.ItemZusammenDaoImpl; public class ItemDaoFactoryImpl extends ItemDaoFactory { - private static ItemDao INSTANCE = - new ItemZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public ItemDao createInterface() { - return INSTANCE; - } + private static ItemDao INSTANCE = new ItemZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ItemDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java index f8b0d71eb7..80a385fd4b 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; @@ -26,11 +25,11 @@ import org.openecomp.sdc.versioning.dao.VersionDaoFactory; import org.openecomp.sdc.versioning.dao.impl.zusammen.VersionZusammenDaoImpl; public class VersionDaoFactoryImpl extends VersionDaoFactory { - private static VersionDao INSTANCE = - new VersionZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public VersionDao createInterface() { - return INSTANCE; - } + private static VersionDao INSTANCE = new VersionZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public VersionDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoFactoryImpl.java index f26164a9d3..5e63a97a92 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.dao.impl; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; @@ -21,10 +20,11 @@ import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; public class VersionInfoDaoFactoryImpl extends VersionInfoDaoFactory { - private static VersionInfoDao INSTANCE = new VersionInfoDaoImpl(NoSqlDbFactory.getInstance().createInterface()); - @Override - public VersionInfoDao createInterface() { - return INSTANCE; - } + private static VersionInfoDao INSTANCE = new VersionInfoDaoImpl(NoSqlDbFactory.getInstance().createInterface()); + + @Override + public VersionInfoDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoImpl.java index 4df67735be..e9bb17efd2 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDaoImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.dao.impl; import com.datastax.driver.extras.codecs.enums.EnumNameCodec; @@ -21,50 +20,46 @@ import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; - import java.util.Collection; - import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -public class VersionInfoDaoImpl extends CassandraBaseDao - implements VersionInfoDao { +public class VersionInfoDaoImpl extends CassandraBaseDao implements VersionInfoDao { + private final NoSqlDb noSqlDb; + private final Mapper mapper; + private final VersionInfoAccessor accessor; - private final NoSqlDb noSqlDb; - private final Mapper mapper; - private final VersionInfoAccessor accessor; - - - public VersionInfoDaoImpl(NoSqlDb noSqlDb) { - this.noSqlDb = noSqlDb; - this.mapper = this.noSqlDb.getMappingManager().mapper(VersionInfoEntity.class); - this.accessor = this.noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); - this.noSqlDb.getMappingManager().getSession().getCluster().getConfiguration().getCodecRegistry() + public VersionInfoDaoImpl(NoSqlDb noSqlDb) { + this.noSqlDb = noSqlDb; + this.mapper = this.noSqlDb.getMappingManager().mapper(VersionInfoEntity.class); + this.accessor = this.noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + this.noSqlDb.getMappingManager().getSession().getCluster().getConfiguration().getCodecRegistry() .register(new EnumNameCodec<>(VersionStatus.class)); - } + } + + @Override + protected Mapper getMapper() { + return mapper; + } - @Override - protected Mapper getMapper() { - return mapper; - } + @Override + protected Object[] getKeys(VersionInfoEntity entity) { + return new Object[]{entity.getEntityType(), entity.getEntityId()}; + } - @Override - protected Object[] getKeys(VersionInfoEntity entity) { - return new Object[]{entity.getEntityType(), entity.getEntityId()}; - } + @Override + public Collection list(VersionInfoEntity entity) { + return accessor.getAll(entity.getEntityType()).all(); + } - @Override - public Collection list(VersionInfoEntity entity) { - return accessor.getAll(entity.getEntityType()).all(); - } + @Accessor + interface VersionInfoAccessor { - @Accessor - interface VersionInfoAccessor { - @Query("select * from version_info where entity_type=?") - Result getAll(String entityType); - } + @Query("select * from version_info where entity_type=?") + Result getAll(String entityType); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoFactoryImpl.java index 9163018a85..fb7c8131e4 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; - import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory; public class VersionInfoDeletedDaoFactoryImpl extends VersionInfoDeletedDaoFactory { - private static VersionInfoDeletedDao INSTANCE = new VersionInfoDeletedDaoImpl(); - @Override - public VersionInfoDeletedDao createInterface() { - return INSTANCE; - } + private static VersionInfoDeletedDao INSTANCE = new VersionInfoDeletedDaoImpl(); + + @Override + public VersionInfoDeletedDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoImpl.java index af6b20252e..02945be400 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionInfoDeletedDaoImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,50 +17,44 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; - import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.Collection; import org.openecomp.core.dao.impl.CassandraBaseDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; import org.openecomp.sdc.versioning.dao.types.VersionInfoDeletedEntity; -import java.util.Collection; - -public class VersionInfoDeletedDaoImpl extends CassandraBaseDao - implements VersionInfoDeletedDao { +public class VersionInfoDeletedDaoImpl extends CassandraBaseDao implements VersionInfoDeletedDao { - private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static Mapper mapper = - noSqlDb.getMappingManager().mapper(VersionInfoDeletedEntity.class); - private static VersionInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static Mapper mapper = noSqlDb.getMappingManager().mapper(VersionInfoDeletedEntity.class); + private static VersionInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + @Override + protected Mapper getMapper() { + return mapper; + } - @Override - protected Mapper getMapper() { - return mapper; - } + @Override + protected Object[] getKeys(VersionInfoDeletedEntity entity) { + return new Object[]{entity.getEntityType(), entity.getEntityId()}; + } - @Override - protected Object[] getKeys(VersionInfoDeletedEntity entity) { - return new Object[]{entity.getEntityType(), entity.getEntityId()}; - } + @Override + public Collection list(VersionInfoDeletedEntity entity) { + return accessor.getAll(entity.getEntityType()).all(); + } - @Override - public Collection list(VersionInfoDeletedEntity entity) { - return accessor.getAll(entity.getEntityType()).all(); - } + @Accessor + interface VersionInfoAccessor { - @Accessor - interface VersionInfoAccessor { - @Query("select * from version_info_deleted where entity_type=?") - Result getAll(String entityType); - } + @Query("select * from version_info_deleted where entity_type=?") + Result getAll(String entityType); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java index 19c62ab43c..fcbbaf77aa 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,12 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; import org.openecomp.core.dao.UniqueValueDao; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; @@ -35,135 +40,103 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.UniqueValueMetadata; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; - class VersionableEntityDaoCassandraImpl implements VersionableEntityDao { - private final UniqueValueUtil uniqueValueUtil; - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static Logger Logger = - (Logger) LoggerFactory.getLogger(VersionableEntityDaoCassandraImpl.class); - - public VersionableEntityDaoCassandraImpl( - UniqueValueDao uniqueValueDao) { - this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); - } + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static Logger Logger = (Logger) LoggerFactory.getLogger(VersionableEntityDaoCassandraImpl.class); + private final UniqueValueUtil uniqueValueUtil; - private static String commaSeparatedQuestionMarks(int size) { - StringBuilder sb = new StringBuilder(size * 2 - 1); - for (int i = 0; i < size; i++) { - if (i > 0) { - sb.append(','); - } - sb.append('?'); + public VersionableEntityDaoCassandraImpl(UniqueValueDao uniqueValueDao) { + this.uniqueValueUtil = new UniqueValueUtil(uniqueValueDao); } - return sb.toString(); - } + private static String commaSeparatedQuestionMarks(int size) { + StringBuilder sb = new StringBuilder(size * 2 - 1); + for (int i = 0; i < size; i++) { + if (i > 0) { + sb.append(','); + } + sb.append('?'); + } + return sb.toString(); + } - @Override - public void initVersion(VersionableEntityMetadata metadata, String entityId, Version baseVersion, - Version newVersion) { - ResultSet rows = loadVersionRows(metadata, entityId, baseVersion); - List columnNames = - rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName) + @Override + public void initVersion(VersionableEntityMetadata metadata, String entityId, Version baseVersion, Version newVersion) { + ResultSet rows = loadVersionRows(metadata, entityId, baseVersion); + List columnNames = rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName) .collect(Collectors.toList()); - - String insertCql = String.format("insert into %s (%s) values (%s)", metadata.getName(), - CommonMethods.listToSeparatedString(columnNames, ','), - commaSeparatedQuestionMarks(columnNames.size())); - Logger.debug("insertCql", insertCql); - - for (Row row : rows) { - List columnValues = new ArrayList<>(); - Map columnNameToValue = new HashMap<>(); - - for (String columnName : columnNames) { - if (metadata.getVersionIdentifierName().equals(columnName)) { - columnValues.add(newVersion); - columnNameToValue.put(columnName, newVersion.toString()); - } else { - Object value = row.getObject(columnName); - columnValues.add(value); - columnNameToValue.put(columnName, value); + String insertCql = String.format("insert into %s (%s) values (%s)", metadata.getName(), CommonMethods.listToSeparatedString(columnNames, ','), + commaSeparatedQuestionMarks(columnNames.size())); + Logger.debug("insertCql", insertCql); + for (Row row : rows) { + List columnValues = new ArrayList<>(); + Map columnNameToValue = new HashMap<>(); + for (String columnName : columnNames) { + if (metadata.getVersionIdentifierName().equals(columnName)) { + columnValues.add(newVersion); + columnNameToValue.put(columnName, newVersion.toString()); + } else { + Object value = row.getObject(columnName); + columnValues.add(value); + columnNameToValue.put(columnName, value); + } + } + initRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue); + noSqlDb.execute(insertCql, columnValues.toArray()); } - } - - initRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue); - - noSqlDb.execute(insertCql, columnValues.toArray()); } - } - - @Override - public void deleteVersion(VersionableEntityMetadata metadata, String entityId, - Version versionToDelete, Version backToVersion) { - deleteRowsUniqueValues(metadata, entityId, versionToDelete); - - String deleteCql = String.format("delete from %s where %s=? and %s=?", metadata.getName(), - metadata.getIdentifierName(), metadata.getVersionIdentifierName()); - noSqlDb.execute(deleteCql, entityId, versionToDelete); - } - - @Override - public void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version versionToClose) { - // redundant in cassandra impl. - } - private ResultSet loadVersionRows(VersionableEntityMetadata metadata, String entityId, - Version version) { - String selectCql = String.format("select * from %s where %s=? and %s=?", metadata.getName(), - metadata.getIdentifierName(), metadata.getVersionIdentifierName()); - Logger.debug("selectCql", selectCql); - Logger.debug("entityId", entityId); - Logger.debug("version", version); + @Override + public void deleteVersion(VersionableEntityMetadata metadata, String entityId, Version versionToDelete, Version backToVersion) { + deleteRowsUniqueValues(metadata, entityId, versionToDelete); + String deleteCql = String + .format("delete from %s where %s=? and %s=?", metadata.getName(), metadata.getIdentifierName(), metadata.getVersionIdentifierName()); + noSqlDb.execute(deleteCql, entityId, versionToDelete); + } - return noSqlDb.execute(selectCql, entityId, version); - } + @Override + public void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version versionToClose) { + // redundant in cassandra impl. + } - private void initRowUniqueValues(List metadata, - Map columnNameToValue) { - for (UniqueValueMetadata uniqueMetadata : metadata) { - List uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream() - .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList()); - uniqueValueUtil.createUniqueValue(uniqueMetadata.getType(), - uniqueValueCombination.toArray(new String[uniqueValueCombination.size()])); + private ResultSet loadVersionRows(VersionableEntityMetadata metadata, String entityId, Version version) { + String selectCql = String + .format("select * from %s where %s=? and %s=?", metadata.getName(), metadata.getIdentifierName(), metadata.getVersionIdentifierName()); + Logger.debug("selectCql", selectCql); + Logger.debug("entityId", entityId); + Logger.debug("version", version); + return noSqlDb.execute(selectCql, entityId, version); } - } - private void deleteRowUniqueValues(List metadata, - Map columnNameToValue) { - for (UniqueValueMetadata uniqueMetadata : metadata) { - List uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream() - .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList()); - uniqueValueUtil.deleteUniqueValue(uniqueMetadata.getType(), - uniqueValueCombination.toArray(new String[uniqueValueCombination.size()])); + private void initRowUniqueValues(List metadata, Map columnNameToValue) { + for (UniqueValueMetadata uniqueMetadata : metadata) { + List uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream() + .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList()); + uniqueValueUtil.createUniqueValue(uniqueMetadata.getType(), uniqueValueCombination.toArray(new String[uniqueValueCombination.size()])); + } } - } - private void deleteRowsUniqueValues(VersionableEntityMetadata metadata, String entityId, - Version version) { - if (metadata.getUniqueValuesMetadata().isEmpty()) { - return; + private void deleteRowUniqueValues(List metadata, Map columnNameToValue) { + for (UniqueValueMetadata uniqueMetadata : metadata) { + List uniqueValueCombination = uniqueMetadata.getUniqueConstraintIdentifiers().stream() + .map(colName -> (String) columnNameToValue.get(colName)).collect(Collectors.toList()); + uniqueValueUtil.deleteUniqueValue(uniqueMetadata.getType(), uniqueValueCombination.toArray(new String[uniqueValueCombination.size()])); + } } - ResultSet rows = loadVersionRows(metadata, entityId, version); - List columnNames = - rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName) - .collect(Collectors.toList()); - for (Row row : rows) { - Map columnNameToValue = - columnNames.stream().filter(name -> row.getObject(name) != null).collect(Collectors - .toMap(Function.identity(), - columnName -> metadata.getVersionIdentifierName().equals(columnName) ? version - .toString() : row.getObject(columnName))); - deleteRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue); + private void deleteRowsUniqueValues(VersionableEntityMetadata metadata, String entityId, Version version) { + if (metadata.getUniqueValuesMetadata().isEmpty()) { + return; + } + ResultSet rows = loadVersionRows(metadata, entityId, version); + List columnNames = rows.getColumnDefinitions().asList().stream().map(ColumnDefinitions.Definition::getName) + .collect(Collectors.toList()); + for (Row row : rows) { + Map columnNameToValue = columnNames.stream().filter(name -> row.getObject(name) != null).collect(Collectors + .toMap(Function.identity(), + columnName -> metadata.getVersionIdentifierName().equals(columnName) ? version.toString() : row.getObject(columnName))); + deleteRowUniqueValues(metadata.getUniqueValuesMetadata(), columnNameToValue); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoFactoryImpl.java index d9300a007b..806d77ecd2 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.dao.impl; import org.openecomp.core.dao.UniqueValueDaoFactory; @@ -27,26 +26,26 @@ import org.openecomp.sdc.versioning.dao.VersionableEntityDaoFactory; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; public class VersionableEntityDaoFactoryImpl extends VersionableEntityDaoFactory { - private static VersionableEntityDao CASSANDRA_INSTANCE = new VersionableEntityDaoCassandraImpl( - UniqueValueDaoFactory.getInstance().createInterface()); - private static VersionableEntityDao ZUSAMMEN_INSTANCE = - new VersionableEntityDaoZusammenImpl(ZusammenAdaptorFactory.getInstance().createInterface()); - @Override - public VersionableEntityDao createInterface() { - throw new UnsupportedOperationException - ("Please use createInterface api with VersionableEntityStoreType argument."); - } + private static VersionableEntityDao CASSANDRA_INSTANCE = new VersionableEntityDaoCassandraImpl( + UniqueValueDaoFactory.getInstance().createInterface()); + private static VersionableEntityDao ZUSAMMEN_INSTANCE = new VersionableEntityDaoZusammenImpl( + ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public VersionableEntityDao createInterface() { + throw new UnsupportedOperationException("Please use createInterface api with VersionableEntityStoreType argument."); + } - @Override - public VersionableEntityDao createInterface(VersionableEntityStoreType storeType) { - switch (storeType) { - case Cassandra: - return CASSANDRA_INSTANCE; - case Zusammen: - return ZUSAMMEN_INSTANCE; - default: - throw new IllegalArgumentException("Unssported state store"); + @Override + public VersionableEntityDao createInterface(VersionableEntityStoreType storeType) { + switch (storeType) { + case Cassandra: + return CASSANDRA_INSTANCE; + case Zusammen: + return ZUSAMMEN_INSTANCE; + default: + throw new IllegalArgumentException("Unssported state store"); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoZusammenImpl.java index f90ef79290..f8c479eb5b 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoZusammenImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.dao.impl; import com.amdocs.zusammen.datatypes.Id; @@ -32,53 +31,47 @@ import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; public class VersionableEntityDaoZusammenImpl implements VersionableEntityDao { - private ZusammenAdaptor zusammenAdaptor; + private ZusammenAdaptor zusammenAdaptor; - public VersionableEntityDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } + public VersionableEntityDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - @Override - public void initVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version baseVersion, Version newVersion) { - // redundant in zusammen impl. - } + private static Comparator getVersionModificationTimeDescComparator() { + return (o1, o2) -> Integer.compare(o2.getId().getValue().length(), o1.getId().getValue().length()); + } - @Override - public void deleteVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version versionToDelete, Version backToVersion) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entityId); - Id versionId = getItemVersionId(itemId, context); - zusammenAdaptor.resetVersionHistory(context, itemId, versionId, backToVersion.toString()); - } + @Override + public void initVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version baseVersion, Version newVersion) { + // redundant in zusammen impl. + } - @Override - public void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, - Version versionToClose) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entityId); - Id versionId = getItemVersionId(itemId, context); - zusammenAdaptor - .tagVersion(context, itemId, versionId, new Tag(versionToClose.toString(), null)); - } + @Override + public void deleteVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version versionToDelete, Version backToVersion) { + SessionContext context = ZusammenUtil.createSessionContext(); + Id itemId = new Id(entityId); + Id versionId = getItemVersionId(itemId, context); + zusammenAdaptor.resetVersionHistory(context, itemId, versionId, backToVersion.toString()); + } - // TODO: 3/19/2017 move to a common util - private Id getItemVersionId(Id itemId, SessionContext context) { - Optional itemVersionOptional = getFirstVersion(context, itemId); - ItemVersion itemVersion = itemVersionOptional.orElseThrow(() -> - new RuntimeException(String.format("No version was found for item %s.", itemId))); - return itemVersion.getId(); - } + @Override + public void closeVersion(VersionableEntityMetadata versionableTableMetadata, String entityId, Version versionToClose) { + SessionContext context = ZusammenUtil.createSessionContext(); + Id itemId = new Id(entityId); + Id versionId = getItemVersionId(itemId, context); + zusammenAdaptor.tagVersion(context, itemId, versionId, new Tag(versionToClose.toString(), null)); + } - private Optional getFirstVersion(SessionContext context, Id itemId) { - Collection versions = zusammenAdaptor.listPublicVersions(context, itemId); - return CollectionUtils.isEmpty(versions) - ? Optional.empty() - : versions.stream().min(getVersionModificationTimeDescComparator()); - } + // TODO: 3/19/2017 move to a common util + private Id getItemVersionId(Id itemId, SessionContext context) { + Optional itemVersionOptional = getFirstVersion(context, itemId); + ItemVersion itemVersion = itemVersionOptional + .orElseThrow(() -> new RuntimeException(String.format("No version was found for item %s.", itemId))); + return itemVersion.getId(); + } - private static Comparator getVersionModificationTimeDescComparator() { - return (o1, o2) -> Integer.compare(o2.getId().getValue().length(), o1.getId().getValue().length()); - } + private Optional getFirstVersion(SessionContext context, Id itemId) { + Collection versions = zusammenAdaptor.listPublicVersions(context, itemId); + return CollectionUtils.isEmpty(versions) ? Optional.empty() : versions.stream().min(getVersionModificationTimeDescComparator()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java index b631663813..6ac18d9ff9 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java @@ -21,6 +21,9 @@ package org.openecomp.sdc.versioning.dao.impl.zusammen; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.item.Info; +import java.util.Collection; +import java.util.Map; +import java.util.stream.Collectors; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; import org.openecomp.sdc.versioning.dao.ItemDao; @@ -28,120 +31,103 @@ import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.types.Item; import org.openecomp.sdc.versioning.types.ItemStatus; -import java.util.Collection; -import java.util.Map; -import java.util.stream.Collectors; - public class ItemZusammenDaoImpl implements ItemDao { - private ZusammenAdaptor zusammenAdaptor; - - public ItemZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public Collection list() { - return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()) - .stream().map(this::mapFromZusammenItem) - .collect(Collectors.toList()); - } - - @Override - public Item get(Item item) { - return mapFromZusammenItem( - zusammenAdaptor.getItem(ZusammenUtil.createSessionContext(), new Id(item.getId()))); - } - - @Override - public Item create(Item item) { - Id itemId = zusammenAdaptor - .createItem(ZusammenUtil.createSessionContext(), mapToZusammenItemInfo(item)); - item.setId(itemId.getValue()); - return item; - } + private ZusammenAdaptor zusammenAdaptor; - @Override - public void delete(Item item){ - zusammenAdaptor.deleteItem(ZusammenUtil.createSessionContext(),new Id(item.getId())); - } + public ItemZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } - @Override - public void update(Item item) { - zusammenAdaptor - .updateItem(ZusammenUtil.createSessionContext(), new Id(item.getId()), - mapToZusammenItemInfo(item)); - } + @Override + public Collection list() { + return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream().map(this::mapFromZusammenItem).collect(Collectors.toList()); + } - private Item mapFromZusammenItem(com.amdocs.zusammen.datatypes.item.Item zusammenItem) { - if (zusammenItem == null) { - return null; + @Override + public Item get(Item item) { + return mapFromZusammenItem(zusammenAdaptor.getItem(ZusammenUtil.createSessionContext(), new Id(item.getId()))); } - Item item = new Item(); - item.setId(zusammenItem.getId().getValue()); - item.setName(zusammenItem.getInfo().getName()); - item.setDescription(zusammenItem.getInfo().getDescription()); - zusammenItem.getInfo().getProperties().entrySet() - .forEach(property -> addPropertyToItem(property.getKey(), property.getValue(), item)); + @Override + public Item create(Item item) { + Id itemId = zusammenAdaptor.createItem(ZusammenUtil.createSessionContext(), mapToZusammenItemInfo(item)); + item.setId(itemId.getValue()); + return item; + } - item.setCreationTime(zusammenItem.getCreationTime()); - item.setModificationTime(zusammenItem.getModificationTime()); + @Override + public void delete(Item item) { + zusammenAdaptor.deleteItem(ZusammenUtil.createSessionContext(), new Id(item.getId())); + } - if(item.getStatus() == null){ - item.setStatus(ItemStatus.ACTIVE); - update(item); + @Override + public void update(Item item) { + zusammenAdaptor.updateItem(ZusammenUtil.createSessionContext(), new Id(item.getId()), mapToZusammenItemInfo(item)); } - return item; - } + private Item mapFromZusammenItem(com.amdocs.zusammen.datatypes.item.Item zusammenItem) { + if (zusammenItem == null) { + return null; + } + Item item = new Item(); + item.setId(zusammenItem.getId().getValue()); + item.setName(zusammenItem.getInfo().getName()); + item.setDescription(zusammenItem.getInfo().getDescription()); + zusammenItem.getInfo().getProperties().entrySet().forEach(property -> addPropertyToItem(property.getKey(), property.getValue(), item)); + item.setCreationTime(zusammenItem.getCreationTime()); + item.setModificationTime(zusammenItem.getModificationTime()); + if (item.getStatus() == null) { + item.setStatus(ItemStatus.ACTIVE); + update(item); + } + return item; + } - private void addPropertyToItem(String propertyKey, Object propertyValue, Item item) { - switch (propertyKey) { - case InfoPropertyName.ITEM_TYPE: - item.setType((String) propertyValue); - break; - case InfoPropertyName.ITEM_OWNER: - item.setOwner((String) propertyValue); - break; - case InfoPropertyName.ITEM_STATUS: - item.setStatus(ItemStatus.valueOf((String)propertyValue)); - break; - case InfoPropertyName.ITEM_VERSIONS_STATUSES: - for (Map.Entry statusCounter : - ((Map) propertyValue).entrySet()) { - item.getVersionStatusCounters().put(VersionStatus.valueOf(statusCounter.getKey()), - statusCounter.getValue().intValue()); + private void addPropertyToItem(String propertyKey, Object propertyValue, Item item) { + switch (propertyKey) { + case InfoPropertyName.ITEM_TYPE: + item.setType((String) propertyValue); + break; + case InfoPropertyName.ITEM_OWNER: + item.setOwner((String) propertyValue); + break; + case InfoPropertyName.ITEM_STATUS: + item.setStatus(ItemStatus.valueOf((String) propertyValue)); + break; + case InfoPropertyName.ITEM_VERSIONS_STATUSES: + for (Map.Entry statusCounter : ((Map) propertyValue).entrySet()) { + item.getVersionStatusCounters().put(VersionStatus.valueOf(statusCounter.getKey()), statusCounter.getValue().intValue()); + } + break; + default: + item.addProperty(propertyKey, propertyValue); } - break; - default: - item.addProperty(propertyKey, propertyValue); } - } - private Info mapToZusammenItemInfo(Item item) { - Info info = new Info(); - info.setName(item.getName()); - info.setDescription(item.getDescription()); - info.addProperty(InfoPropertyName.ITEM_TYPE, item.getType()); - info.addProperty(InfoPropertyName.ITEM_OWNER,item.getOwner()); - if (item.getStatus() != null) { - info.addProperty(InfoPropertyName.ITEM_STATUS, item.getStatus()); + private Info mapToZusammenItemInfo(Item item) { + Info info = new Info(); + info.setName(item.getName()); + info.setDescription(item.getDescription()); + info.addProperty(InfoPropertyName.ITEM_TYPE, item.getType()); + info.addProperty(InfoPropertyName.ITEM_OWNER, item.getOwner()); + if (item.getStatus() != null) { + info.addProperty(InfoPropertyName.ITEM_STATUS, item.getStatus()); + } + info.addProperty(InfoPropertyName.ITEM_VERSIONS_STATUSES, item.getVersionStatusCounters()); + item.getProperties().entrySet().forEach(property -> info.addProperty(property.getKey(), property.getValue())); + return info; } - info.addProperty(InfoPropertyName.ITEM_VERSIONS_STATUSES, item.getVersionStatusCounters()); - item.getProperties().entrySet() - .forEach(property -> info.addProperty(property.getKey(), property.getValue())); - return info; - } - private static final class InfoPropertyName { - private static final String ITEM_TYPE = "item_type"; - private static final String ITEM_VERSIONS_STATUSES = "item_versions_statuses"; - private static final String ITEM_OWNER = "Owner"; - private static final String ITEM_STATUS = "status"; + private static final class InfoPropertyName { - private InfoPropertyName() { - throw new IllegalStateException("Constants class"); + private static final String ITEM_TYPE = "item_type"; + private static final String ITEM_VERSIONS_STATUSES = "item_versions_statuses"; + private static final String ITEM_OWNER = "Owner"; + private static final String ITEM_STATUS = "status"; + + private InfoPropertyName() { + throw new IllegalStateException("Constants class"); + } } - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java index dfefc7273d..044359a165 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java @@ -23,7 +23,11 @@ import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.*; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.SynchronizationStatus; import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; import java.util.ArrayList; import java.util.List; @@ -42,168 +46,148 @@ import org.openecomp.sdc.versioning.dao.types.VersionState; public class VersionZusammenDaoImpl implements VersionDao { - public static final class ZusammenProperty { - public static final String LABEL = "label"; - public static final String STATUS = "status"; - - private ZusammenProperty() { - throw new IllegalStateException("Constants class"); - } - } - - private ZusammenAdaptor zusammenAdaptor; - - public VersionZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { - this.zusammenAdaptor = zusammenAdaptor; - } - - @Override - public List list(String itemId) { - ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); - return zusammenAdaptor.listPublicVersions(createSessionContext(), new Id(itemId)).stream() - .map(convertor::convert) - .collect(Collectors.toList()); - } - - @Override - public void create(String itemId, Version version) { - Id versionId = - zusammenAdaptor.createVersion(createSessionContext(), new Id(itemId), - version.getBaseId() == null ? null : new Id(version.getBaseId()), - mapToZusammenVersion(version)); - - version.setId(versionId.getValue()); - } - - @Override - public void update(String itemId, Version version) { - zusammenAdaptor.updateVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), - mapToZusammenVersion(version)); - } - - @Override - public Optional get(String itemId, Version version) { - SessionContext context = createSessionContext(); - Id itemIdObj = new Id(itemId); - Id versionId = new Id(version.getId()); - ItemVersion itemVersion = zusammenAdaptor.getVersion(context, itemIdObj, versionId); - - if (itemVersion == null) { - return Optional.empty(); - } - - VersionState versionState = - convertState(zusammenAdaptor.getVersionStatus(context, itemIdObj, versionId)); - updateVersionStatus(context, itemIdObj, versionId, versionState, itemVersion); - - Version result = new ItemVersionToVersionConvertor().convert(itemVersion); - result.setState(versionState); - return Optional.of(result); - } - - @Override - public void delete(String itemId, Version version) { - throw new UnsupportedOperationException("Delete version operation is not yet supported."); - } - - @Override - public void publish(String itemId, Version version, String message) { - zusammenAdaptor - .publishVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), message); - } - - @Override - public void sync(String itemId, Version version) { - zusammenAdaptor - .syncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); - } - - @Override - public void forceSync(String itemId, Version version) { - zusammenAdaptor - .forceSyncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); - } - - @Override - public void clean(String itemId, Version version) { - zusammenAdaptor.cleanVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); - } - - @Override - public void revert(String itemId, Version version, String revisionId) { - zusammenAdaptor.revert(createSessionContext(), new Id(itemId), new Id(version.getId()), - new Id(revisionId)); - } - - @Override - public List listRevisions(String itemId, Version version) { - ItemVersionRevisions itemVersionRevisions = zusammenAdaptor - .listRevisions(createSessionContext(), new Id(itemId), new Id(version.getId())); - - return itemVersionRevisions == null || itemVersionRevisions.getItemVersionRevisions() == null || - itemVersionRevisions.getItemVersionRevisions().isEmpty() - ? new ArrayList<>() - : itemVersionRevisions.getItemVersionRevisions().stream() - .map(this::convertRevision) - .sorted(this::compareRevisionsTime) + private ZusammenAdaptor zusammenAdaptor; + + public VersionZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public List list(String itemId) { + ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); + return zusammenAdaptor.listPublicVersions(createSessionContext(), new Id(itemId)).stream().map(convertor::convert) .collect(Collectors.toList()); - } - - private void updateVersionStatus(SessionContext context, Id itemId, Id versionId, - VersionState versionState, ItemVersion itemVersion) { - if (versionState.getSynchronizationState() != SynchronizationState.UpToDate) { - String versionStatus = zusammenAdaptor.getPublicVersion(context, itemId, versionId) - .getData().getInfo().getProperty(ZusammenProperty.STATUS); - itemVersion.getData().getInfo().addProperty(ZusammenProperty.STATUS, versionStatus); - } - } - - private ItemVersionData mapToZusammenVersion(Version version) { - Info info = new Info(); - info.addProperty(ZusammenProperty.LABEL, version.toString()); - info.addProperty(ZusammenProperty.STATUS, version.getStatus().name()); - info.setName(version.getName()); - info.setDescription(version.getDescription()); - - ItemVersionData itemVersionData = new ItemVersionData(); - itemVersionData.setInfo(info); - return itemVersionData; - } - - private VersionState convertState(ItemVersionStatus versionStatus) { - VersionState state = new VersionState(); - state.setSynchronizationState(getSyncState(versionStatus.getSynchronizationStatus())); - state.setDirty(versionStatus.isDirty()); - return state; - } - - private SynchronizationState getSyncState(SynchronizationStatus synchronizationStatus) { - switch (synchronizationStatus) { - case UP_TO_DATE: - return SynchronizationState.UpToDate; - case OUT_OF_SYNC: - return SynchronizationState.OutOfSync; - case MERGING: - return SynchronizationState.Merging; - default: - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId("UNKNOWN_VERSION_STATE") - .withMessage("Version state is unknown").build()); - } - } - - private Revision convertRevision( - com.amdocs.zusammen.datatypes.itemversion.Revision zusammenRevision) { - Revision revision = new Revision(); - revision.setId(zusammenRevision.getRevisionId().getValue()); - revision.setTime(zusammenRevision.getTime()); - revision.setUser(zusammenRevision.getUser()); - revision.setMessage(zusammenRevision.getMessage()); - return revision; - } - - private int compareRevisionsTime(Revision revision1, Revision revision2) { - return revision1.getTime().before(revision2.getTime()) ? 1 : -1; - } + } + + @Override + public void create(String itemId, Version version) { + Id versionId = zusammenAdaptor + .createVersion(createSessionContext(), new Id(itemId), version.getBaseId() == null ? null : new Id(version.getBaseId()), + mapToZusammenVersion(version)); + version.setId(versionId.getValue()); + } + + @Override + public void update(String itemId, Version version) { + zusammenAdaptor.updateVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), mapToZusammenVersion(version)); + } + + @Override + public Optional get(String itemId, Version version) { + SessionContext context = createSessionContext(); + Id itemIdObj = new Id(itemId); + Id versionId = new Id(version.getId()); + ItemVersion itemVersion = zusammenAdaptor.getVersion(context, itemIdObj, versionId); + if (itemVersion == null) { + return Optional.empty(); + } + VersionState versionState = convertState(zusammenAdaptor.getVersionStatus(context, itemIdObj, versionId)); + updateVersionStatus(context, itemIdObj, versionId, versionState, itemVersion); + Version result = new ItemVersionToVersionConvertor().convert(itemVersion); + result.setState(versionState); + return Optional.of(result); + } + + @Override + public void delete(String itemId, Version version) { + throw new UnsupportedOperationException("Delete version operation is not yet supported."); + } + + @Override + public void publish(String itemId, Version version, String message) { + zusammenAdaptor.publishVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), message); + } + + @Override + public void sync(String itemId, Version version) { + zusammenAdaptor.syncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); + } + + @Override + public void forceSync(String itemId, Version version) { + zusammenAdaptor.forceSyncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); + } + + @Override + public void clean(String itemId, Version version) { + zusammenAdaptor.cleanVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); + } + + @Override + public void revert(String itemId, Version version, String revisionId) { + zusammenAdaptor.revert(createSessionContext(), new Id(itemId), new Id(version.getId()), new Id(revisionId)); + } + + @Override + public List listRevisions(String itemId, Version version) { + ItemVersionRevisions itemVersionRevisions = zusammenAdaptor.listRevisions(createSessionContext(), new Id(itemId), new Id(version.getId())); + return + itemVersionRevisions == null || itemVersionRevisions.getItemVersionRevisions() == null || itemVersionRevisions.getItemVersionRevisions() + .isEmpty() ? new ArrayList<>() + : itemVersionRevisions.getItemVersionRevisions().stream().map(this::convertRevision).sorted(this::compareRevisionsTime) + .collect(Collectors.toList()); + } + + private void updateVersionStatus(SessionContext context, Id itemId, Id versionId, VersionState versionState, ItemVersion itemVersion) { + if (versionState.getSynchronizationState() != SynchronizationState.UpToDate) { + String versionStatus = zusammenAdaptor.getPublicVersion(context, itemId, versionId).getData().getInfo() + .getProperty(ZusammenProperty.STATUS); + itemVersion.getData().getInfo().addProperty(ZusammenProperty.STATUS, versionStatus); + } + } + + private ItemVersionData mapToZusammenVersion(Version version) { + Info info = new Info(); + info.addProperty(ZusammenProperty.LABEL, version.toString()); + info.addProperty(ZusammenProperty.STATUS, version.getStatus().name()); + info.setName(version.getName()); + info.setDescription(version.getDescription()); + ItemVersionData itemVersionData = new ItemVersionData(); + itemVersionData.setInfo(info); + return itemVersionData; + } + + private VersionState convertState(ItemVersionStatus versionStatus) { + VersionState state = new VersionState(); + state.setSynchronizationState(getSyncState(versionStatus.getSynchronizationStatus())); + state.setDirty(versionStatus.isDirty()); + return state; + } + + private SynchronizationState getSyncState(SynchronizationStatus synchronizationStatus) { + switch (synchronizationStatus) { + case UP_TO_DATE: + return SynchronizationState.UpToDate; + case OUT_OF_SYNC: + return SynchronizationState.OutOfSync; + case MERGING: + return SynchronizationState.Merging; + default: + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId("UNKNOWN_VERSION_STATE") + .withMessage("Version state is unknown").build()); + } + } + + private Revision convertRevision(com.amdocs.zusammen.datatypes.itemversion.Revision zusammenRevision) { + Revision revision = new Revision(); + revision.setId(zusammenRevision.getRevisionId().getValue()); + revision.setTime(zusammenRevision.getTime()); + revision.setUser(zusammenRevision.getUser()); + revision.setMessage(zusammenRevision.getMessage()); + return revision; + } + + private int compareRevisionsTime(Revision revision1, Revision revision2) { + return revision1.getTime().before(revision2.getTime()) ? 1 : -1; + } + + public static final class ZusammenProperty { + + public static final String LABEL = "label"; + public static final String STATUS = "status"; + + private ZusammenProperty() { + throw new IllegalStateException("Constants class"); + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java index 2ebb95b33b..361b1bcbec 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java @@ -29,40 +29,37 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; public class ItemVersionToVersionConvertor extends ElementConvertor { - @Override - public Object convert(Element element) { - return null; - } - @Override - public Object convert(Item item) { - return null; - } - - @Override - public Object convert(ElementInfo elementInfo) { - return null; - } + @Override + public Object convert(Element element) { + return null; + } - @Override - public Version convert(ItemVersion itemVersion) { - if (itemVersion == null) { - return null; + @Override + public Object convert(Item item) { + return null; } - Version version = Version.valueOf( - itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL)); - version.setStatus(VersionStatus.valueOf(itemVersion.getData().getInfo() - .getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); - version.setName(itemVersion.getData().getInfo().getName()); - version.setDescription(itemVersion.getData().getInfo().getDescription()); - version.setId(itemVersion.getId().getValue()); - if (itemVersion.getBaseId() != null) { - version.setBaseId(itemVersion.getBaseId().getValue()); + @Override + public Object convert(ElementInfo elementInfo) { + return null; } - version.setCreationTime(itemVersion.getCreationTime()); - version.setModificationTime(itemVersion.getModificationTime()); - return version; - } + @Override + public Version convert(ItemVersion itemVersion) { + if (itemVersion == null) { + return null; + } + Version version = Version.valueOf(itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL)); + version.setStatus(VersionStatus.valueOf(itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); + version.setName(itemVersion.getData().getInfo().getName()); + version.setDescription(itemVersion.getData().getInfo().getDescription()); + version.setId(itemVersion.getId().getValue()); + if (itemVersion.getBaseId() != null) { + version.setBaseId(itemVersion.getBaseId().getValue()); + } + version.setCreationTime(itemVersion.getCreationTime()); + version.setModificationTime(itemVersion.getModificationTime()); + return version; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerFactoryImpl.java index 054a569958..0de4af3ab8 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.versioning.ActionVersioningManager; @@ -26,14 +25,10 @@ import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory; public class ActionVersioningManagerFactoryImpl extends ActionVersioningManagerFactory { - - @Override - public ActionVersioningManager createInterface() { - return new ActionVersioningManagerImpl( - VersionInfoDaoFactory.getInstance().createInterface(), - VersionInfoDeletedDaoFactory.getInstance().createInterface(), - VersionDaoFactory.getInstance().createInterface(), - VersionCalculatorFactory.getInstance().createInterface(), - AsdcItemManagerFactory.getInstance().createInterface()); - } + @Override + public ActionVersioningManager createInterface() { + return new ActionVersioningManagerImpl(VersionInfoDaoFactory.getInstance().createInterface(), + VersionInfoDeletedDaoFactory.getInstance().createInterface(), VersionDaoFactory.getInstance().createInterface(), + VersionCalculatorFactory.getInstance().createInterface(), AsdcItemManagerFactory.getInstance().createInterface()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerImpl.java index ef33beadab..a69e862582 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ActionVersioningManagerImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -28,585 +34,494 @@ import org.openecomp.sdc.versioning.dao.VersionDao; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; import org.openecomp.sdc.versioning.dao.VersionableEntityDaoFactory; -import org.openecomp.sdc.versioning.dao.types.*; -import org.openecomp.sdc.versioning.errors.*; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; +import org.openecomp.sdc.versioning.dao.types.UserCandidateVersion; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionInfoDeletedEntity; +import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.errors.CheckinOnEntityLockedByOtherErrorBuilder; +import org.openecomp.sdc.versioning.errors.CheckinOnUnlockedEntityErrorBuilder; +import org.openecomp.sdc.versioning.errors.CheckoutOnLockedEntityErrorBuilder; +import org.openecomp.sdc.versioning.errors.DeleteOnLockedEntityErrorBuilder; +import org.openecomp.sdc.versioning.errors.EditOnEntityLockedByOtherErrorBuilder; +import org.openecomp.sdc.versioning.errors.EditOnUnlockedEntityErrorBuilder; +import org.openecomp.sdc.versioning.errors.EntityAlreadyExistErrorBuilder; +import org.openecomp.sdc.versioning.errors.EntityAlreadyFinalizedErrorBuilder; +import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder; +import org.openecomp.sdc.versioning.errors.SubmitLockedEntityNotAllowedErrorBuilder; +import org.openecomp.sdc.versioning.errors.UndoCheckoutOnEntityLockedByOtherErrorBuilder; +import org.openecomp.sdc.versioning.errors.UndoCheckoutOnUnlockedEntityErrorBuilder; import org.openecomp.sdc.versioning.types.VersionCreationMethod; import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; -import java.util.stream.Collectors; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - public class ActionVersioningManagerImpl implements ActionVersioningManager { - private static final Logger LOGGER = LoggerFactory.getLogger(ActionVersioningManagerImpl.class); - private static final Version INITIAL_ACTIVE_VERSION = new Version(0, 0); - private static final Map> VERSIONABLE_ENTITIES = - new HashMap<>(); - - private final VersionInfoDao versionInfoDao; - private final VersionInfoDeletedDao versionInfoDeletedDao; - private VersionDao versionDao; - private VersionCalculator versionCalculator; - private AsdcItemManager asdcItemManager; - - public ActionVersioningManagerImpl(VersionInfoDao versionInfoDao, - VersionInfoDeletedDao versionInfoDeletedDao, - VersionDao versionDao, - VersionCalculator versionCalculator, - AsdcItemManager asdcItemManager) { - this.versionInfoDao = versionInfoDao; - this.versionInfoDeletedDao = versionInfoDeletedDao; - this.versionDao = versionDao; - this.versionCalculator = versionCalculator; - this.asdcItemManager = asdcItemManager; - } - - private static VersionInfo getVersionInfo(VersionInfoEntity versionInfoEntity, String user, - VersionableEntityAction action) { - return getVersionInfo(versionInfoEntity.getEntityId(), - versionInfoEntity.getEntityType(), - versionInfoEntity.getActiveVersion(), - versionInfoEntity.getCandidate(), - versionInfoEntity.getStatus(), - versionInfoEntity.getLatestFinalVersion(), - versionInfoEntity.getViewableVersions(), - action, - user); - } - - private static VersionInfo getVersionInfo(VersionInfoDeletedEntity versionInfoEntity, String user, - VersionableEntityAction action) { - return getVersionInfo(versionInfoEntity.getEntityId(), - versionInfoEntity.getEntityType(), - versionInfoEntity.getActiveVersion(), - versionInfoEntity.getCandidate(), - versionInfoEntity.getStatus(), - versionInfoEntity.getLatestFinalVersion(), - versionInfoEntity.getViewableVersions(), - action, - user); - } - - private static VersionInfo getVersionInfo(String entityId, String entityType, Version activeVer, - UserCandidateVersion candidate, VersionStatus status, - Version latestFinalVersion, - Set viewableVersions, - VersionableEntityAction action, String user) { - Version activeVersion; - - if (action == VersionableEntityAction.Write) { - if (candidate != null) { - if (user.equals(candidate.getUser())) { - activeVersion = candidate.getVersion(); + + private static final Logger LOGGER = LoggerFactory.getLogger(ActionVersioningManagerImpl.class); + private static final Version INITIAL_ACTIVE_VERSION = new Version(0, 0); + private static final Map> VERSIONABLE_ENTITIES = new HashMap<>(); + private final VersionInfoDao versionInfoDao; + private final VersionInfoDeletedDao versionInfoDeletedDao; + private VersionDao versionDao; + private VersionCalculator versionCalculator; + private AsdcItemManager asdcItemManager; + + public ActionVersioningManagerImpl(VersionInfoDao versionInfoDao, VersionInfoDeletedDao versionInfoDeletedDao, VersionDao versionDao, + VersionCalculator versionCalculator, AsdcItemManager asdcItemManager) { + this.versionInfoDao = versionInfoDao; + this.versionInfoDeletedDao = versionInfoDeletedDao; + this.versionDao = versionDao; + this.versionCalculator = versionCalculator; + this.asdcItemManager = asdcItemManager; + } + + private static VersionInfo getVersionInfo(VersionInfoEntity versionInfoEntity, String user, VersionableEntityAction action) { + return getVersionInfo(versionInfoEntity.getEntityId(), versionInfoEntity.getEntityType(), versionInfoEntity.getActiveVersion(), + versionInfoEntity.getCandidate(), versionInfoEntity.getStatus(), versionInfoEntity.getLatestFinalVersion(), + versionInfoEntity.getViewableVersions(), action, user); + } + + private static VersionInfo getVersionInfo(VersionInfoDeletedEntity versionInfoEntity, String user, VersionableEntityAction action) { + return getVersionInfo(versionInfoEntity.getEntityId(), versionInfoEntity.getEntityType(), versionInfoEntity.getActiveVersion(), + versionInfoEntity.getCandidate(), versionInfoEntity.getStatus(), versionInfoEntity.getLatestFinalVersion(), + versionInfoEntity.getViewableVersions(), action, user); + } + + private static VersionInfo getVersionInfo(String entityId, String entityType, Version activeVer, UserCandidateVersion candidate, + VersionStatus status, Version latestFinalVersion, Set viewableVersions, + VersionableEntityAction action, String user) { + Version activeVersion; + if (action == VersionableEntityAction.Write) { + if (candidate != null) { + if (user.equals(candidate.getUser())) { + activeVersion = candidate.getVersion(); + } else { + throw new CoreException(new EditOnEntityLockedByOtherErrorBuilder(entityType, entityId, candidate.getUser()).build()); + } + } else { + throw new CoreException(new EditOnUnlockedEntityErrorBuilder(entityType, entityId).build()); + } } else { - throw new CoreException( - new EditOnEntityLockedByOtherErrorBuilder(entityType, entityId, candidate.getUser()) - .build()); + if (candidate != null && user.equals(candidate.getUser())) { + activeVersion = candidate.getVersion(); + } else { + activeVersion = activeVer; + } } - } else { - throw new CoreException(new EditOnUnlockedEntityErrorBuilder(entityType, entityId).build()); - } - } else { - if (candidate != null && user.equals(candidate.getUser())) { - activeVersion = candidate.getVersion(); - } else { - activeVersion = activeVer; - } - } - - VersionInfo versionInfo = new VersionInfo(); - versionInfo.setStatus(status); - activeVersion.setStatus(status); - if (latestFinalVersion != null) { - latestFinalVersion.setStatus(status); - } - if (viewableVersions != null) { - viewableVersions.forEach(version -> version.setStatus(status)); - versionInfo.setViewableVersions(toSortedList(viewableVersions)); - versionInfo.setFinalVersions(getFinalVersions(viewableVersions)); - } - versionInfo.setActiveVersion(activeVersion); - versionInfo.setLatestFinalVersion(latestFinalVersion); - if (candidate != null) { - candidate.getVersion().setStatus(status); - versionInfo.setLockingUser(candidate.getUser()); - if (user.equals(candidate.getUser())) { - versionInfo.getViewableVersions().add(candidate.getVersion()); - } - } - return versionInfo; - } - - private static List toSortedList( - Set versions) { // changing the Set to List in DB will require migration... - return versions.stream().sorted((o1, o2) -> o1.getMajor() > o2.getMajor() ? 1 - : o1.getMajor() == o2.getMajor() ? (o1.getMinor() > o2.getMinor() ? 1 - : o1.getMinor() == o2.getMinor() ? 0 : -1) : -1).collect(Collectors.toList()); - } - - private static List getFinalVersions(Set versions) { - return versions.stream().filter(Version::isFinal).collect(Collectors.toList()); - } - - @Override - public void register(String entityType, VersionableEntityMetadata entityMetadata) { - Set entitiesMetadata = - VERSIONABLE_ENTITIES.computeIfAbsent(entityType, k -> new HashSet<>()); - entitiesMetadata.add(entityMetadata); - } - - @Override - public Version create(String entityType, String entityId, String user) { - VersionInfoEntity - versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity != null) { - throw new CoreException(new EntityAlreadyExistErrorBuilder(entityType, entityId).build()); - } - - versionInfoEntity = new VersionInfoEntity(entityType, entityId); - versionInfoEntity.setActiveVersion(INITIAL_ACTIVE_VERSION); - markAsCheckedOut(versionInfoEntity, user); - versionInfoDao.create(versionInfoEntity); - - return versionInfoEntity.getCandidate().getVersion(); - } - - @Override - public void delete(String entityType, String entityId, String user) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - switch (versionInfoEntity.getStatus()) { - case Locked: - throw new CoreException(new DeleteOnLockedEntityErrorBuilder(entityType, entityId, - versionInfoEntity.getCandidate().getUser()).build()); - default: - //do nothing - break; - } - - doDelete(versionInfoEntity); - } - - @Override - public void undoDelete(String entityType, String entityId, String user) { - VersionInfoDeletedEntity versionInfoDeletedEntity = - versionInfoDeletedDao.get(new VersionInfoDeletedEntity(entityType, entityId)); - if (versionInfoDeletedEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - doUndoDelete(versionInfoDeletedEntity); -} + VersionInfo versionInfo = new VersionInfo(); + versionInfo.setStatus(status); + activeVersion.setStatus(status); + if (latestFinalVersion != null) { + latestFinalVersion.setStatus(status); + } + if (viewableVersions != null) { + viewableVersions.forEach(version -> version.setStatus(status)); + versionInfo.setViewableVersions(toSortedList(viewableVersions)); + versionInfo.setFinalVersions(getFinalVersions(viewableVersions)); + } + versionInfo.setActiveVersion(activeVersion); + versionInfo.setLatestFinalVersion(latestFinalVersion); + if (candidate != null) { + candidate.getVersion().setStatus(status); + versionInfo.setLockingUser(candidate.getUser()); + if (user.equals(candidate.getUser())) { + versionInfo.getViewableVersions().add(candidate.getVersion()); + } + } + return versionInfo; + } - @Override - public Version checkout(String entityType, String entityId, String user) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - Version checkoutVersion = null; - switch (versionInfoEntity.getStatus()) { - case Locked: - throw new CoreException(new CheckoutOnLockedEntityErrorBuilder(entityType, entityId, - versionInfoEntity.getCandidate().getUser()).build()); - case Certified: - case Draft: - checkoutVersion = doCheckout(versionInfoEntity, user); - break; - default: - //do nothing - break; - } - - return checkoutVersion; - } - - @Override - public Version undoCheckout(String entityType, String entityId, String user) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - Version activeVersion = null; - switch (versionInfoEntity.getStatus()) { - case Locked: - if (!user.equals(versionInfoEntity.getCandidate().getUser())) { - throw new CoreException( - new UndoCheckoutOnEntityLockedByOtherErrorBuilder(entityType, entityId, - versionInfoEntity.getCandidate().getUser()).build()); + private static List toSortedList( + Set versions) { // changing the Set to List in DB will require migration... + return versions.stream().sorted((o1, o2) -> o1.getMajor() > o2.getMajor() ? 1 + : o1.getMajor() == o2.getMajor() ? (o1.getMinor() > o2.getMinor() ? 1 : o1.getMinor() == o2.getMinor() ? 0 : -1) : -1) + .collect(Collectors.toList()); + } + + private static List getFinalVersions(Set versions) { + return versions.stream().filter(Version::isFinal).collect(Collectors.toList()); + } + + @Override + public void register(String entityType, VersionableEntityMetadata entityMetadata) { + Set entitiesMetadata = VERSIONABLE_ENTITIES.computeIfAbsent(entityType, k -> new HashSet<>()); + entitiesMetadata.add(entityMetadata); + } + + @Override + public Version create(String entityType, String entityId, String user) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity != null) { + throw new CoreException(new EntityAlreadyExistErrorBuilder(entityType, entityId).build()); + } + versionInfoEntity = new VersionInfoEntity(entityType, entityId); + versionInfoEntity.setActiveVersion(INITIAL_ACTIVE_VERSION); + markAsCheckedOut(versionInfoEntity, user); + versionInfoDao.create(versionInfoEntity); + return versionInfoEntity.getCandidate().getVersion(); + } + + @Override + public void delete(String entityType, String entityId, String user) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); + } + switch (versionInfoEntity.getStatus()) { + case Locked: + throw new CoreException( + new DeleteOnLockedEntityErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); + default: + //do nothing + break; + } + doDelete(versionInfoEntity); + } + + @Override + public void undoDelete(String entityType, String entityId, String user) { + VersionInfoDeletedEntity versionInfoDeletedEntity = versionInfoDeletedDao.get(new VersionInfoDeletedEntity(entityType, entityId)); + if (versionInfoDeletedEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); + } + doUndoDelete(versionInfoDeletedEntity); + } + + @Override + public Version checkout(String entityType, String entityId, String user) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); + } + Version checkoutVersion = null; + switch (versionInfoEntity.getStatus()) { + case Locked: + throw new CoreException( + new CheckoutOnLockedEntityErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); + case Certified: + case Draft: + checkoutVersion = doCheckout(versionInfoEntity, user); + break; + default: + //do nothing + break; + } + return checkoutVersion; + } + + @Override + public Version undoCheckout(String entityType, String entityId, String user) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); + } + Version activeVersion = null; + switch (versionInfoEntity.getStatus()) { + case Locked: + if (!user.equals(versionInfoEntity.getCandidate().getUser())) { + throw new CoreException( + new UndoCheckoutOnEntityLockedByOtherErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); + } + activeVersion = undoCheckout(versionInfoEntity); + break; + case Certified: + case Draft: + throw new CoreException(new UndoCheckoutOnUnlockedEntityErrorBuilder(entityType, entityId).build()); + default: + //do nothing + break; + } + return activeVersion; + } + + private Version undoCheckout(VersionInfoEntity versionInfoEntity) { + deleteVersionFromEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getCandidate().getVersion(), + versionInfoEntity.getActiveVersion()); + versionInfoEntity.setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Certified : VersionStatus.Draft); + versionInfoEntity.setCandidate(null); + versionInfoDao.update(versionInfoEntity); + return versionInfoEntity.getActiveVersion(); + } + + @Override + public Version checkin(String entityType, String entityId, String user, String checkinDescription) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); } - activeVersion = undoCheckout(versionInfoEntity); - break; - case Certified: - case Draft: - throw new CoreException( - new UndoCheckoutOnUnlockedEntityErrorBuilder(entityType, entityId).build()); - default: - //do nothing - break; - } - - return activeVersion; - } - - private Version undoCheckout(VersionInfoEntity versionInfoEntity) { - deleteVersionFromEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), - versionInfoEntity.getCandidate().getVersion(), versionInfoEntity.getActiveVersion()); - - versionInfoEntity - .setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Certified - : VersionStatus.Draft); - versionInfoEntity.setCandidate(null); - versionInfoDao.update(versionInfoEntity); - return versionInfoEntity.getActiveVersion(); - } - - @Override - public Version checkin(String entityType, String entityId, String user, - String checkinDescription) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - Version checkedInVersion = null; - switch (versionInfoEntity.getStatus()) { - case Draft: - case Certified: - throw new CoreException( - new CheckinOnUnlockedEntityErrorBuilder(entityType, entityId).build()); - case Locked: - if (!user.equals(versionInfoEntity.getCandidate().getUser())) { - throw new CoreException(new CheckinOnEntityLockedByOtherErrorBuilder(entityType, entityId, - versionInfoEntity.getCandidate().getUser()).build()); + Version checkedInVersion = null; + switch (versionInfoEntity.getStatus()) { + case Draft: + case Certified: + throw new CoreException(new CheckinOnUnlockedEntityErrorBuilder(entityType, entityId).build()); + case Locked: + if (!user.equals(versionInfoEntity.getCandidate().getUser())) { + throw new CoreException( + new CheckinOnEntityLockedByOtherErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); + } + checkedInVersion = doCheckin(versionInfoEntity, checkinDescription); + break; + default: + //do nothing + break; + } + return checkedInVersion; + } + + @Override + public Version submit(String entityType, String entityId, String user, String submitDescription) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); + } + Version submitVersion = null; + switch (versionInfoEntity.getStatus()) { + case Certified: + throw new CoreException(new EntityAlreadyFinalizedErrorBuilder(entityType, entityId).build()); + case Locked: + throw new CoreException( + new SubmitLockedEntityNotAllowedErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); + case Draft: + submitVersion = doSubmit(versionInfoEntity, user, submitDescription); + break; + default: + //do nothing + break; + } + return submitVersion; + } + + @Override + public VersionInfo getEntityVersionInfo(String entityType, String entityId, String user, VersionableEntityAction action) { + VersionInfoEntity versionInfoEntity = versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); + if (versionInfoEntity == null) { + throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); } - checkedInVersion = doCheckin(versionInfoEntity, checkinDescription); - break; - default: - //do nothing - break; - } - - return checkedInVersion; - } - - @Override - public Version submit(String entityType, String entityId, String user, String submitDescription) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - - Version submitVersion = null; - switch (versionInfoEntity.getStatus()) { - case Certified: - throw new CoreException( - new EntityAlreadyFinalizedErrorBuilder(entityType, entityId).build()); - case Locked: - throw new CoreException(new SubmitLockedEntityNotAllowedErrorBuilder(entityType, entityId, - versionInfoEntity.getCandidate().getUser()).build()); - case Draft: - submitVersion = doSubmit(versionInfoEntity, user, submitDescription); - break; - default: - //do nothing - break; - } - - return submitVersion; - } - - @Override - public VersionInfo getEntityVersionInfo(String entityType, String entityId, String user, - VersionableEntityAction action) { - VersionInfoEntity versionInfoEntity = - versionInfoDao.get(new VersionInfoEntity(entityType, entityId)); - if (versionInfoEntity == null) { - throw new CoreException(new EntityNotExistErrorBuilder(entityType, entityId).build()); - } - return getVersionInfo(versionInfoEntity, user, action); - } - - @Override - public Map listEntitiesVersionInfo(String entityType, String user, - VersionableEntityAction action) { - Collection versionInfoEntities = - versionInfoDao.list(new VersionInfoEntity(entityType, null)); - Map activeVersions = new HashMap<>(); - for (VersionInfoEntity versionInfoEntity : versionInfoEntities) { - activeVersions - .put(versionInfoEntity.getEntityId(), getVersionInfo(versionInfoEntity, user, action)); - } - return activeVersions; - } - - @Override - public Map listDeletedEntitiesVersionInfo(String entityType, String user, - VersionableEntityAction action) { - Collection versionInfoDeletedEntities = - versionInfoDeletedDao.list(new VersionInfoDeletedEntity(entityType, null)); - Map activeVersions = new HashMap<>(); - - - for (VersionInfoDeletedEntity versionInfoDeletedEntity : versionInfoDeletedEntities) { - activeVersions.put(versionInfoDeletedEntity.getEntityId(), - getVersionInfo(versionInfoDeletedEntity, user, action)); - } - return activeVersions; - } - - @Override - public List list(String itemId) { - - List versions = versionDao.list(itemId); - Set versionsNames = versions.stream().map(Version::getName).collect(Collectors.toSet()); - versions.forEach(version -> { - version.setAdditionalInfo(new HashMap<>()); - versionCalculator.injectAdditionalInfo(version, versionsNames); - }); - return versions; - } - - @Override - public Version get(String itemId, Version version) { - return versionDao.get(itemId, version) - .map(retrievedVersion -> getUpdateRetrievedVersion(itemId, retrievedVersion)) - .orElseGet(() -> getSyncedVersion(itemId, version)); - } - - private Version getUpdateRetrievedVersion(String itemId, Version version) { - if (version.getStatus() == VersionStatus.Certified && - (version.getState().getSynchronizationState() == SynchronizationState.OutOfSync || - version.getState().isDirty())) { - forceSync(itemId, version); - LOGGER.info("Item Id {}, version Id {}: Force sync is done", itemId, version.getId()); - version = versionDao.get(itemId, version) - .orElseThrow(() -> new IllegalStateException( - "Get version after a successful force sync must return the version")); - } - return version; - } - - private Version getSyncedVersion(String itemId, Version version) { - sync(itemId, version); - LOGGER.info("Item Id {}, version Id {}: First time sync is done", itemId, version.getId()); - return versionDao.get(itemId, version) - .orElseThrow(() -> new IllegalStateException( - "Get version after a successful sync must return the version")); - } - - @Override - public Version create(String itemId, Version version, VersionCreationMethod creationMethod) { - String baseVersionName = null; - if (version.getBaseId() == null) { - version.setDescription("Initial version"); - } else { - baseVersionName = get(itemId, new Version(version.getBaseId())).getName(); - } - String versionName = versionCalculator.calculate(baseVersionName, creationMethod); - validateVersionName(itemId, versionName); - version.setName(versionName); - - versionDao.create(itemId, version); - asdcItemManager.updateVersionStatus(itemId, VersionStatus.Draft, null); - - publish(itemId, version, String.format("Create version: %s", version.getName())); - return version; - } - - private void validateVersionName(String itemId, String versionName) { - if (versionDao.list(itemId).stream() - .anyMatch(version -> versionName.equals(version.getName()))) { - String errorDescription = String - .format("Item %s: create version failed, a version with the name %s already exist", - itemId, versionName); - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId("VERSION_NAME_ALREADY_EXIST") - .withMessage(errorDescription) - .build()); - } - } - - @Override - public void submit(String itemId, Version version, String submitDescription) { - version = get(itemId, version); - - validateSubmit(itemId, version); - - version.setStatus(VersionStatus.Certified); - versionDao.update(itemId, version); - - publish(itemId, version, submitDescription); - - asdcItemManager.updateVersionStatus(itemId, VersionStatus.Certified, VersionStatus.Draft); - } - - private void validateSubmit(String itemId, Version version) { - if (version.getStatus() == VersionStatus.Certified) { - String errorDescription = String - .format("Item %s: submit version failed, version %s is already Certified", itemId, - version.getId()); - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId("VERSION_ALREADY_CERTIFIED") - .withMessage(errorDescription) - .build()); - } - } - - @Override - public void publish(String itemId, Version version, String message) { - versionDao.publish(itemId, version, message); - } - - - @Override - public void sync(String itemId, Version version) { - versionDao.sync(itemId, version); - } - - @Override - public void forceSync(String itemId, Version version) { - versionDao.forceSync(itemId, version); - } - - @Override - public void revert(String itemId, Version version, String revisionId) { - versionDao.revert(itemId, version, revisionId); - } - - @Override - public List listRevisions(String itemId, Version version) { - return versionDao.listRevisions(itemId, version); - } - - private void markAsCheckedOut(VersionInfoEntity versionInfoEntity, String checkingOutUser) { - versionInfoEntity.setStatus(VersionStatus.Locked); - versionInfoEntity.setCandidate(new UserCandidateVersion(checkingOutUser, - versionInfoEntity.getActiveVersion().calculateNextCandidate())); - } - - private Version doCheckout(VersionInfoEntity versionInfoEntity, String user) { - markAsCheckedOut(versionInfoEntity, user); - versionInfoDao.update(versionInfoEntity); - - initVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), - versionInfoEntity.getActiveVersion(), versionInfoEntity.getCandidate().getVersion()); - - return versionInfoEntity.getCandidate().getVersion(); - } - - private void doDelete(VersionInfoEntity versionInfoEntity) { - VersionInfoDeletedEntity versionInfoDeletedEntity = new VersionInfoDeletedEntity(); - versionInfoDeletedEntity.setStatus(versionInfoEntity.getStatus()); - versionInfoDeletedEntity.setViewableVersions(versionInfoEntity.getViewableVersions()); - versionInfoDeletedEntity.setActiveVersion(versionInfoEntity.getActiveVersion()); - versionInfoDeletedEntity.setCandidate(versionInfoEntity.getCandidate()); - versionInfoDeletedEntity.setEntityId(versionInfoEntity.getEntityId()); - versionInfoDeletedEntity.setEntityType(versionInfoEntity.getEntityType()); - versionInfoDeletedEntity.setLatestFinalVersion(versionInfoEntity.getLatestFinalVersion()); - versionInfoDeletedDao.create(versionInfoDeletedEntity); - versionInfoDao.delete(versionInfoEntity); - } - - private void doUndoDelete(VersionInfoDeletedEntity versionInfoDeletedEntity) { - VersionInfoEntity versionInfoEntity = new VersionInfoEntity(); - versionInfoEntity.setStatus(versionInfoDeletedEntity.getStatus()); - versionInfoEntity.setViewableVersions(versionInfoDeletedEntity.getViewableVersions()); - versionInfoEntity.setActiveVersion(versionInfoDeletedEntity.getActiveVersion()); - versionInfoEntity.setCandidate(versionInfoDeletedEntity.getCandidate()); - versionInfoEntity.setEntityId(versionInfoDeletedEntity.getEntityId()); - versionInfoEntity.setEntityType(versionInfoDeletedEntity.getEntityType()); - versionInfoEntity.setLatestFinalVersion(versionInfoDeletedEntity.getLatestFinalVersion()); - versionInfoDao.create(versionInfoEntity); - versionInfoDeletedDao.delete(versionInfoDeletedEntity); - } - - private Version doCheckin(VersionInfoEntity versionInfoEntity, String checkinDescription) { - UserCandidateVersion userCandidateVersion = versionInfoEntity.getCandidate(); - versionInfoEntity.setCandidate(null); - versionInfoEntity.setActiveVersion(userCandidateVersion.getVersion()); - versionInfoEntity.getViewableVersions().add(versionInfoEntity.getActiveVersion()); - versionInfoEntity.setStatus(VersionStatus.Draft); - - closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), - versionInfoEntity.getActiveVersion()); - - versionInfoDao.update(versionInfoEntity); - - return versionInfoEntity.getActiveVersion(); - } - - private Version doSubmit(VersionInfoEntity versionInfoEntity, String submittingUser, - String submitDescription) { - Version finalVersion = versionInfoEntity.getActiveVersion().calculateNextFinal(); - initVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), - versionInfoEntity.getActiveVersion(), finalVersion); - closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), - finalVersion); - - Set viewableVersions = new HashSet<>(); - for (Version version : versionInfoEntity.getViewableVersions()) { - if (version.isFinal()) { - viewableVersions.add(version); - } - } - viewableVersions.add(finalVersion); - versionInfoEntity.setViewableVersions(viewableVersions); - versionInfoEntity.setActiveVersion(finalVersion); - versionInfoEntity.setLatestFinalVersion(finalVersion); - versionInfoEntity.setStatus(VersionStatus.Certified); - versionInfoDao.update(versionInfoEntity); - - return finalVersion; - } - - private void initVersionOnEntity(String entityType, String entityId, Version baseVersion, - Version newVersion) { - Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); - if (entityMetadatas != null) { - for (VersionableEntityMetadata entityMetadata : entityMetadatas) { - VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) - .initVersion(entityMetadata, entityId, baseVersion, newVersion); - } - } - } - - private void deleteVersionFromEntity(String entityType, String entityId, - Version versionToDelete, Version backToVersion) { - Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); - if (entityMetadatas != null) { - for (VersionableEntityMetadata entityMetadata : entityMetadatas) { - VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) - .deleteVersion(entityMetadata, entityId, versionToDelete, backToVersion); - } - } - } - - private void closeVersionOnEntity(String entityType, String entityId, Version versionToClose) { - Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); - if (entityMetadatas != null) { - for (VersionableEntityMetadata entityMetadata : entityMetadatas) { - VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) - .closeVersion(entityMetadata, entityId, versionToClose); - } - } - } + return getVersionInfo(versionInfoEntity, user, action); + } + + @Override + public Map listEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action) { + Collection versionInfoEntities = versionInfoDao.list(new VersionInfoEntity(entityType, null)); + Map activeVersions = new HashMap<>(); + for (VersionInfoEntity versionInfoEntity : versionInfoEntities) { + activeVersions.put(versionInfoEntity.getEntityId(), getVersionInfo(versionInfoEntity, user, action)); + } + return activeVersions; + } + + @Override + public Map listDeletedEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action) { + Collection versionInfoDeletedEntities = versionInfoDeletedDao.list(new VersionInfoDeletedEntity(entityType, null)); + Map activeVersions = new HashMap<>(); + for (VersionInfoDeletedEntity versionInfoDeletedEntity : versionInfoDeletedEntities) { + activeVersions.put(versionInfoDeletedEntity.getEntityId(), getVersionInfo(versionInfoDeletedEntity, user, action)); + } + return activeVersions; + } + + @Override + public List list(String itemId) { + List versions = versionDao.list(itemId); + Set versionsNames = versions.stream().map(Version::getName).collect(Collectors.toSet()); + versions.forEach(version -> { + version.setAdditionalInfo(new HashMap<>()); + versionCalculator.injectAdditionalInfo(version, versionsNames); + }); + return versions; + } + + @Override + public Version get(String itemId, Version version) { + return versionDao.get(itemId, version).map(retrievedVersion -> getUpdateRetrievedVersion(itemId, retrievedVersion)) + .orElseGet(() -> getSyncedVersion(itemId, version)); + } + + private Version getUpdateRetrievedVersion(String itemId, Version version) { + if (version.getStatus() == VersionStatus.Certified && (version.getState().getSynchronizationState() == SynchronizationState.OutOfSync + || version.getState().isDirty())) { + forceSync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: Force sync is done", itemId, version.getId()); + version = versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException("Get version after a successful force sync must return the version")); + } + return version; + } + + private Version getSyncedVersion(String itemId, Version version) { + sync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: First time sync is done", itemId, version.getId()); + return versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException("Get version after a successful sync must return the version")); + } + + @Override + public Version create(String itemId, Version version, VersionCreationMethod creationMethod) { + String baseVersionName = null; + if (version.getBaseId() == null) { + version.setDescription("Initial version"); + } else { + baseVersionName = get(itemId, new Version(version.getBaseId())).getName(); + } + String versionName = versionCalculator.calculate(baseVersionName, creationMethod); + validateVersionName(itemId, versionName); + version.setName(versionName); + versionDao.create(itemId, version); + asdcItemManager.updateVersionStatus(itemId, VersionStatus.Draft, null); + publish(itemId, version, String.format("Create version: %s", version.getName())); + return version; + } + + private void validateVersionName(String itemId, String versionName) { + if (versionDao.list(itemId).stream().anyMatch(version -> versionName.equals(version.getName()))) { + String errorDescription = String.format("Item %s: create version failed, a version with the name %s already exist", itemId, versionName); + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId("VERSION_NAME_ALREADY_EXIST") + .withMessage(errorDescription).build()); + } + } + + @Override + public void submit(String itemId, Version version, String submitDescription) { + version = get(itemId, version); + validateSubmit(itemId, version); + version.setStatus(VersionStatus.Certified); + versionDao.update(itemId, version); + publish(itemId, version, submitDescription); + asdcItemManager.updateVersionStatus(itemId, VersionStatus.Certified, VersionStatus.Draft); + } + + private void validateSubmit(String itemId, Version version) { + if (version.getStatus() == VersionStatus.Certified) { + String errorDescription = String.format("Item %s: submit version failed, version %s is already Certified", itemId, version.getId()); + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId("VERSION_ALREADY_CERTIFIED") + .withMessage(errorDescription).build()); + } + } + + @Override + public void publish(String itemId, Version version, String message) { + versionDao.publish(itemId, version, message); + } + + @Override + public void sync(String itemId, Version version) { + versionDao.sync(itemId, version); + } + + @Override + public void forceSync(String itemId, Version version) { + versionDao.forceSync(itemId, version); + } + + @Override + public void revert(String itemId, Version version, String revisionId) { + versionDao.revert(itemId, version, revisionId); + } + + @Override + public List listRevisions(String itemId, Version version) { + return versionDao.listRevisions(itemId, version); + } + + private void markAsCheckedOut(VersionInfoEntity versionInfoEntity, String checkingOutUser) { + versionInfoEntity.setStatus(VersionStatus.Locked); + versionInfoEntity.setCandidate(new UserCandidateVersion(checkingOutUser, versionInfoEntity.getActiveVersion().calculateNextCandidate())); + } + + private Version doCheckout(VersionInfoEntity versionInfoEntity, String user) { + markAsCheckedOut(versionInfoEntity, user); + versionInfoDao.update(versionInfoEntity); + initVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion(), + versionInfoEntity.getCandidate().getVersion()); + return versionInfoEntity.getCandidate().getVersion(); + } + + private void doDelete(VersionInfoEntity versionInfoEntity) { + VersionInfoDeletedEntity versionInfoDeletedEntity = new VersionInfoDeletedEntity(); + versionInfoDeletedEntity.setStatus(versionInfoEntity.getStatus()); + versionInfoDeletedEntity.setViewableVersions(versionInfoEntity.getViewableVersions()); + versionInfoDeletedEntity.setActiveVersion(versionInfoEntity.getActiveVersion()); + versionInfoDeletedEntity.setCandidate(versionInfoEntity.getCandidate()); + versionInfoDeletedEntity.setEntityId(versionInfoEntity.getEntityId()); + versionInfoDeletedEntity.setEntityType(versionInfoEntity.getEntityType()); + versionInfoDeletedEntity.setLatestFinalVersion(versionInfoEntity.getLatestFinalVersion()); + versionInfoDeletedDao.create(versionInfoDeletedEntity); + versionInfoDao.delete(versionInfoEntity); + } + + private void doUndoDelete(VersionInfoDeletedEntity versionInfoDeletedEntity) { + VersionInfoEntity versionInfoEntity = new VersionInfoEntity(); + versionInfoEntity.setStatus(versionInfoDeletedEntity.getStatus()); + versionInfoEntity.setViewableVersions(versionInfoDeletedEntity.getViewableVersions()); + versionInfoEntity.setActiveVersion(versionInfoDeletedEntity.getActiveVersion()); + versionInfoEntity.setCandidate(versionInfoDeletedEntity.getCandidate()); + versionInfoEntity.setEntityId(versionInfoDeletedEntity.getEntityId()); + versionInfoEntity.setEntityType(versionInfoDeletedEntity.getEntityType()); + versionInfoEntity.setLatestFinalVersion(versionInfoDeletedEntity.getLatestFinalVersion()); + versionInfoDao.create(versionInfoEntity); + versionInfoDeletedDao.delete(versionInfoDeletedEntity); + } + + private Version doCheckin(VersionInfoEntity versionInfoEntity, String checkinDescription) { + UserCandidateVersion userCandidateVersion = versionInfoEntity.getCandidate(); + versionInfoEntity.setCandidate(null); + versionInfoEntity.setActiveVersion(userCandidateVersion.getVersion()); + versionInfoEntity.getViewableVersions().add(versionInfoEntity.getActiveVersion()); + versionInfoEntity.setStatus(VersionStatus.Draft); + closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion()); + versionInfoDao.update(versionInfoEntity); + return versionInfoEntity.getActiveVersion(); + } + + private Version doSubmit(VersionInfoEntity versionInfoEntity, String submittingUser, String submitDescription) { + Version finalVersion = versionInfoEntity.getActiveVersion().calculateNextFinal(); + initVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion(), finalVersion); + closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), finalVersion); + Set viewableVersions = new HashSet<>(); + for (Version version : versionInfoEntity.getViewableVersions()) { + if (version.isFinal()) { + viewableVersions.add(version); + } + } + viewableVersions.add(finalVersion); + versionInfoEntity.setViewableVersions(viewableVersions); + versionInfoEntity.setActiveVersion(finalVersion); + versionInfoEntity.setLatestFinalVersion(finalVersion); + versionInfoEntity.setStatus(VersionStatus.Certified); + versionInfoDao.update(versionInfoEntity); + return finalVersion; + } + + private void initVersionOnEntity(String entityType, String entityId, Version baseVersion, Version newVersion) { + Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); + if (entityMetadatas != null) { + for (VersionableEntityMetadata entityMetadata : entityMetadatas) { + VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) + .initVersion(entityMetadata, entityId, baseVersion, newVersion); + } + } + } + + private void deleteVersionFromEntity(String entityType, String entityId, Version versionToDelete, Version backToVersion) { + Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); + if (entityMetadatas != null) { + for (VersionableEntityMetadata entityMetadata : entityMetadatas) { + VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) + .deleteVersion(entityMetadata, entityId, versionToDelete, backToVersion); + } + } + } + + private void closeVersionOnEntity(String entityType, String entityId, Version versionToClose) { + Set entityMetadatas = VERSIONABLE_ENTITIES.get(entityType); + if (entityMetadatas != null) { + for (VersionableEntityMetadata entityMetadata : entityMetadatas) { + VersionableEntityDaoFactory.getInstance().createInterface(entityMetadata.getStoreType()) + .closeVersion(entityMetadata, entityId, versionToClose); + } + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerFactoryImpl.java index 090f042027..f071d5e500 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; @@ -23,13 +22,12 @@ import org.openecomp.sdc.versioning.AsdcItemManagerFactory; import org.openecomp.sdc.versioning.dao.ItemDaoFactory; public class AsdcItemManagerFactoryImpl extends AsdcItemManagerFactory { - private static final AsdcItemManager INSTANCE = - new AsdcItemManagerImpl(ItemDaoFactory.getInstance().createInterface(), - PermissionsServicesFactory.getInstance().createInterface(), - SubscriptionServiceFactory.getInstance().createInterface()); - @Override - public AsdcItemManager createInterface() { - return INSTANCE; - } + private static final AsdcItemManager INSTANCE = new AsdcItemManagerImpl(ItemDaoFactory.getInstance().createInterface(), + PermissionsServicesFactory.getInstance().createInterface(), SubscriptionServiceFactory.getInstance().createInterface()); + + @Override + public AsdcItemManager createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerImpl.java index 82d3ae5a61..a4741f57e3 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/AsdcItemManagerImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.common.session.SessionContextProviderFactory; @@ -24,47 +23,39 @@ import org.openecomp.sdc.versioning.dao.ItemDao; import org.openecomp.sdc.versioning.types.Item; public class AsdcItemManagerImpl extends ItemManagerImpl implements AsdcItemManager { - private static final String CREATE_ITEM = "Create_Item"; - - private PermissionsServices permissionsServices; - private SubscriptionService subscriptionService; - - public AsdcItemManagerImpl(ItemDao itemDao, PermissionsServices permissionsServices, - SubscriptionService subscriptionService) { - super(itemDao); - - this.permissionsServices = permissionsServices; - this.subscriptionService = subscriptionService; - } - - @Override - public Item create(Item item) { - Item createdItem = super.create(item); - String userId = SessionContextProviderFactory.getInstance() - .createInterface().get().getUser().getUserId(); - String itemId = createdItem.getId(); - permissionsServices.execute(itemId, userId, CREATE_ITEM); - subscriptionService.subscribe(userId, itemId); + private static final String CREATE_ITEM = "Create_Item"; + private PermissionsServices permissionsServices; + private SubscriptionService subscriptionService; - return createdItem; - } - - - @Override - public void updateOwner(String itemId, String owner) { - Item item = get(itemId); - if (item == null) { - return; + public AsdcItemManagerImpl(ItemDao itemDao, PermissionsServices permissionsServices, SubscriptionService subscriptionService) { + super(itemDao); + this.permissionsServices = permissionsServices; + this.subscriptionService = subscriptionService; } - item.setOwner(owner); - super.update(item); - } - @Override - public void delete(Item item) { - super.delete(item); - } + @Override + public Item create(Item item) { + Item createdItem = super.create(item); + String userId = SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId(); + String itemId = createdItem.getId(); + permissionsServices.execute(itemId, userId, CREATE_ITEM); + subscriptionService.subscribe(userId, itemId); + return createdItem; + } + @Override + public void updateOwner(String itemId, String owner) { + Item item = get(itemId); + if (item == null) { + return; + } + item.setOwner(owner); + super.update(item); + } + @Override + public void delete(Item item) { + super.delete(item); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java index fbbc32e58e..77f4ef90c7 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.versioning.ItemManager; @@ -21,11 +20,11 @@ import org.openecomp.sdc.versioning.ItemManagerFactory; import org.openecomp.sdc.versioning.dao.ItemDaoFactory; public class ItemManagerFactoryImpl extends ItemManagerFactory { - private static final ItemManager instance = - new ItemManagerImpl(ItemDaoFactory.getInstance().createInterface()); - @Override - public ItemManager createInterface() { - return instance; - } + private static final ItemManager instance = new ItemManagerImpl(ItemDaoFactory.getInstance().createInterface()); + + @Override + public ItemManager createInterface() { + return instance; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java index 368eadad2c..8ef1fd2e04 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -25,98 +27,81 @@ import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.types.Item; import org.openecomp.sdc.versioning.types.ItemStatus; -import java.util.Collection; -import java.util.function.Predicate; -import java.util.stream.Collectors; - public class ItemManagerImpl implements ItemManager { - private ItemDao itemDao; - - - public ItemManagerImpl(ItemDao itemDao) { - this.itemDao = itemDao; - - } + private ItemDao itemDao; - @Override - public Collection list(Predicate predicate) { - return itemDao.list().stream().filter(predicate).collect(Collectors.toList()); - } - - @Override - public Item get(String itemId) { - Item item = new Item(); - item.setId(itemId); - return itemDao.get(item); - } - - @Override - public Item create(Item item) { - return itemDao.create(item); - } - - @Override - public void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, - VersionStatus removedVersionStatus) { - Item item = get(itemId); - if (item == null) { - return; + public ItemManagerImpl(ItemDao itemDao) { + this.itemDao = itemDao; } - item.addVersionStatus(addedVersionStatus); - if (removedVersionStatus != null) { - item.removeVersionStatus(removedVersionStatus); + @Override + public Collection list(Predicate predicate) { + return itemDao.list().stream().filter(predicate).collect(Collectors.toList()); } - itemDao.update(item); - } - @Override - public void delete(Item item) { - itemDao.delete(item); - } - - @Override - public void updateName(String itemId, String name) { - Item item = get(itemId); - if (item == null) { - return; + @Override + public Item get(String itemId) { + Item item = new Item(); + item.setId(itemId); + return itemDao.get(item); } - item.setName(name); - itemDao.update(item); - } - - @Override - public void archive(Item item) { + @Override + public Item create(Item item) { + return itemDao.create(item); + } - if (item.getStatus() == ItemStatus.ARCHIVED) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format("Archive item failed, item %s is already Archived", item.getId())) - .build()); + @Override + public void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, VersionStatus removedVersionStatus) { + Item item = get(itemId); + if (item == null) { + return; + } + item.addVersionStatus(addedVersionStatus); + if (removedVersionStatus != null) { + item.removeVersionStatus(removedVersionStatus); + } + itemDao.update(item); } - item.setStatus(ItemStatus.ARCHIVED); - itemDao.update(item); - } + @Override + public void delete(Item item) { + itemDao.delete(item); + } - @Override - public void restore(Item item) { + @Override + public void updateName(String itemId, String name) { + Item item = get(itemId); + if (item == null) { + return; + } + item.setName(name); + itemDao.update(item); + } - if (item.getStatus() == ItemStatus.ACTIVE) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format("Restore item failed, item %s is already Active", item.getId())) - .build()); - } + @Override + public void archive(Item item) { + if (item.getStatus() == ItemStatus.ARCHIVED) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format("Archive item failed, item %s is already Archived", item.getId())).build()); + } + item.setStatus(ItemStatus.ARCHIVED); + itemDao.update(item); + } - item.setStatus(ItemStatus.ACTIVE); - itemDao.update(item); + @Override + public void restore(Item item) { + if (item.getStatus() == ItemStatus.ACTIVE) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format("Restore item failed, item %s is already Active", item.getId())).build()); + } + item.setStatus(ItemStatus.ACTIVE); + itemDao.update(item); } - @Override - public void update(Item item) { - itemDao.update(item); - } + @Override + public void update(Item item) { + itemDao.update(item); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java index 8cb524c27c..ef3ca5059f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java @@ -23,11 +23,11 @@ import org.openecomp.sdc.versioning.VersionCalculator; import org.openecomp.sdc.versioning.VersionCalculatorFactory; public class MajorVersionCalculatorFactoryImpl extends VersionCalculatorFactory { - private static final VersionCalculator INSTANCE = - new MajorVersionCalculatorImpl(); - @Override - public VersionCalculator createInterface() { - return INSTANCE; - } + private static final VersionCalculator INSTANCE = new MajorVersionCalculatorImpl(); + + @Override + public VersionCalculator createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java index 008d96713f..c5e69ce647 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java @@ -19,54 +19,49 @@ */ package org.openecomp.sdc.versioning.impl; +import java.util.HashSet; +import java.util.Set; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.versioning.VersionCalculator; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.types.VersionCreationMethod; -import java.util.HashSet; -import java.util.Set; - public class MajorVersionCalculatorImpl implements VersionCalculator { - private static final String INITIAL_VERSION = "1.0"; - private static final String VERSION_STRING_VIOLATION_MSG = - "Version string must be in the format of: {integer}.{integer}"; - @Override - public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + private static final String INITIAL_VERSION = "1.0"; + private static final String VERSION_STRING_VIOLATION_MSG = "Version string must be in the format of: {integer}.{integer}"; - if (baseVersion == null) { - return INITIAL_VERSION; - } - - String[] versionLevels = baseVersion.split("\\."); - if (versionLevels.length != 2) { - throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + if (baseVersion == null) { + return INITIAL_VERSION; + } + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length != 2) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + int index = Integer.parseInt(versionLevels[0]); + index++; + versionLevels[0] = Integer.toString(index); + versionLevels[1] = "0"; + return CommonMethods.arrayToSeparatedString(versionLevels, '.'); } - int index = Integer.parseInt(versionLevels[0]); - index++; - versionLevels[0] = Integer.toString(index); - versionLevels[1] = "0"; - - return CommonMethods.arrayToSeparatedString(versionLevels, '.'); - } - - @Override - public void injectAdditionalInfo(Version version, Set existingVersions) { - String optionalVersion; - Set optionalCreationMethods = new HashSet<>(); - if(version.getStatus().equals(VersionStatus.Certified)) { - try { - optionalVersion = calculate(version.getName(), VersionCreationMethod.major); - if (!existingVersions.contains(optionalVersion)) { - optionalCreationMethods.add(VersionCreationMethod.major); + @Override + public void injectAdditionalInfo(Version version, Set existingVersions) { + String optionalVersion; + Set optionalCreationMethods = new HashSet<>(); + if (version.getStatus().equals(VersionStatus.Certified)) { + try { + optionalVersion = calculate(version.getName(), VersionCreationMethod.major); + if (!existingVersions.contains(optionalVersion)) { + optionalCreationMethods.add(VersionCreationMethod.major); + } + } catch (IllegalArgumentException iae) { + //not a valid creation method. + } } - } catch (IllegalArgumentException iae) { - //not a valid creation method. - } + version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); } - version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java index 155aa9c5e6..9f2b9fbe58 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java @@ -17,18 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.versioning.VersionCalculator; import org.openecomp.sdc.versioning.VersionCalculatorFactory; public class VersionCalculatorFactoryImpl extends VersionCalculatorFactory { - private static final VersionCalculator INSTANCE = - new VersionCalculatorImpl(); - @Override - public VersionCalculator createInterface() { - return INSTANCE; - } + private static final VersionCalculator INSTANCE = new VersionCalculatorImpl(); + + @Override + public VersionCalculator createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java index 5fe48ff7ca..4e9f460f04 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java @@ -19,6 +19,8 @@ */ package org.openecomp.sdc.versioning.impl; +import java.util.HashSet; +import java.util.Set; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -27,62 +29,55 @@ import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.types.VersionCreationMethod; -import java.util.HashSet; -import java.util.Set; - public class VersionCalculatorImpl implements VersionCalculator { - private static final Logger LOGGER = LoggerFactory.getLogger(VersionCalculatorImpl.class); - - private static final String INITIAL_VERSION = "1.0"; - private static final String VERSION_STRING_VIOLATION_MSG = - "Version string must be in the format of: {integer}.{integer}"; - private static final String INVALID_CREATION_METHOD_MSG = "Invalid creation method"; - @Override - public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + private static final Logger LOGGER = LoggerFactory.getLogger(VersionCalculatorImpl.class); + private static final String INITIAL_VERSION = "1.0"; + private static final String VERSION_STRING_VIOLATION_MSG = "Version string must be in the format of: {integer}.{integer}"; + private static final String INVALID_CREATION_METHOD_MSG = "Invalid creation method"; - if (baseVersion == null) { - return INITIAL_VERSION; - } - - String[] versionLevels = baseVersion.split("\\."); - if (versionLevels.length != 2) { - throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); - } - - int index; - switch (creationMethod) { - case major: - index = Integer.parseInt(versionLevels[0]); - index++; - versionLevels[0] = Integer.toString(index); - versionLevels[1] = "0"; - break; - case minor: - index = Integer.parseInt(versionLevels[1]); - index++; - versionLevels[1] = Integer.toString(index); - break; + @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + if (baseVersion == null) { + return INITIAL_VERSION; + } + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length != 2) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + int index; + switch (creationMethod) { + case major: + index = Integer.parseInt(versionLevels[0]); + index++; + versionLevels[0] = Integer.toString(index); + versionLevels[1] = "0"; + break; + case minor: + index = Integer.parseInt(versionLevels[1]); + index++; + versionLevels[1] = Integer.toString(index); + break; + } + return CommonMethods.arrayToSeparatedString(versionLevels, '.'); } - return CommonMethods.arrayToSeparatedString(versionLevels, '.'); - } - @Override - public void injectAdditionalInfo(Version version, Set existingVersions) { - String optionalVersion; - Set optionalCreationMethods = new HashSet<>(); - if(version.getStatus().equals(VersionStatus.Certified)) { - for (VersionCreationMethod versionCreationMethod : VersionCreationMethod.values()) { - try { - optionalVersion = calculate(version.getName(), versionCreationMethod); - if (!existingVersions.contains(optionalVersion)) { - optionalCreationMethods.add(versionCreationMethod); - } - } catch (IllegalArgumentException iae) { - LOGGER.error("{}:{}", INVALID_CREATION_METHOD_MSG, versionCreationMethod.name(), iae); + @Override + public void injectAdditionalInfo(Version version, Set existingVersions) { + String optionalVersion; + Set optionalCreationMethods = new HashSet<>(); + if (version.getStatus().equals(VersionStatus.Certified)) { + for (VersionCreationMethod versionCreationMethod : VersionCreationMethod.values()) { + try { + optionalVersion = calculate(version.getName(), versionCreationMethod); + if (!existingVersions.contains(optionalVersion)) { + optionalCreationMethods.add(versionCreationMethod); + } + } catch (IllegalArgumentException iae) { + LOGGER.error("{}:{}", INVALID_CREATION_METHOD_MSG, versionCreationMethod.name(), iae); + } + } } - } + version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); } - version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); - } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java index 83f3d77ae3..a8aad15677 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.versioning.ItemManagerFactory; @@ -24,12 +23,9 @@ import org.openecomp.sdc.versioning.dao.VersionDaoFactory; public class VersioningManagerFactoryImpl extends VersioningManagerFactory { - - @Override - public VersioningManager createInterface() { - return new VersioningManagerImpl( - VersionDaoFactory.getInstance().createInterface(), - VersionCalculatorFactory.getInstance().createInterface(), - ItemManagerFactory.getInstance().createInterface()); - } + @Override + public VersioningManager createInterface() { + return new VersioningManagerImpl(VersionDaoFactory.getInstance().createInterface(), VersionCalculatorFactory.getInstance().createInterface(), + ItemManagerFactory.getInstance().createInterface()); + } } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java index 95779c232c..6f1a7c4e13 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java @@ -13,9 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.versioning.impl; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Certified; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Draft; + +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -30,163 +36,128 @@ import org.openecomp.sdc.versioning.dao.types.SynchronizationState; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionCreationMethod; -import java.util.HashMap; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; +public class VersioningManagerImpl implements VersioningManager { -import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Certified; -import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Draft; + private static final Logger LOGGER = LoggerFactory.getLogger(VersioningManagerImpl.class); + private VersionDao versionDao; + private VersionCalculator versionCalculator; + private ItemManager itemManager; -public class VersioningManagerImpl implements VersioningManager { - private static final Logger LOGGER = LoggerFactory.getLogger(VersioningManagerImpl.class); - - private VersionDao versionDao; - private VersionCalculator versionCalculator; - private ItemManager itemManager; - - public VersioningManagerImpl(VersionDao versionDao, - VersionCalculator versionCalculator, - ItemManager itemManager) { - this.versionDao = versionDao; - this.versionCalculator = versionCalculator; - this.itemManager = itemManager; - } - - - @Override - public List list(String itemId) { - - List versions = versionDao.list(itemId); - Set versionsNames = versions.stream().map(Version::getName).collect(Collectors.toSet()); - versions.forEach(version -> { - version.setAdditionalInfo(new HashMap<>()); - versionCalculator.injectAdditionalInfo(version, versionsNames); - }); - return versions; - } - - @Override - public Version get(String itemId, Version version) { - return versionDao.get(itemId, version) - .map(retrievedVersion -> getUpdateRetrievedVersion(itemId, retrievedVersion)) - .orElseGet(() -> getSyncedVersion(itemId, version)); - } - - private Version getUpdateRetrievedVersion(String itemId, Version version) { - if (version.getStatus() == Certified && - (version.getState().getSynchronizationState() == SynchronizationState.OutOfSync || - version.getState().isDirty())) { - forceSync(itemId, version); - LOGGER.info("Item Id {}, version Id {}: Force sync is done", itemId, version.getId()); - version = versionDao.get(itemId, version) - .orElseThrow(() -> new IllegalStateException( - "Get version after a successful force sync must return the version")); - } - return version; - } - - private Version getSyncedVersion(String itemId, Version version) { - sync(itemId, version); - LOGGER.info("Item Id {}, version Id {}: First time sync is done", itemId, version.getId()); - return versionDao.get(itemId, version) - .orElseThrow(() -> new IllegalStateException( - "Get version after a successful sync must return the version")); - } - - @Override - public Version create(String itemId, Version version, VersionCreationMethod creationMethod) { - String baseVersionName = null; - if (version.getBaseId() == null) { - version.setDescription("Initial version"); - } else { - baseVersionName = get(itemId, new Version(version.getBaseId())).getName(); - } - String versionName = versionCalculator.calculate(baseVersionName, creationMethod); - validateVersionName(itemId, versionName); - version.setName(versionName); - - versionDao.create(itemId, version); - itemManager.updateVersionStatus(itemId, Draft, null); - - publish(itemId, version, String.format("Create version: %s", version.getName())); - return version; - } - - private void validateVersionName(String itemId, String versionName) { - if (versionDao.list(itemId).stream() - .anyMatch(version -> versionName.equals(version.getName()))) { - String errorDescription = String - .format("Item %s: create version failed, a version with the name %s already exist", - itemId, versionName); - - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(errorDescription) - .build()); - } - } - - @Override - public void submit(String itemId, Version version, String submitDescription) { - version = get(itemId, version); - - validateSubmit(itemId, version); - - version.setStatus(Certified); - versionDao.update(itemId, version); - - publish(itemId, version, submitDescription); - - itemManager.updateVersionStatus(itemId, Certified, Draft); - } - - private void validateSubmit(String itemId, Version version) { - if (version.getStatus() == Certified) { - String errorDescription = String - .format("Item %s: submit version failed, version %s is already Certified", itemId, - version.getId()); - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withId("VERSION_ALREADY_CERTIFIED") - .withMessage(errorDescription) - .build()); - } - } - - @Override - public void publish(String itemId, Version version, String message) { - versionDao.publish(itemId, version, message); - } - - - @Override - public void sync(String itemId, Version version) { - versionDao.sync(itemId, version); - } - - @Override - public void forceSync(String itemId, Version version) { - versionDao.forceSync(itemId, version); - } - - @Override - public void revert(String itemId, Version version, String revisionId) { - versionDao.revert(itemId, version, revisionId); - } - - @Override - public List listRevisions(String itemId, Version version) { - return versionDao.listRevisions(itemId, version); - } - - @Override - public void updateVersion(String itemId, Version version) { - versionDao.update(itemId, version); - } - - @Override - public void clean(String itemId, Version version) { - versionDao.clean(itemId, version); - } + public VersioningManagerImpl(VersionDao versionDao, VersionCalculator versionCalculator, ItemManager itemManager) { + this.versionDao = versionDao; + this.versionCalculator = versionCalculator; + this.itemManager = itemManager; + } + + @Override + public List list(String itemId) { + List versions = versionDao.list(itemId); + Set versionsNames = versions.stream().map(Version::getName).collect(Collectors.toSet()); + versions.forEach(version -> { + version.setAdditionalInfo(new HashMap<>()); + versionCalculator.injectAdditionalInfo(version, versionsNames); + }); + return versions; + } + + @Override + public Version get(String itemId, Version version) { + return versionDao.get(itemId, version).map(retrievedVersion -> getUpdateRetrievedVersion(itemId, retrievedVersion)) + .orElseGet(() -> getSyncedVersion(itemId, version)); + } + + private Version getUpdateRetrievedVersion(String itemId, Version version) { + if (version.getStatus() == Certified && (version.getState().getSynchronizationState() == SynchronizationState.OutOfSync || version.getState() + .isDirty())) { + forceSync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: Force sync is done", itemId, version.getId()); + version = versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException("Get version after a successful force sync must return the version")); + } + return version; + } + private Version getSyncedVersion(String itemId, Version version) { + sync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: First time sync is done", itemId, version.getId()); + return versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException("Get version after a successful sync must return the version")); + } + + @Override + public Version create(String itemId, Version version, VersionCreationMethod creationMethod) { + String baseVersionName = null; + if (version.getBaseId() == null) { + version.setDescription("Initial version"); + } else { + baseVersionName = get(itemId, new Version(version.getBaseId())).getName(); + } + String versionName = versionCalculator.calculate(baseVersionName, creationMethod); + validateVersionName(itemId, versionName); + version.setName(versionName); + versionDao.create(itemId, version); + itemManager.updateVersionStatus(itemId, Draft, null); + publish(itemId, version, String.format("Create version: %s", version.getName())); + return version; + } + + private void validateVersionName(String itemId, String versionName) { + if (versionDao.list(itemId).stream().anyMatch(version -> versionName.equals(version.getName()))) { + String errorDescription = String.format("Item %s: create version failed, a version with the name %s already exist", itemId, versionName); + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(errorDescription).build()); + } + } + + @Override + public void submit(String itemId, Version version, String submitDescription) { + version = get(itemId, version); + validateSubmit(itemId, version); + version.setStatus(Certified); + versionDao.update(itemId, version); + publish(itemId, version, submitDescription); + itemManager.updateVersionStatus(itemId, Certified, Draft); + } + + private void validateSubmit(String itemId, Version version) { + if (version.getStatus() == Certified) { + String errorDescription = String.format("Item %s: submit version failed, version %s is already Certified", itemId, version.getId()); + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION).withId("VERSION_ALREADY_CERTIFIED") + .withMessage(errorDescription).build()); + } + } + + @Override + public void publish(String itemId, Version version, String message) { + versionDao.publish(itemId, version, message); + } + + @Override + public void sync(String itemId, Version version) { + versionDao.sync(itemId, version); + } + + @Override + public void forceSync(String itemId, Version version) { + versionDao.forceSync(itemId, version); + } + + @Override + public void revert(String itemId, Version version, String revisionId) { + versionDao.revert(itemId, version, revisionId); + } + + @Override + public List listRevisions(String itemId, Version version) { + return versionDao.listRevisions(itemId, version); + } + + @Override + public void updateVersion(String itemId, Version version) { + versionDao.update(itemId, version); + } + + @Override + public void clean(String itemId, Version version) { + versionDao.clean(itemId, version); + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ServiceTemplateReaderService.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ServiceTemplateReaderService.java index afde5052d3..50656dcb89 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ServiceTemplateReaderService.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ServiceTemplateReaderService.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter; import java.util.List; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ToscaConverter.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ToscaConverter.java index d2e227d2f0..c9d3aa6224 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ToscaConverter.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/ToscaConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter; +import java.io.IOException; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import java.io.IOException; - public interface ToscaConverter { - ToscaServiceModel convert(FileContentHandler fileContentHandler) - throws IOException; + ToscaServiceModel convert(FileContentHandler fileContentHandler) throws IOException; } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/Constants.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/Constants.java index a8d29b9c6a..415bfe4180 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/Constants.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/Constants.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.converter.datatypes; public final class Constants { + public static final String MAIN_ST_NAME = "MainServiceTemplate.yaml"; public static final String GLOBAL_ST_NAME = "GlobalSubstitutionTypesServiceTemplate.yaml"; public static final String DEFINITIONS_DIR = "Definitions/"; @@ -32,13 +32,11 @@ public final class Constants { public static final String CAPABILITIES = "capabilities"; public static final String REQUIREMENTS = "requirements"; public static final String POLICIES = "policies"; - public static final String OPENECOMP_HEAT_INDEX = "openecomp_heat_index"; public static final String ONAP_INDEX = "onap_index"; public static final String GLOBAL_SUBSTITUTION = "GlobalSubstitutionTypes"; // prevent utility class instantiation - private Constants () { + private Constants() { } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java index 38b3e823f7..281ff3a7d7 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/datatypes/CsarFileTypes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.datatypes; public enum CsarFileTypes { diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java index b1b5098fed..314ecad73c 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; public class CreateToscaObjectErrorBuilder extends BaseErrorBuilder { - private static final String CANT_CREATE_OBJECT_FROM_CLASS = - "Can't create %s from %s."; - private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; - public CreateToscaObjectErrorBuilder(String className, - String objectId) { - getErrorCodeBuilder() - .withId(IMPORT_TOSCA) - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId)); - } + private static final String CANT_CREATE_OBJECT_FROM_CLASS = "Can't create %s from %s."; + private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; + + public CreateToscaObjectErrorBuilder(String className, String objectId) { + getErrorCodeBuilder().withId(IMPORT_TOSCA).withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId)); + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/SubstitutionMappingsConverterErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/SubstitutionMappingsConverterErrorBuilder.java index 8e09b27d11..03027bcd24 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/SubstitutionMappingsConverterErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/SubstitutionMappingsConverterErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,24 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; public class SubstitutionMappingsConverterErrorBuilder extends BaseErrorBuilder { - private static final String SUB_MAPPINGS_CAPABILITY_REQUIREMENT_ENTRY_VALUE_ILLEGAL = "%s value" + - " in substitution mappings is invalid, expected it to be %s"; - private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; - - public SubstitutionMappingsConverterErrorBuilder(String section, - String expectedType) { - getErrorCodeBuilder() - .withId(IMPORT_TOSCA) - .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(SUB_MAPPINGS_CAPABILITY_REQUIREMENT_ENTRY_VALUE_ILLEGAL, section, expectedType)); + private static final String SUB_MAPPINGS_CAPABILITY_REQUIREMENT_ENTRY_VALUE_ILLEGAL = + "%s value" + " in substitution mappings is invalid, expected it to be %s"; + private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; - } + public SubstitutionMappingsConverterErrorBuilder(String section, String expectedType) { + getErrorCodeBuilder().withId(IMPORT_TOSCA).withCategory(ErrorCategory.APPLICATION) + .withMessage(String.format(SUB_MAPPINGS_CAPABILITY_REQUIREMENT_ENTRY_VALUE_ILLEGAL, section, expectedType)); + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/factory/ToscaConverterFactory.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/factory/ToscaConverterFactory.java index 147d9e4376..3ca9863d67 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/factory/ToscaConverterFactory.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/factory/ToscaConverterFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.factory; import org.openecomp.core.converter.ToscaConverter; @@ -26,7 +25,7 @@ import org.openecomp.core.factory.api.AbstractFactory; public abstract class ToscaConverterFactory extends AbstractComponentFactory { - public static ToscaConverterFactory getInstance(){ - return AbstractFactory.getInstance(ToscaConverterFactory.class); - } + public static ToscaConverterFactory getInstance() { + return AbstractFactory.getInstance(ToscaConverterFactory.class); + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/PnfdTransformationEngine.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/PnfdTransformationEngine.java index 12949f2dcc..fa1487f444 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/PnfdTransformationEngine.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/PnfdTransformationEngine.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd; /** @@ -26,5 +25,4 @@ package org.openecomp.core.converter.pnfd; public interface PnfdTransformationEngine { void transform(); - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/exception/QueryOperationNotSupportedException.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/exception/QueryOperationNotSupportedException.java index a3f4b83812..e070c449ad 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/exception/QueryOperationNotSupportedException.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/exception/QueryOperationNotSupportedException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.exception; public class QueryOperationNotSupportedException extends RuntimeException { @@ -24,5 +23,4 @@ public class QueryOperationNotSupportedException extends RuntimeException { public QueryOperationNotSupportedException(final String s) { super(s); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionDefinition.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionDefinition.java index fa06ab800e..7ef99f2562 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionDefinition.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionDefinition.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import lombok.AllArgsConstructor; @@ -32,8 +31,7 @@ public class ConversionDefinition { private PnfdConversionStrategy pnfdConversionStrategy; private String toGetInput; - public ConversionDefinition(ConversionQuery conversionQuery, String toAttributeName, - PnfdConversionStrategy pnfdConversionStrategy) { + public ConversionDefinition(ConversionQuery conversionQuery, String toAttributeName, PnfdConversionStrategy pnfdConversionStrategy) { this.conversionQuery = conversionQuery; this.toAttributeName = toAttributeName; this.pnfdConversionStrategy = pnfdConversionStrategy; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionQuery.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionQuery.java index fc1ef75f05..ced653d8d8 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionQuery.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionQuery.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.Map; @@ -25,8 +24,8 @@ import lombok.EqualsAndHashCode; import lombok.Getter; /** - * Stores a YAML query. The query is a YAML Object that should have the same structure or part of the original YAML that - * is desired to find in a TOSCA Yaml block. + * Stores a YAML query. The query is a YAML Object that should have the same structure or part of the original YAML that is desired to find in a TOSCA + * Yaml block. */ @Getter @EqualsAndHashCode diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionStrategyType.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionStrategyType.java index b5c1f7c411..b58834b1fa 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionStrategyType.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/ConversionStrategyType.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.Optional; @@ -25,25 +24,18 @@ import java.util.Optional; * Represents a type of a conversion strategy */ public enum ConversionStrategyType { - COPY("copy"), - REPLACE("replace"), - REPLACE_IN_LIST("replaceInList"); - + COPY("copy"), REPLACE("replace"), REPLACE_IN_LIST("replaceInList"); private final String type; ConversionStrategyType(final String type) { this.type = type; } - public String getType() { - return type; - } - /** * Parse a String to the related {@link ConversionStrategyType}. - * @param type the {@link ConversionStrategyType} type - * @return - * The {@link ConversionStrategyType} representing the given type. + * + * @param type the {@link ConversionStrategyType} type + * @return The {@link ConversionStrategyType} representing the given type. */ public static Optional parse(final String type) { for (final ConversionStrategyType conversionStrategyType : values()) { @@ -51,7 +43,10 @@ public enum ConversionStrategyType { return Optional.of(conversionStrategyType); } } - return Optional.empty(); } + + public String getType() { + return type; + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/PnfTransformationToken.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/PnfTransformationToken.java index 886614799f..4a0433aeef 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/PnfTransformationToken.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/PnfTransformationToken.java @@ -16,13 +16,13 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; /** * Represents a token from the transformation descriptor */ public enum PnfTransformationToken { + // @formatter:off CONVERSIONS("conversions"), FROM("from"), LIST("list"), @@ -38,6 +38,7 @@ public enum PnfTransformationToken { TO_GET_INPUT("to-get-input"), PROPERTIES("properties"), NODE_TYPE("node_types"); + // @formatter:on private final String name; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/Transformation.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/Transformation.java index ff3e19bd1b..313ac2c158 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/Transformation.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/Transformation.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.List; @@ -38,7 +37,6 @@ import org.openecomp.sdc.logging.api.LoggerFactory; public class Transformation { private static final Logger LOGGER = LoggerFactory.getLogger(Transformation.class); - private String name; private String description; private TransformationBlock block; @@ -69,12 +67,10 @@ public class Transformation { final Transformation that = (Transformation) o; //if there is no query, compares by block and name. if (conversionQuery == null && that.conversionQuery == null) { - return block == that.block && - Objects.equals(name, that.name); + return block == that.block && Objects.equals(name, that.name); } //transformations with the same block and query will override themselves. - return block == that.block && - Objects.equals(conversionQuery, that.conversionQuery); + return block == that.block && Objects.equals(conversionQuery, that.conversionQuery); } @Override @@ -86,10 +82,8 @@ public class Transformation { if (CollectionUtils.isEmpty(propertySet)) { return Optional.empty(); } - final Optional transformationProperty = propertySet.stream() - .filter(transformationProperty1 -> transformationProperty1.getType() == type) - .findFirst(); + .filter(transformationProperty1 -> transformationProperty1.getType() == type).findFirst(); if (transformationProperty.isPresent()) { try { T value = clazz.cast(transformationProperty.get().getValue()); @@ -99,7 +93,6 @@ public class Transformation { return Optional.empty(); } } - return Optional.empty(); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationBlock.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationBlock.java index f8a5aee407..d29a8ca91f 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationBlock.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationBlock.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.Optional; @@ -29,19 +28,21 @@ import lombok.Getter; @AllArgsConstructor @Getter public enum TransformationBlock { + // @formatter:off INPUT("input"), GET_INPUT_FUNCTION("getInputFunction"), NODE_TEMPLATE("nodeTemplate"), CUSTOM_NODE_TYPE("customNodeType"), NODE_TYPE("nodeType"); + // @formatter:of private final String name; /** * Parse a String to the related {@link TransformationBlock}. - * @param name the {@link TransformationBlock} name - * @return - * The {@link TransformationBlock} representing the given name. + * + * @param name the {@link TransformationBlock} name + * @return The {@link TransformationBlock} representing the given name. */ public static Optional parse(final String name) { for (final TransformationBlock transformationBlock : values()) { @@ -49,7 +50,6 @@ public enum TransformationBlock { return Optional.of(transformationBlock); } } - return Optional.empty(); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationDescription.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationDescription.java index f21a719f8d..6aebc36d11 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationDescription.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationDescription.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.Set; @@ -28,5 +27,4 @@ import lombok.Getter; public class TransformationDescription { private final Set transformationSet; - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationProperty.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationProperty.java index c42917d95d..7616ec0f14 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationProperty.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationProperty.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import lombok.AllArgsConstructor; @@ -34,7 +33,6 @@ import lombok.Getter; public class TransformationProperty { private TransformationPropertyType type; - @EqualsAndHashCode.Exclude private T value; } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationPropertyType.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationPropertyType.java index eed251944f..4cf33085ca 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationPropertyType.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/model/TransformationPropertyType.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.model; import java.util.Arrays; @@ -31,12 +30,9 @@ import lombok.Getter; @AllArgsConstructor public enum TransformationPropertyType { NODE_NAME_PREFIX("nodeNamePrefix"); - private final String type; public static Optional parse(final String type) { - return Arrays.stream(values()) - .filter(transformationPropertyType -> transformationPropertyType.getType().equals(type)) - .findFirst(); + return Arrays.stream(values()).filter(transformationPropertyType -> transformationPropertyType.getType().equals(type)).findFirst(); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/parser/PnfdBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/parser/PnfdBlockParser.java index dd66f502ea..417a640abf 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/parser/PnfdBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/parser/PnfdBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.parser; import java.util.Map; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/AbstractPnfdConversionStrategy.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/AbstractPnfdConversionStrategy.java index ffd2e6fb34..31a87ea9e2 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/AbstractPnfdConversionStrategy.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/AbstractPnfdConversionStrategy.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.strategy; import java.util.Map; @@ -35,5 +34,4 @@ public abstract class AbstractPnfdConversionStrategy implements PnfdConver public ConversionStrategyType getStrategyType() { return strategyType; } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/PnfdConversionStrategy.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/PnfdConversionStrategy.java index 724f20550f..0e2888e887 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/PnfdConversionStrategy.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/pnfd/strategy/PnfdConversionStrategy.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.pnfd.strategy; import java.util.Optional; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/AbstractPnfdTransformationEngine.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/AbstractPnfdTransformationEngine.java index 2391ed6ecc..f97b1d37b2 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/AbstractPnfdTransformationEngine.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/AbstractPnfdTransformationEngine.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd; import java.io.IOException; @@ -38,23 +37,19 @@ import org.openecomp.sdc.logging.api.LoggerFactory; public abstract class AbstractPnfdTransformationEngine implements PnfdTransformationEngine { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractPnfdTransformationEngine.class); - protected final ServiceTemplate templateTo; protected final ServiceTemplateReaderService templateFrom; - private final PnfdTransformationDescriptorReader pnfdTransformationDescriptorReader = - new PnfdTransformationDescriptorReader(); + private final PnfdTransformationDescriptorReader pnfdTransformationDescriptorReader = new PnfdTransformationDescriptorReader(); + private final String descriptorResourcePath; protected TransformationDescription transformationDescription; protected Map> transformationGroupByBlockMap; - private final String descriptorResourcePath; - public AbstractPnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, - final ServiceTemplate templateTo) { + public AbstractPnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo) { this(templateFrom, templateTo, "pnfdTransformationTemplate/model-driven-conversion.yaml"); } //used for tests purposes - AbstractPnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, - final ServiceTemplate templateTo, + AbstractPnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo, final String descriptorResourcePath) { this.templateFrom = templateFrom; this.templateTo = templateTo; @@ -66,7 +61,7 @@ public abstract class AbstractPnfdTransformationEngine implements PnfdTransforma */ protected void readDefinition() { try (final InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(descriptorResourcePath)) { - if (resourceAsStream == null) { + if (resourceAsStream == null) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Could not find resource '{}'", descriptorResourcePath); } @@ -82,5 +77,4 @@ public abstract class AbstractPnfdTransformationEngine implements PnfdTransforma * Executes all transformations specified in the descriptor. */ protected abstract void executeTransformations(); - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTemplateTransformationEngine.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTemplateTransformationEngine.java index 3c996462fe..8ce29b8d6e 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTemplateTransformationEngine.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTemplateTransformationEngine.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd; import java.util.Collections; @@ -40,15 +39,13 @@ import org.openecomp.core.converter.pnfd.model.TransformationBlock; */ public class PnfdNodeTemplateTransformationEngine extends AbstractPnfdTransformationEngine { - public PnfdNodeTemplateTransformationEngine(final ServiceTemplateReaderService templateFrom, - final ServiceTemplate templateTo) { + public PnfdNodeTemplateTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo) { super(templateFrom, templateTo); } //used for tests purposes - PnfdNodeTemplateTransformationEngine(final ServiceTemplateReaderService templateFrom, - final ServiceTemplate templateTo, - final String descriptorResourcePath) { + PnfdNodeTemplateTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo, + final String descriptorResourcePath) { super(templateFrom, templateTo, descriptorResourcePath); } @@ -75,7 +72,6 @@ public class PnfdNodeTemplateTransformationEngine extends AbstractPnfdTransforma } } - /** * Execute all transformations specified in the descriptor. */ @@ -88,8 +84,7 @@ public class PnfdNodeTemplateTransformationEngine extends AbstractPnfdTransforma if (CollectionUtils.isEmpty(transformationSet)) { return; } - transformationGroupByBlockMap = transformationSet.stream() - .filter(Transformation::isValid) + transformationGroupByBlockMap = transformationSet.stream().filter(Transformation::isValid) .collect(Collectors.groupingBy(Transformation::getBlock)); executeCustomTypeTransformations(); final Map inputsToConvertMap = executeNodeTemplateTransformations(); @@ -98,56 +93,45 @@ public class PnfdNodeTemplateTransformationEngine extends AbstractPnfdTransforma /** * Parses all topology_template node_template. - * @return - * A map containing any input that was called with a get_input TOSCA function and its getInputFunction - * transformation name + * + * @return A map containing any input that was called with a get_input TOSCA function and its getInputFunction transformation name */ private Map executeNodeTemplateTransformations() { - final List transformationList = transformationGroupByBlockMap - .get(TransformationBlock.NODE_TEMPLATE); + final List transformationList = transformationGroupByBlockMap.get(TransformationBlock.NODE_TEMPLATE); if (CollectionUtils.isEmpty(transformationList)) { return Collections.emptyMap(); } - final Map inputsToConvertMap = new HashMap<>(); - transformationList.forEach(transformation -> - PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfParser -> { - pnfParser.parse(templateFrom, templateTo); - if (pnfParser.getInputAndTransformationNameMap().isPresent()) { - inputsToConvertMap.putAll(pnfParser.getInputAndTransformationNameMap().get()); - } - })); + transformationList.forEach(transformation -> PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfParser -> { + pnfParser.parse(templateFrom, templateTo); + if (pnfParser.getInputAndTransformationNameMap().isPresent()) { + inputsToConvertMap.putAll(pnfParser.getInputAndTransformationNameMap().get()); + } + })); return inputsToConvertMap; } /** * Parses all topology_template inputs called with a get_input TOSCA function. - * @param inputsToConvertMap A map containing the topology_template input name and its conversion definition name + * + * @param inputsToConvertMap A map containing the topology_template input name and its conversion definition name */ private void executeGetInputFunctionTransformations(final Map inputsToConvertMap) { - final List transformationListOfGetInputFunction = transformationGroupByBlockMap - .get(TransformationBlock.GET_INPUT_FUNCTION); - - if(MapUtils.isEmpty(inputsToConvertMap) || CollectionUtils.isEmpty(transformationListOfGetInputFunction)) { + final List transformationListOfGetInputFunction = transformationGroupByBlockMap.get(TransformationBlock.GET_INPUT_FUNCTION); + if (MapUtils.isEmpty(inputsToConvertMap) || CollectionUtils.isEmpty(transformationListOfGetInputFunction)) { return; } - final Map> transformationByName = transformationListOfGetInputFunction.stream() .collect(Collectors.groupingBy(Transformation::getName)); - inputsToConvertMap.forEach((inputName, transformationName) -> { final List transformationList = transformationByName.get(transformationName); if (!CollectionUtils.isEmpty(transformationList)) { - final Transformation transformation = transformationList.stream() - .findFirst().orElse(null); + final Transformation transformation = transformationList.stream().findFirst().orElse(null); if (transformation != null) { final Map conversionQueryMap = new HashMap<>(); conversionQueryMap.put(inputName, null); - transformation.setConversionQuery( - ConversionQueryYamlParser.parse(conversionQueryMap).orElse(null) - ); - PnfdBlockParserFactory.getInstance().get(transformation) - .ifPresent(pnfParser -> pnfParser.parse(templateFrom, templateTo)); + transformation.setConversionQuery(ConversionQueryYamlParser.parse(conversionQueryMap).orElse(null)); + PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfParser -> pnfParser.parse(templateFrom, templateTo)); } } }); @@ -157,14 +141,11 @@ public class PnfdNodeTemplateTransformationEngine extends AbstractPnfdTransforma * Parses a Customized Node Type that extend from a valid ONAP NodeType. */ private void executeCustomTypeTransformations() { - final List transformationList = transformationGroupByBlockMap - .get((TransformationBlock.CUSTOM_NODE_TYPE)); + final List transformationList = transformationGroupByBlockMap.get((TransformationBlock.CUSTOM_NODE_TYPE)); if (CollectionUtils.isEmpty(transformationList)) { return; } - transformationList.forEach(transformation -> - PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfdBlockParser -> - pnfdBlockParser.parse(templateFrom, templateTo))); + transformationList.forEach(transformation -> PnfdBlockParserFactory.getInstance().get(transformation) + .ifPresent(pnfdBlockParser -> pnfdBlockParser.parse(templateFrom, templateTo))); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTypeTransformationEngine.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTypeTransformationEngine.java index 48d06b67a4..3e6cca4609 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTypeTransformationEngine.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdNodeTypeTransformationEngine.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd; import java.util.Set; @@ -33,8 +32,7 @@ import org.openecomp.core.converter.pnfd.model.TransformationBlock; */ public class PnfdNodeTypeTransformationEngine extends AbstractPnfdTransformationEngine { - public PnfdNodeTypeTransformationEngine(final ServiceTemplateReaderService templateFrom, - final ServiceTemplate templateTo) { + public PnfdNodeTypeTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo) { super(templateFrom, templateTo); } @@ -57,16 +55,12 @@ public class PnfdNodeTypeTransformationEngine extends AbstractPnfdTransformation return; } final Set validNodeTypeTransformationSet = transformationSet.stream() - .filter(transformation -> transformation.getBlock() == TransformationBlock.NODE_TYPE) - .filter(Transformation::isValid) + .filter(transformation -> transformation.getBlock() == TransformationBlock.NODE_TYPE).filter(Transformation::isValid) .collect(Collectors.toSet()); - if (CollectionUtils.isEmpty(validNodeTypeTransformationSet)) { return; } - validNodeTypeTransformationSet.forEach(transformation -> - PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfdBlockParser -> - pnfdBlockParser.parse(templateFrom, templateTo))); + validNodeTypeTransformationSet.forEach(transformation -> PnfdBlockParserFactory.getInstance().get(transformation) + .ifPresent(pnfdBlockParser -> pnfdBlockParser.parse(templateFrom, templateTo))); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdQueryExecutor.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdQueryExecutor.java index 890dedb2a7..375dd2aa1a 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdQueryExecutor.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdQueryExecutor.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd; import java.util.List; @@ -33,36 +32,32 @@ import org.openecomp.core.converter.pnfd.model.ConversionQuery; public class PnfdQueryExecutor { private PnfdQueryExecutor() { - } /** * Finds if a YAML object contains the provided YAML query. - * @param conversionQuery The query - * @param yamlObject The YAML object to be searched - * @return - * {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. + * + * @param conversionQuery The query + * @param yamlObject The YAML object to be searched + * @return {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. */ public static boolean find(final ConversionQuery conversionQuery, final Object yamlObject) { return find(conversionQuery.getQuery(), yamlObject); } /** - * Recursive structure combined with {@link #findMap(Map, Map)} to find if a YAML object contains the provided YAML query. - * Compares the objects if it's a scalar value, otherwise go further in the YAML hierarchical structure - * calling the {@link #findMap(Map, Map)}. - * @param query The current query - * @param yamlObject The current YAML object to be searched - * @return - * {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. + * Recursive structure combined with {@link #findMap(Map, Map)} to find if a YAML object contains the provided YAML query. Compares the objects if + * it's a scalar value, otherwise go further in the YAML hierarchical structure calling the {@link #findMap(Map, Map)}. + * + * @param query The current query + * @param yamlObject The current YAML object to be searched + * @return {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. */ private static boolean find(final Object query, final Object yamlObject) { if (query == null) { return true; } - checkSupportedQueryType(query); - if (query instanceof String) { return query.equals(yamlObject); } @@ -74,20 +69,18 @@ public class PnfdQueryExecutor { /** * Recursive structure combined with {@link #find(Object, Object)} to find if a YAML object contains the provided YAML query. * - * @param query The query current object - * @param yamlObject The YAML object to be searched - * @return - * {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. + * + * @param query The query current object + * @param yamlObject The YAML object to be searched + * @return {@code true} if the YAML query structure was found in the YAML object, {@code false} otherwise. */ private static boolean findMap(final Map query, final Map yamlObject) { if (MapUtils.isEmpty(query) || MapUtils.isEmpty(yamlObject)) { return false; } - if (!yamlObject.keySet().containsAll(query.keySet())) { return false; } - return query.entrySet().parallelStream().allMatch(queryEntryObj -> { final Entry queryEntry = (Entry) queryEntryObj; return find(queryEntry.getValue(), yamlObject.get(queryEntry.getKey())); @@ -96,7 +89,8 @@ public class PnfdQueryExecutor { /** * Checks the supported types for a query. - * @param query the query to check + * + * @param query the query to check */ private static void checkSupportedQueryType(final Object query) { if (query instanceof String || query instanceof Map) { @@ -105,9 +99,6 @@ public class PnfdQueryExecutor { if (query instanceof List || query instanceof Set) { throw new QueryOperationNotSupportedException("Yaml list query is not supported yet"); } - throw new QueryOperationNotSupportedException( - String.format("Yaml query operation for '%s' is not supported yet", query.getClass()) - ); + throw new QueryOperationNotSupportedException(String.format("Yaml query operation for '%s' is not supported yet", query.getClass())); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdTransformationDescriptorReader.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdTransformationDescriptorReader.java index d040c93d09..a4dcc8a27a 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdTransformationDescriptorReader.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/PnfdTransformationDescriptorReader.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd; import java.io.FileNotFoundException; @@ -45,20 +44,19 @@ public class PnfdTransformationDescriptorReader { /** * Parse the transformation description to {@link TransformationDescription} class. - * @return - * The {@link TransformationDescription} instance. + * + * @return The {@link TransformationDescription} instance. */ public TransformationDescription parse(final InputStream transformationDescriptionInputStream) { final List transformationList = readDescriptionYaml(transformationDescriptionInputStream); final Set transformationSet = parseTransformationList(transformationList); - return new TransformationDescription(transformationSet); } /** * Reads the description file that has the required YAML format. - * @return - * The yaml parsed to Object + * + * @return The yaml parsed to Object */ private List readDescriptionYaml(final InputStream transformationDescriptionPath) { try (final InputStream fileInputStream = transformationDescriptionPath) { @@ -73,19 +71,15 @@ public class PnfdTransformationDescriptorReader { /** * Parse the transformation list represented in a YAML object to {@link Transformation}. - * @param transformationYamlList the YAML object read from the transformation description file - * @return - * The set of transformations represented as {@link Transformation} class + * + * @param transformationYamlList the YAML object read from the transformation description file + * @return The set of transformations represented as {@link Transformation} class */ private Set parseTransformationList(final List transformationYamlList) { if (CollectionUtils.isEmpty(transformationYamlList)) { return Collections.emptySet(); } - - return transformationYamlList.stream() - .map(conversionMap -> TransformationYamlParser.parse((Map) conversionMap).orElse(null)) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + return transformationYamlList.stream().map(conversionMap -> TransformationYamlParser.parse((Map) conversionMap).orElse(null)) + .filter(Objects::nonNull).collect(Collectors.toSet()); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/factory/PnfdBlockParserFactory.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/factory/PnfdBlockParserFactory.java index 12dd790c9d..0b3c5c944e 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/factory/PnfdBlockParserFactory.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/factory/PnfdBlockParserFactory.java @@ -16,13 +16,12 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.factory; import java.util.Optional; +import org.openecomp.core.converter.impl.pnfd.parser.PnfdCustomNodeTypeBlockParser; import org.openecomp.core.converter.impl.pnfd.parser.PnfdInputBlockParser; import org.openecomp.core.converter.impl.pnfd.parser.PnfdNodeTemplateBlockParser; -import org.openecomp.core.converter.impl.pnfd.parser.PnfdCustomNodeTypeBlockParser; import org.openecomp.core.converter.impl.pnfd.parser.PnfdNodeTypeBlockParser; import org.openecomp.core.converter.pnfd.model.Transformation; import org.openecomp.core.converter.pnfd.parser.PnfdBlockParser; @@ -31,6 +30,7 @@ import org.openecomp.core.converter.pnfd.parser.PnfdBlockParser; * Factory for {@link PnfdBlockParser}. */ public class PnfdBlockParserFactory { + private static PnfdBlockParserFactory instance; private PnfdBlockParserFactory() { @@ -40,7 +40,6 @@ public class PnfdBlockParserFactory { if (instance == null) { instance = new PnfdBlockParserFactory(); } - return instance; } @@ -59,5 +58,4 @@ public class PnfdBlockParserFactory { return Optional.empty(); } } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/AbstractPnfdBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/AbstractPnfdBlockParser.java index 056d07aed0..fcf6ec8735 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/AbstractPnfdBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/AbstractPnfdBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import com.google.common.collect.ImmutableMap; @@ -48,11 +47,10 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { } /** - * Parses a PNFD block based on the {@link Transformation} provided during the {@link PnfdBlockParser} - * instantiation. + * Parses a PNFD block based on the {@link Transformation} provided during the {@link PnfdBlockParser} instantiation. * * @param templateFrom the original PNFD template - * @param templateTo the resulting PNFD template + * @param templateTo the resulting PNFD template */ public void parse(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo) { this.templateFrom = templateFrom; @@ -64,8 +62,7 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { } /** - * Applies all specified conversions in {@link Transformation#getConversionDefinitionList()} for the given - * blockYamlObject. + * Applies all specified conversions in {@link Transformation#getConversionDefinitionList()} for the given blockYamlObject. * * @param blockYamlObject the block content as a YAML object */ @@ -76,37 +73,31 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { final List conversionDefinitionList = transformation.getConversionDefinitionList(); final Map parsedBlockYamlObject = new HashMap<>(); final String blockName = blockYamlObject.keySet().iterator().next(); - conversionDefinitionList.stream() - .filter(conversionDefinition -> conversionDefinition.getConversionQuery().isValidAttributeQuery()) + conversionDefinitionList.stream().filter(conversionDefinition -> conversionDefinition.getConversionQuery().isValidAttributeQuery()) .forEach(conversionDefinition -> { - final Map query = - (Map) conversionDefinition.getConversionQuery().getQuery(); + final Map query = (Map) conversionDefinition.getConversionQuery().getQuery(); final Map blockAttributeMap = (Map) blockYamlObject.get(blockName); - final Optional> parsedBlockAttributeMap = buildParsedBlock(query, blockAttributeMap - , conversionDefinition); - parsedBlockAttributeMap.ifPresent(convertedNodeTemplateAttributeMap1 -> - mergeYamlObjects(parsedBlockYamlObject, convertedNodeTemplateAttributeMap1) - ); + final Optional> parsedBlockAttributeMap = buildParsedBlock(query, blockAttributeMap, conversionDefinition); + parsedBlockAttributeMap + .ifPresent(convertedNodeTemplateAttributeMap1 -> mergeYamlObjects(parsedBlockYamlObject, convertedNodeTemplateAttributeMap1)); }); - write(blockName, parsedBlockYamlObject); } /** * Writes the block in the resulting {@link ServiceTemplate} {@link #templateTo}. * - * @param blockName the name of the block + * @param blockName the name of the block * @param parsedBlockYamlObject the block content as a YAML object */ protected abstract void write(final String blockName, final Map parsedBlockYamlObject); /** - * Uses the provided attribute query to find a attribute in the original YAML object and apply the provided - * conversion. + * Uses the provided attribute query to find a attribute in the original YAML object and apply the provided conversion. * - * @param attributeQuery the attribute query + * @param attributeQuery the attribute query * @param fromNodeTemplateAttributeMap the original YAML object - * @param conversionDefinition the conversion + * @param conversionDefinition the conversion * @return the rebuilt original YAML object with the converted attribute */ protected abstract Optional> buildParsedBlock(final Map attributeQuery, @@ -116,28 +107,22 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { /** * Merges two YAML objects. * - * @param originalMap original YAML object + * @param originalMap original YAML object * @param toBeMergedMap YAML object to be merged * @return the new YAML object representing the merge result. */ - protected Map mergeYamlObjects(final Map originalMap, - final Map toBeMergedMap) { - toBeMergedMap.forEach( - (key, value) -> originalMap.merge(key, value, - (toBeMergedValue, originalValue) -> { - if (originalValue instanceof Map) { - return mergeYamlObjects((Map) originalValue, (Map) toBeMergedValue); - } - return originalValue; - }) - ); - + protected Map mergeYamlObjects(final Map originalMap, final Map toBeMergedMap) { + toBeMergedMap.forEach((key, value) -> originalMap.merge(key, value, (toBeMergedValue, originalValue) -> { + if (originalValue instanceof Map) { + return mergeYamlObjects((Map) originalValue, (Map) toBeMergedValue); + } + return originalValue; + })); return originalMap; } /** - * Executes the provided {@link #transformation getConversionQuery} YAML query to find the blocks to be parsed in - * {@link #templateFrom}. + * Executes the provided {@link #transformation getConversionQuery} YAML query to find the blocks to be parsed in {@link #templateFrom}. * * @return The YAML blocks found */ @@ -154,12 +139,12 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { final Map yamlMap = (Map) yamlObject; return yamlMap.containsKey(PnfTransformationToken.GET_INPUT.getName()); } - return false; } /** * Extracts the value from an YAML Object. + * * @param yamlObject * @return The Object value from the yamlObject parameter. */ @@ -168,7 +153,6 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { final Map yamlMap = (Map) yamlObject; return (String) yamlMap.values().stream().findFirst().orElse(null); } - return null; } @@ -183,18 +167,15 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { /** * Finds all the derived node types from the provided node types. * - * @param rootNodeTypeMap a map with the root node types to find the derived ones + * @param rootNodeTypeMap a map with the root node types to find the derived ones * @param derivedNodeTypeMap a map that will be filled with the derived node types */ - private void findAllDerivedNodeType(final Map rootNodeTypeMap, - final Map derivedNodeTypeMap) { - templateFrom.getNodeTypes().entrySet().stream() - .filter(nodeEntry -> rootNodeTypeMap.containsKey(extractObjectValue(nodeEntry.getValue()))) + private void findAllDerivedNodeType(final Map rootNodeTypeMap, final Map derivedNodeTypeMap) { + templateFrom.getNodeTypes().entrySet().stream().filter(nodeEntry -> rootNodeTypeMap.containsKey(extractObjectValue(nodeEntry.getValue()))) .forEach(nodeEntry -> { if (!derivedNodeTypeMap.containsKey(nodeEntry.getKey())) { derivedNodeTypeMap.put(nodeEntry.getKey(), nodeEntry.getValue()); - final ImmutableMap newRootNodeTypeMap = ImmutableMap - .of(nodeEntry.getKey(), nodeEntry.getValue()); + final ImmutableMap newRootNodeTypeMap = ImmutableMap.of(nodeEntry.getKey(), nodeEntry.getValue()); findAllDerivedNodeType(newRootNodeTypeMap, derivedNodeTypeMap); } }); @@ -202,6 +183,7 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { /** * Fetches all Custom NodeTypes based on the query result. + * * @return a map with all custom Node Types that matches with the query result. */ protected Map fetchCustomNodeType() { @@ -211,16 +193,13 @@ public abstract class AbstractPnfdBlockParser implements PnfdBlockParser { } final ConversionQuery conversionQuery = transformation.getConversionQuery(); final Map customNodeTypesMap = new HashMap<>(); - nodeTypesMap.entrySet().stream() - .filter(nodeEntry -> PnfdQueryExecutor.find(conversionQuery, nodeEntry.getValue())) - .forEach(customNode -> { - attributeValueToBeConverted = extractObjectValue(customNode.getValue()); - customNodeTypesMap.put(customNode.getKey(), customNode.getValue()); - }); + nodeTypesMap.entrySet().stream().filter(nodeEntry -> PnfdQueryExecutor.find(conversionQuery, nodeEntry.getValue())).forEach(customNode -> { + attributeValueToBeConverted = extractObjectValue(customNode.getValue()); + customNodeTypesMap.put(customNode.getKey(), customNode.getValue()); + }); final Map childNodeTypeMap = new HashMap<>(); findAllDerivedNodeType(customNodeTypesMap, childNodeTypeMap); customNodeTypesMap.putAll(childNodeTypeMap); return customNodeTypesMap; } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionDefinitionYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionDefinitionYamlParser.java index 2ea9f2dc93..28d066d972 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionDefinitionYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionDefinitionYamlParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.Map; @@ -36,29 +35,25 @@ public class ConversionDefinitionYamlParser { private static final Logger LOGGER = LoggerFactory.getLogger(ConversionDefinitionYamlParser.class); private ConversionDefinitionYamlParser() { - } /** * Parses the given a YAML object to a {@link ConversionDefinition} instance. - * @param conversionYaml the YAML object representing a conversion definition - * @return - * A new instance of {@link ConversionDefinition}. + * + * @param conversionYaml the YAML object representing a conversion definition + * @return A new instance of {@link ConversionDefinition}. */ public static Optional parse(final Map conversionYaml) { - final ConversionQuery conversionQuery = ConversionQueryYamlParser - .parse(conversionYaml.get(PnfTransformationToken.QUERY.getName())).orElse(null); + final ConversionQuery conversionQuery = ConversionQueryYamlParser.parse(conversionYaml.get(PnfTransformationToken.QUERY.getName())) + .orElse(null); if (conversionQuery == null) { LOGGER.warn("Invalid '{}' for '{}'", PnfTransformationToken.QUERY.getName(), conversionYaml.toString()); return Optional.empty(); } final String toName = (String) conversionYaml.get(PnfTransformationToken.TO_NAME.getName()); final PnfdConversionStrategy toValue = PnfdConversionStrategyYamlParser - .parse((Map) conversionYaml.get(PnfTransformationToken.TO_VALUE.getName())) - .orElse(null); + .parse((Map) conversionYaml.get(PnfTransformationToken.TO_VALUE.getName())).orElse(null); final String toGetInput = (String) conversionYaml.get(PnfTransformationToken.TO_GET_INPUT.getName()); - return Optional.of(new ConversionDefinition(conversionQuery, toName, toValue, toGetInput)); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionQueryYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionQueryYamlParser.java index 374bf3702f..451498228c 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionQueryYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ConversionQueryYamlParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.Optional; @@ -28,20 +27,18 @@ import org.openecomp.core.converter.pnfd.model.ConversionQuery; public class ConversionQueryYamlParser { private ConversionQueryYamlParser() { - } /** * Parses the given a YAML object to a {@link ConversionQuery} instance. - * @param conversionYaml the YAML object representing a conversion query - * @return - * A new instance of {@link ConversionQuery}. + * + * @param conversionYaml the YAML object representing a conversion query + * @return A new instance of {@link ConversionQuery}. */ public static Optional parse(final Object conversionYaml) { if (conversionYaml == null) { return Optional.empty(); } - return Optional.of(new ConversionQuery(conversionYaml)); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTemplateYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTemplateYamlParser.java index fdf276f37d..354256e57f 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTemplateYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTemplateYamlParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.List; @@ -33,9 +32,9 @@ public class NodeTemplateYamlParser { /** * Parses the given a YAML object to a {@link NodeTemplate} instance. - * @param nodeTemplateYaml the YAML object representing a TOSCA Node Template - * @return - * A new instance of {@link NodeTemplate}. + * + * @param nodeTemplateYaml the YAML object representing a TOSCA Node Template + * @return A new instance of {@link NodeTemplate}. */ public static NodeTemplate parse(final Map nodeTemplateYaml) { final NodeTemplate nodeTemplate = new NodeTemplate(); @@ -47,9 +46,6 @@ public class NodeTemplateYamlParser { nodeTemplate.setDirectives((List) nodeTemplateYaml.get("directives")); nodeTemplate.setMetadata((Map) nodeTemplateYaml.get("metadata")); nodeTemplate.setInterfaces((Map) nodeTemplateYaml.get("interfaces")); - return nodeTemplate; } - - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTypeYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTypeYamlParser.java index b0b52e0c40..585d9e1bbf 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTypeYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/NodeTypeYamlParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.List; @@ -39,6 +38,7 @@ public class NodeTypeYamlParser { /** * Parses the given a YAML object to a {@link NodeType} instance. + * * @param nodeTypeYaml the YAML object representing a TOSCA Node Type * @return A new instance of {@link NodeType}. */ @@ -48,20 +48,13 @@ public class NodeTypeYamlParser { nodeType.setDerived_from((String) nodeTypeYaml.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName())); nodeType.setDescription((String) nodeTypeYaml.get(ToscaTagNamesEnum.DESCRIPTION.getElementName())); nodeType.setVersion((String) nodeTypeYaml.get("version")); - nodeType.setProperties( - (Map) nodeTypeYaml.get(ToscaTagNamesEnum.PROPERTIES.getElementName())); + nodeType.setProperties((Map) nodeTypeYaml.get(ToscaTagNamesEnum.PROPERTIES.getElementName())); nodeType.setArtifacts((Map) nodeTypeYaml.get("artifacts")); nodeType.setMetadata((Map) nodeTypeYaml.get("metadata")); - nodeType.setInterfaces( - (Map) nodeTypeYaml.get(ToscaTagNamesEnum.INTERFACES.getElementName())); - nodeType.setRequirements( - (List>) nodeTypeYaml.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); - nodeType.setCapabilities( - (Map) nodeTypeYaml.get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); - nodeType.setAttributes( - (Map) nodeTypeYaml.get(ToscaTagNamesEnum.ATTRIBUTES.getElementName())); - + nodeType.setInterfaces((Map) nodeTypeYaml.get(ToscaTagNamesEnum.INTERFACES.getElementName())); + nodeType.setRequirements((List>) nodeTypeYaml.get(ToscaTagNamesEnum.REQUIREMENTS.getElementName())); + nodeType.setCapabilities((Map) nodeTypeYaml.get(ToscaTagNamesEnum.CAPABILITIES.getElementName())); + nodeType.setAttributes((Map) nodeTypeYaml.get(ToscaTagNamesEnum.ATTRIBUTES.getElementName())); return nodeType; } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ParameterDefinitionYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ParameterDefinitionYamlParser.java index 4158deb9fe..53b0759a62 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ParameterDefinitionYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/ParameterDefinitionYamlParser.java @@ -16,13 +16,11 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.Map; import org.onap.sdc.tosca.datatypes.model.EntrySchema; import org.onap.sdc.tosca.datatypes.model.ParameterDefinition; -import org.onap.sdc.tosca.datatypes.model.Status; /** * Handles YAML from/to {@link ParameterDefinition} conversions @@ -34,9 +32,9 @@ public class ParameterDefinitionYamlParser { /** * Parses the given a YAML object to a {@link ParameterDefinition} instance. - * @param parameterDefinitionYaml the YAML object representing a TOSCA Parameter Definition - * @return - * A new instance of {@link ParameterDefinition}. + * + * @param parameterDefinitionYaml the YAML object representing a TOSCA Parameter Definition + * @return A new instance of {@link ParameterDefinition}. */ public static ParameterDefinition parse(final Map parameterDefinitionYaml) { final ParameterDefinition parameterDefinition = new ParameterDefinition(); @@ -51,7 +49,6 @@ public class ParameterDefinitionYamlParser { parameterDefinition.setRequired((Boolean) parameterDefinitionYaml.get("required")); parameterDefinition.setType((String) parameterDefinitionYaml.get("type")); parameterDefinition.setStatus((String) parameterDefinitionYaml.get("status")); - return parameterDefinition; } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdConversionStrategyYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdConversionStrategyYamlParser.java index dee16749ae..d927bc9537 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdConversionStrategyYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdConversionStrategyYamlParser.java @@ -16,19 +16,17 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.List; import java.util.Map; import java.util.Optional; -import org.openecomp.core.converter.pnfd.model.ConversionStrategyType; -import org.openecomp.core.converter.pnfd.model.PnfTransformationToken; import org.openecomp.core.converter.impl.pnfd.strategy.CopyConversionStrategy; -import org.openecomp.core.converter.pnfd.strategy.PnfdConversionStrategy; import org.openecomp.core.converter.impl.pnfd.strategy.ReplaceConversionStrategy; import org.openecomp.core.converter.impl.pnfd.strategy.ReplaceInListConversionStrategy; - +import org.openecomp.core.converter.pnfd.model.ConversionStrategyType; +import org.openecomp.core.converter.pnfd.model.PnfTransformationToken; +import org.openecomp.core.converter.pnfd.strategy.PnfdConversionStrategy; /** * Handles YAML from/to {@link PnfdConversionStrategy} conversions. @@ -36,24 +34,20 @@ import org.openecomp.core.converter.impl.pnfd.strategy.ReplaceInListConversionSt public class PnfdConversionStrategyYamlParser { private PnfdConversionStrategyYamlParser() { - } /** * Parses the given YAML object to a {@link PnfdConversionStrategy} instance. - * @param strategyYaml the YAML object representing a conversion strategy - * @return - * A new instance of {@link PnfdConversionStrategy}. + * + * @param strategyYaml the YAML object representing a conversion strategy + * @return A new instance of {@link PnfdConversionStrategy}. */ public static Optional parse(final Map strategyYaml) { - final Optional optionalStrategy = ConversionStrategyType.parse( - (String) strategyYaml.get(PnfTransformationToken.STRATEGY.getName()) - ); - + final Optional optionalStrategy = ConversionStrategyType + .parse((String) strategyYaml.get(PnfTransformationToken.STRATEGY.getName())); if (!optionalStrategy.isPresent()) { return Optional.empty(); } - final ConversionStrategyType strategyType = optionalStrategy.get(); if (strategyType == ConversionStrategyType.COPY) { return Optional.of(new CopyConversionStrategy()); @@ -64,11 +58,9 @@ public class PnfdConversionStrategyYamlParser { return Optional.of(new ReplaceConversionStrategy(from, to)); } if (strategyType == ConversionStrategyType.REPLACE_IN_LIST) { - return Optional.of(new ReplaceInListConversionStrategy( - (List>) strategyYaml.get(PnfTransformationToken.LIST.getName())) - ); + return Optional + .of(new ReplaceInListConversionStrategy((List>) strategyYaml.get(PnfTransformationToken.LIST.getName()))); } return Optional.empty(); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdCustomNodeTypeBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdCustomNodeTypeBlockParser.java index 3efde199b4..f242e9f1d2 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdCustomNodeTypeBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdCustomNodeTypeBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.Collections; @@ -45,21 +44,19 @@ public class PnfdCustomNodeTypeBlockParser extends AbstractPnfdBlockParser { if (customNodeTypeMap.isEmpty() || MapUtils.isEmpty(nodeTemplateMap)) { return Collections.emptySet(); } - return customNodeTypeMap.entrySet().stream() - .map(customNode -> { - final Map map = new HashMap<>(); - nodeTemplateMap.entrySet().stream() - .filter(nodeTemplate -> - extractObjectValue(nodeTemplate.getValue()).equalsIgnoreCase(customNode.getKey())) - .forEach(nodeType -> map.put(nodeType.getKey(), nodeType.getValue())); - return map; - }).collect(Collectors.toSet()); + return customNodeTypeMap.entrySet().stream().map(customNode -> { + final Map map = new HashMap<>(); + nodeTemplateMap.entrySet().stream() + .filter(nodeTemplate -> extractObjectValue(nodeTemplate.getValue()).equalsIgnoreCase(customNode.getKey())) + .forEach(nodeType -> map.put(nodeType.getKey(), nodeType.getValue())); + return map; + }).collect(Collectors.toSet()); } @Override protected Optional> buildParsedBlock(final Map attributeQuery, - final Map fromNodeTemplateAttributeMap, - final ConversionDefinition conversionDefinition) { + final Map fromNodeTemplateAttributeMap, + final ConversionDefinition conversionDefinition) { //cannot query for more than one attribute if (attributeQuery.keySet().size() > 1) { return Optional.empty(); @@ -84,5 +81,4 @@ public class PnfdCustomNodeTypeBlockParser extends AbstractPnfdBlockParser { DataModelUtil.addNodeTemplate(templateTo, nodeTemplateName, parsedNodeTemplate); } } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdInputBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdInputBlockParser.java index 4ce7b2e1c7..ddb3fe24fd 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdInputBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdInputBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import com.google.common.collect.ImmutableMap; @@ -42,8 +41,8 @@ public class PnfdInputBlockParser extends AbstractPnfdBlockParser { } @Override - protected Optional> buildParsedBlock(final Map attributeQuery, - final Map originalAttributeMap, final ConversionDefinition conversionDefinition) { + protected Optional> buildParsedBlock(final Map attributeQuery, final Map originalAttributeMap, + final ConversionDefinition conversionDefinition) { //cannot query for more than one attribute if (attributeQuery.keySet().size() > 1) { return Optional.empty(); @@ -59,7 +58,6 @@ public class PnfdInputBlockParser extends AbstractPnfdBlockParser { (Map) originalAttributeMap.get(attribute), conversionDefinition); builtInput.ifPresent(builtInput1 -> parsedInput.put(attribute, builtInput1)); } - return parsedInput.isEmpty() ? Optional.empty() : Optional.of(parsedInput); } @@ -78,16 +76,12 @@ public class PnfdInputBlockParser extends AbstractPnfdBlockParser { if (MapUtils.isEmpty(inputsMap)) { return Collections.emptySet(); } - return inputsMap.entrySet().stream() - .filter(inputMapEntry -> PnfdQueryExecutor - .find(conversionQuery, ImmutableMap.of(inputMapEntry.getKey(), inputMapEntry.getValue())) - ) + .filter(inputMapEntry -> PnfdQueryExecutor.find(conversionQuery, ImmutableMap.of(inputMapEntry.getKey(), inputMapEntry.getValue()))) .map(inputMapEntry -> { final Map map = new HashMap<>(); map.put(inputMapEntry.getKey(), inputMapEntry.getValue()); return map; }).collect(Collectors.toSet()); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTemplateBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTemplateBlockParser.java index 5d7a6049cd..713cbf9dba 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTemplateBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTemplateBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import java.util.Collections; @@ -50,9 +49,7 @@ public class PnfdNodeTemplateBlockParser extends AbstractPnfdBlockParser { if (MapUtils.isEmpty(nodeTemplateMap)) { return Collections.emptySet(); } - - return nodeTemplateMap.entrySet().stream() - .filter(mapEntry -> PnfdQueryExecutor.find(conversionQuery, mapEntry.getValue())) + return nodeTemplateMap.entrySet().stream().filter(mapEntry -> PnfdQueryExecutor.find(conversionQuery, mapEntry.getValue())) .map(stringObjectEntry -> { final Map map = new HashMap<>(); map.put(stringObjectEntry.getKey(), stringObjectEntry.getValue()); @@ -62,8 +59,8 @@ public class PnfdNodeTemplateBlockParser extends AbstractPnfdBlockParser { @Override protected Optional> buildParsedBlock(final Map attributeQuery, - final Map fromNodeTemplateAttributeMap, - final ConversionDefinition conversionDefinition) { + final Map fromNodeTemplateAttributeMap, + final ConversionDefinition conversionDefinition) { //cannot query for more than one attribute if (attributeQuery.keySet().size() > 1) { return Optional.empty(); @@ -74,9 +71,7 @@ public class PnfdNodeTemplateBlockParser extends AbstractPnfdBlockParser { if (queryValue == null) { PnfdConversionStrategy pnfdConversionStrategy = conversionDefinition.getPnfdConversionStrategy(); if (isGetInputFunction(attributeValueToConvert)) { - inputNameToConvertMap.put(extractObjectValue(attributeValueToConvert) - , conversionDefinition.getToGetInput() - ); + inputNameToConvertMap.put(extractObjectValue(attributeValueToConvert), conversionDefinition.getToGetInput()); pnfdConversionStrategy = new CopyConversionStrategy(); } final Map parsedNodeTemplate = new HashMap<>(); @@ -84,18 +79,15 @@ public class PnfdNodeTemplateBlockParser extends AbstractPnfdBlockParser { if (convertedAttribute.isPresent()) { parsedNodeTemplate.put(conversionDefinition.getToAttributeName(), convertedAttribute.get()); } - return parsedNodeTemplate.isEmpty() ? Optional.empty() : Optional.of(parsedNodeTemplate); } else { if (!(queryValue instanceof Map) || !(attributeValueToConvert instanceof Map)) { return Optional.empty(); } final Map parsedNodeTemplate = new HashMap<>(); - final Optional> builtNodeTemplate = buildParsedBlock( - (Map) queryValue, + final Optional> builtNodeTemplate = buildParsedBlock((Map) queryValue, (Map) attributeValueToConvert, conversionDefinition); builtNodeTemplate.ifPresent(builtNodeTemplate1 -> parsedNodeTemplate.put(attribute, builtNodeTemplate1)); - return parsedNodeTemplate.isEmpty() ? Optional.empty() : Optional.of(parsedNodeTemplate); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTypeBlockParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTypeBlockParser.java index 386bbfb558..e77200a906 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTypeBlockParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/PnfdNodeTypeBlockParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DERIVED_FROM; @@ -46,17 +45,12 @@ public class PnfdNodeTypeBlockParser extends AbstractPnfdBlockParser { if (customNodeTypeMap.isEmpty()) { return Collections.emptySet(); } - - final String nodeNamePrefix = - transformation.getPropertyValue(TransformationPropertyType.NODE_NAME_PREFIX, String.class) - .orElse(""); - - return customNodeTypeMap.entrySet().parallelStream() - .map(nodeEntry -> { - final Map map = new HashMap<>(); - map.put(nodeNamePrefix.concat(nodeEntry.getKey()), nodeEntry.getValue()); - return map; - }).collect(Collectors.toSet()); + final String nodeNamePrefix = transformation.getPropertyValue(TransformationPropertyType.NODE_NAME_PREFIX, String.class).orElse(""); + return customNodeTypeMap.entrySet().parallelStream().map(nodeEntry -> { + final Map map = new HashMap<>(); + map.put(nodeNamePrefix.concat(nodeEntry.getKey()), nodeEntry.getValue()); + return map; + }).collect(Collectors.toSet()); } @Override @@ -74,8 +68,7 @@ public class PnfdNodeTypeBlockParser extends AbstractPnfdBlockParser { if (queryValue == null) { PnfdConversionStrategy pnfdConversionStrategy = conversionDefinition.getPnfdConversionStrategy(); final Optional convertedAttribute = pnfdConversionStrategy - .convert(DERIVED_FROM.getElementName() - .equalsIgnoreCase(attribute) ? attributeValueToBeConverted : attributeValueToConvert); + .convert(DERIVED_FROM.getElementName().equalsIgnoreCase(attribute) ? attributeValueToBeConverted : attributeValueToConvert); if (convertedAttribute.isPresent()) { parsedNodeTemplate.put(conversionDefinition.getToAttributeName(), convertedAttribute.get()); } @@ -90,5 +83,4 @@ public class PnfdNodeTypeBlockParser extends AbstractPnfdBlockParser { DataModelUtil.addNodeType(templateTo, blockName, nodeTypeYamlParser); } } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/TransformationYamlParser.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/TransformationYamlParser.java index 92e1d8f392..210ffc6b5b 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/TransformationYamlParser.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/parser/TransformationYamlParser.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.parser; import static org.openecomp.core.converter.pnfd.model.PnfTransformationToken.CONVERSIONS; @@ -59,14 +58,13 @@ public class TransformationYamlParser { private static final Logger LOGGER = LoggerFactory.getLogger(TransformationYamlParser.class); private TransformationYamlParser() { - } /** * Parses the given YAML object to a {@link Transformation} instance. - * @param transformationYaml the YAML object representing a transformation - * @return - * A new instance of {@link Transformation}. + * + * @param transformationYaml the YAML object representing a transformation + * @return A new instance of {@link Transformation}. */ public static Optional parse(final Map transformationYaml) { final Transformation transformation = new Transformation(); @@ -77,7 +75,6 @@ public class TransformationYamlParser { transformation.setName(name.orElse(null)); transformation.setDescription(parseStringAttribute(DESCRIPTION.getName(), transformationYaml).orElse(null)); transformation.setPropertySet(readProperties(transformationYaml)); - final String block = parseStringAttribute(TRANSFORMATION_FOR.getName(), transformationYaml).orElse(null); final Optional transformationBlockOptional = TransformationBlock.parse(block); if (transformationBlockOptional.isPresent()) { @@ -85,14 +82,11 @@ public class TransformationYamlParser { transformation.setBlock(transformationBlock); parseTransformationBlock(transformationBlock, transformation, transformationYaml); } else { - LOGGER.warn("Invalid '{}' value in transformation '{}'", TRANSFORMATION_FOR.getName(), - transformationYaml.toString()); + LOGGER.warn("Invalid '{}' value in transformation '{}'", TRANSFORMATION_FOR.getName(), transformationYaml.toString()); } - if (transformation.isValid()) { return Optional.of(transformation); } - return Optional.empty(); } @@ -101,14 +95,10 @@ public class TransformationYamlParser { if (MapUtils.isEmpty(propertyMap)) { return Collections.emptySet(); } - final Set propertySet = new HashSet<>(); - propertyMap.forEach((key, value) -> { - final TransformationPropertyType transformationPropertyType = TransformationPropertyType.parse(key) - .orElse(null); - - if(transformationPropertyType != null) { + final TransformationPropertyType transformationPropertyType = TransformationPropertyType.parse(key).orElse(null); + if (transformationPropertyType != null) { if (value instanceof String) { propertySet.add(new TransformationProperty<>(transformationPropertyType, (String) value)); } else if (value instanceof Boolean) { @@ -120,72 +110,57 @@ public class TransformationYamlParser { } } }); - return propertySet; } - private static void parseTransformationBlock(final TransformationBlock transformationBlock, - final Transformation transformationReference, + private static void parseTransformationBlock(final TransformationBlock transformationBlock, final Transformation transformationReference, final Map transformationYaml) { if (transformationBlock == TransformationBlock.CUSTOM_NODE_TYPE) { parseCustomNodeTypeBlock(transformationReference, transformationYaml); return; } - - ConversionQueryYamlParser.parse(transformationYaml.get(QUERY.getName())) - .ifPresent(transformationReference::setConversionQuery); - + ConversionQueryYamlParser.parse(transformationYaml.get(QUERY.getName())).ifPresent(transformationReference::setConversionQuery); transformationReference.setConversionDefinitionList(parseConversions(transformationYaml)); } - private static void parseCustomNodeTypeBlock(final Transformation transformationReference, - final Map transformationYaml) { + private static void parseCustomNodeTypeBlock(final Transformation transformationReference, final Map transformationYaml) { final Object fromAttribute = transformationYaml.get(FROM.getName()); if (!(fromAttribute instanceof String)) { return; } final String from = parseStringAttribute(FROM.getName(), transformationYaml).orElse(null); - final Object toAttribute = transformationYaml.get(TO.getName()); if (!(toAttribute instanceof String)) { return; } final String to = parseStringAttribute(TO.getName(), transformationYaml).orElse(null); - final HashMap transformationQuery = new HashMap<>(); transformationQuery.put(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), from); transformationReference.setConversionQuery(new ConversionQuery(transformationQuery)); - final List conversionDefinitionList = new ArrayList<>(); final HashMap conversionDefinitionQuery = new HashMap<>(); conversionDefinitionQuery.put(ToscaTagNamesEnum.TYPE.getElementName(), null); - ConversionDefinition conversionDefinition = new ConversionDefinition(new ConversionQuery(conversionDefinitionQuery) - , ToscaTagNamesEnum.TYPE.getElementName(), new ReplaceConversionStrategy(from, to)); + ConversionDefinition conversionDefinition = new ConversionDefinition(new ConversionQuery(conversionDefinitionQuery), + ToscaTagNamesEnum.TYPE.getElementName(), new ReplaceConversionStrategy(from, to)); conversionDefinitionList.add(conversionDefinition); transformationReference.setConversionDefinitionList(conversionDefinitionList); } private static List parseConversions(final Map conversionYaml) { final List conversionList = (List) conversionYaml.get(CONVERSIONS.getName()); - if (CollectionUtils.isEmpty(conversionList)) { return Collections.emptyList(); } - - return conversionList.stream() - .map(conversion -> ConversionDefinitionYamlParser.parse((Map) conversion).orElse(null)) - .filter(Objects::nonNull) - .collect(Collectors.toList()); + return conversionList.stream().map(conversion -> ConversionDefinitionYamlParser.parse((Map) conversion).orElse(null)) + .filter(Objects::nonNull).collect(Collectors.toList()); } private static Optional parseStringAttribute(final String attribute, final Map transformationYaml) { try { return Optional.of((String) transformationYaml.get(attribute)); } catch (final Exception e) { - LOGGER.warn("Could not parse the String '{}' in transformation '{}'", - attribute, transformationYaml.toString(), e); + LOGGER.warn("Could not parse the String '{}' in transformation '{}'", attribute, transformationYaml.toString(), e); return Optional.empty(); } } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/CopyConversionStrategy.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/CopyConversionStrategy.java index c379dfa85c..762e997e01 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/CopyConversionStrategy.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/CopyConversionStrategy.java @@ -16,13 +16,12 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.strategy; import java.util.HashMap; import java.util.Optional; -import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; import org.openecomp.core.converter.pnfd.model.ConversionStrategyType; +import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; public class CopyConversionStrategy extends AbstractPnfdConversionStrategy { diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceConversionStrategy.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceConversionStrategy.java index 3bde6326b7..83f860b089 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceConversionStrategy.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceConversionStrategy.java @@ -16,13 +16,12 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.strategy; import java.util.HashMap; import java.util.Optional; -import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; import org.openecomp.core.converter.pnfd.model.ConversionStrategyType; +import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; public class ReplaceConversionStrategy extends AbstractPnfdConversionStrategy { @@ -35,5 +34,4 @@ public class ReplaceConversionStrategy extends AbstractPnfdConversionStrategy convert(final Object originalValue) { return Optional.ofNullable(conversionMap.get(originalValue)); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceInListConversionStrategy.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceInListConversionStrategy.java index 9984a8708d..de3b8ff8cb 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceInListConversionStrategy.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/converter/impl/pnfd/strategy/ReplaceInListConversionStrategy.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.converter.impl.pnfd.strategy; import java.util.HashMap; @@ -26,9 +25,9 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; -import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; import org.openecomp.core.converter.pnfd.model.ConversionStrategyType; import org.openecomp.core.converter.pnfd.model.PnfTransformationToken; +import org.openecomp.core.converter.pnfd.strategy.AbstractPnfdConversionStrategy; public class ReplaceInListConversionStrategy extends AbstractPnfdConversionStrategy, List> { @@ -37,11 +36,8 @@ public class ReplaceInListConversionStrategy extends AbstractPnfdConversionStrat public ReplaceInListConversionStrategy(final List> descriptorList) { super(ConversionStrategyType.REPLACE_IN_LIST, new HashMap<>()); replaceInListConversionStrategyMap = new LinkedHashMap<>(); - descriptorList - .forEach(stringObjectMap -> replaceInListConversionStrategyMap.put(stringObjectMap.get( - PnfTransformationToken.FROM.getName()) - , stringObjectMap.get(PnfTransformationToken.TO.getName())) - ); + descriptorList.forEach(stringObjectMap -> replaceInListConversionStrategyMap + .put(stringObjectMap.get(PnfTransformationToken.FROM.getName()), stringObjectMap.get(PnfTransformationToken.TO.getName()))); } @Override @@ -49,12 +45,8 @@ public class ReplaceInListConversionStrategy extends AbstractPnfdConversionStrat if (originalValue == null || originalValue.isEmpty()) { return Optional.empty(); } - - final List convertedList = originalValue.stream() - .map(replaceInListConversionStrategyMap::get) - .filter(Objects::nonNull) + final List convertedList = originalValue.stream().map(replaceInListConversionStrategyMap::get).filter(Objects::nonNull) .collect(Collectors.toList()); - return convertedList.isEmpty() ? Optional.empty() : Optional.of(convertedList); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaConverter.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaConverter.java index 7168192526..1be85a5759 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaConverter.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaConverter.java @@ -19,20 +19,20 @@ * * ============LICENSE_END========================================================= * */ - package org.openecomp.core.impl; -import static org.openecomp.core.converter.datatypes.Constants.ONAP_INDEX; import static org.openecomp.core.converter.datatypes.Constants.DEFINITIONS_DIR; import static org.openecomp.core.converter.datatypes.Constants.GLOBAL_ST_NAME; import static org.openecomp.core.converter.datatypes.Constants.GLOBAL_SUBSTITUTION; import static org.openecomp.core.converter.datatypes.Constants.MAIN_ST_NAME; +import static org.openecomp.core.converter.datatypes.Constants.ONAP_INDEX; import static org.openecomp.core.converter.datatypes.Constants.OPENECOMP_HEAT_INDEX; import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME; import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.HEAT_INDEX_IMPORT_FILE; import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.ONAP_INDEX_IMPORT_FILE; import static org.openecomp.sdc.tosca.csar.CSARConstants.TOSCA_META_ORIG_PATH_FILE_NAME; import static org.openecomp.sdc.tosca.csar.ToscaMetadataFileInfo.TOSCA_META_PATH_FILE_NAME; + import java.io.File; import java.util.ArrayList; import java.util.Collection; @@ -66,10 +66,10 @@ import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.error.YAMLException; public abstract class AbstractToscaConverter implements ToscaConverter { + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractToscaConverter.class); - public abstract void convertTopologyTemplate(@NotNull ServiceTemplate serviceTemplate, - ServiceTemplateReaderService readerService); + public abstract void convertTopologyTemplate(@NotNull ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService); protected void handleMetadataFile(Map csarFiles) { byte[] bytes = csarFiles.remove(TOSCA_META_PATH_FILE_NAME); @@ -78,8 +78,7 @@ public abstract class AbstractToscaConverter implements ToscaConverter { } } - protected void handleDefinitionTemplate(String key, Map csarFiles, - GlobalSubstitutionServiceTemplate gsst) { + protected void handleDefinitionTemplate(String key, Map csarFiles, GlobalSubstitutionServiceTemplate gsst) { try { ServiceTemplateReaderService readerService = new ServiceTemplateReaderServiceImpl(csarFiles.get(key)); Object nodeTypes = readerService.getNodeTypes(); @@ -89,9 +88,9 @@ public abstract class AbstractToscaConverter implements ToscaConverter { } gsst.appendDataTypes((Map) readerService.getDataTypes()); } catch (YAMLException ye) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file " + key) - .withCategory(ErrorCategory.APPLICATION).build(), ye); + throw new CoreException( + new ErrorCode.ErrorCodeBuilder().withMessage("Invalid YAML content in file " + key).withCategory(ErrorCategory.APPLICATION).build(), + ye); } } @@ -100,52 +99,39 @@ public abstract class AbstractToscaConverter implements ToscaConverter { if (artifactIndex < 0) { return fileName; } - - int artifactDirectoryIndex = - artifactIndex + CsarFileTypes.Artifacts.name().length() + 1; + int artifactDirectoryIndex = artifactIndex + CsarFileTypes.Artifacts.name().length() + 1; return fileName.substring(artifactDirectoryIndex); } - protected void updateToscaServiceModel(ToscaServiceModel toscaServiceModel, - Map serviceTemplates, + protected void updateToscaServiceModel(ToscaServiceModel toscaServiceModel, Map serviceTemplates, FileContentHandler externalFilesHandler, - GlobalSubstitutionServiceTemplate globalSubstitutionServiceTemplate, - Map csarFiles, String entryDefinitionServiceTemplateName) { - Collection globalServiceTemplates = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.CSAR).values(); + GlobalSubstitutionServiceTemplate globalSubstitutionServiceTemplate, Map csarFiles, + String entryDefinitionServiceTemplateName) { + Collection globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.CSAR).values(); addGlobalServiceTemplates(globalServiceTemplates, serviceTemplates); toscaServiceModel.setServiceTemplates(serviceTemplates); toscaServiceModel.setEntryDefinitionServiceTemplate(entryDefinitionServiceTemplateName); - externalFilesHandler.addFile(TOSCA_META_ORIG_PATH_FILE_NAME, - csarFiles.get(TOSCA_META_ORIG_PATH_FILE_NAME)); + externalFilesHandler.addFile(TOSCA_META_ORIG_PATH_FILE_NAME, csarFiles.get(TOSCA_META_ORIG_PATH_FILE_NAME)); toscaServiceModel.setArtifactFiles(externalFilesHandler); - if (MapUtils.isNotEmpty(globalSubstitutionServiceTemplate.getNode_types())) { - serviceTemplates - .put(GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME, globalSubstitutionServiceTemplate); + serviceTemplates.put(GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME, globalSubstitutionServiceTemplate); } } - private void addGlobalServiceTemplates(Collection globalServiceTemplates, - Map serviceTemplates) { + private void addGlobalServiceTemplates(Collection globalServiceTemplates, Map serviceTemplates) { for (ServiceTemplate serviceTemplate : globalServiceTemplates) { serviceTemplates.put(ToscaUtil.getServiceTemplateFileName(serviceTemplate), serviceTemplate); } } - protected void handleServiceTemplate(String serviceTemplateName, - String fileName, Map csarFiles, + protected void handleServiceTemplate(String serviceTemplateName, String fileName, Map csarFiles, Map serviceTemplates) { final byte[] inputServiceTemplate = getServiceTemplateFromCsar(fileName, csarFiles); Optional serviceTemplate = convertServiceTemplate(fileName, inputServiceTemplate); - serviceTemplate.ifPresent( - serviceTemplateValue -> addServiceTemplate(serviceTemplateName, serviceTemplateValue, - serviceTemplates)); + serviceTemplate.ifPresent(serviceTemplateValue -> addServiceTemplate(serviceTemplateName, serviceTemplateValue, serviceTemplates)); } - private void addServiceTemplate(String serviceTemplateName, - ServiceTemplate serviceTemplate, - Map serviceTemplates) { + private void addServiceTemplate(String serviceTemplateName, ServiceTemplate serviceTemplate, Map serviceTemplates) { serviceTemplates.put(serviceTemplateName, serviceTemplate); } @@ -153,12 +139,10 @@ public abstract class AbstractToscaConverter implements ToscaConverter { return csarFiles.get(fileName); } - private Optional convertServiceTemplate(String serviceTemplateName, - byte[] fileContent) { + private Optional convertServiceTemplate(String serviceTemplateName, byte[] fileContent) { ServiceTemplate serviceTemplate = new ServiceTemplate(); try { - ServiceTemplateReaderService readerService = - new ServiceTemplateReaderServiceImpl(fileContent); + ServiceTemplateReaderService readerService = new ServiceTemplateReaderServiceImpl(fileContent); convertMetadata(serviceTemplateName, serviceTemplate, readerService); convertToscaVersion(serviceTemplate, readerService); convertImports(serviceTemplate); @@ -166,17 +150,13 @@ public abstract class AbstractToscaConverter implements ToscaConverter { convertDataTypes(serviceTemplate, readerService); convertTopologyTemplate(serviceTemplate, readerService); } catch (YAMLException ye) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file" + serviceTemplateName) - .withCategory(ErrorCategory.APPLICATION).build(), ye); + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage("Invalid YAML content in file" + serviceTemplateName) + .withCategory(ErrorCategory.APPLICATION).build(), ye); } - - return Optional.of(serviceTemplate); } - private void convertToscaVersion(ServiceTemplate serviceTemplate, - ServiceTemplateReaderService readerService) { + private void convertToscaVersion(ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { Object toscaVersion = readerService.getToscaVersion(); serviceTemplate.setTosca_definitions_version((String) toscaVersion); } @@ -194,26 +174,20 @@ public abstract class AbstractToscaConverter implements ToscaConverter { Import anImport = new Import(); anImport.setFile(fileName); importMap.put(key, anImport); - return importMap; } - private void convertMetadata(String serviceTemplateName, - ServiceTemplate serviceTemplate, - ServiceTemplateReaderService readerService) { + private void convertMetadata(String serviceTemplateName, ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { Map metadataToConvert = (Map) readerService.getMetadata(); Map finalMetadata = new HashMap<>(); - if (MapUtils.isNotEmpty(metadataToConvert)) { for (Map.Entry metadataEntry : metadataToConvert.entrySet()) { - if (Objects.isNull(metadataEntry.getValue()) || - !(metadataEntry.getValue() instanceof String)) { + if (Objects.isNull(metadataEntry.getValue()) || !(metadataEntry.getValue() instanceof String)) { continue; } finalMetadata.put(metadataEntry.getKey(), (String) metadataEntry.getValue()); } } - finalMetadata.put("template_name", getTemplateNameFromStName(serviceTemplateName)); serviceTemplate.setMetadata(finalMetadata); } @@ -223,27 +197,18 @@ public abstract class AbstractToscaConverter implements ToscaConverter { if (MapUtils.isEmpty(nodeTypes)) { return; } - for (Map.Entry nodeTypeEntry : nodeTypes.entrySet()) { - Optional nodeType = ToscaConverterUtil - .createObjectFromClass(nodeTypeEntry.getKey(), nodeTypeEntry.getValue(), - NodeType.class); - - nodeType.ifPresent(nodeTypeValue -> DataModelUtil - .addNodeType(serviceTemplate, nodeTypeEntry.getKey(), nodeTypeValue)); + Optional nodeType = ToscaConverterUtil.createObjectFromClass(nodeTypeEntry.getKey(), nodeTypeEntry.getValue(), NodeType.class); + nodeType.ifPresent(nodeTypeValue -> DataModelUtil.addNodeType(serviceTemplate, nodeTypeEntry.getKey(), nodeTypeValue)); } } - protected void convertDataTypes(final ServiceTemplate serviceTemplate, - final ServiceTemplateReaderService readerService) { + protected void convertDataTypes(final ServiceTemplate serviceTemplate, final ServiceTemplateReaderService readerService) { try { final Map dataTypes = readerService.getDataTypes(); for (final Map.Entry entry : dataTypes.entrySet()) { - final Optional dataType = - ToscaConverterUtil.createObjectFromClass(entry.getKey(), entry.getValue(), DataType.class); - - dataType.ifPresent( - nodeTypeValue -> DataModelUtil.addDataType(serviceTemplate, entry.getKey(), nodeTypeValue)); + final Optional dataType = ToscaConverterUtil.createObjectFromClass(entry.getKey(), entry.getValue(), DataType.class); + dataType.ifPresent(nodeTypeValue -> DataModelUtil.addDataType(serviceTemplate, entry.getKey(), nodeTypeValue)); } } catch (final Exception ex) { LOGGER.error("Unable to process data types: ", ex); diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaSolConverter.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaSolConverter.java index ee669244ce..fb170e3ece 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaSolConverter.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/AbstractToscaSolConverter.java @@ -19,7 +19,6 @@ * * ============LICENSE_END========================================================= * */ - package org.openecomp.core.impl; import static org.openecomp.core.converter.datatypes.Constants.GLOBAL_ST_NAME; @@ -40,7 +39,6 @@ import org.openecomp.sdc.tosca.csar.OnboardingToscaMetadata; import org.openecomp.sdc.tosca.csar.ToscaMetadata; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; - public abstract class AbstractToscaSolConverter extends AbstractToscaConverter { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractToscaSolConverter.class); @@ -75,21 +73,19 @@ public abstract class AbstractToscaSolConverter extends AbstractToscaConverter { if (isGlobalServiceTemplate(fileEntry.getKey())) { handleServiceTemplate(GLOBAL_ST_NAME, fileEntry.getKey(), csarFiles, serviceTemplates); } else { - artifacts.addFile( - getConcreteArtifactFileName(fileEntry.getKey()), fileEntry.getValue()); + artifacts.addFile(getConcreteArtifactFileName(fileEntry.getKey()), fileEntry.getValue()); } } } } - private void handleImportDefinitions(final String fileName, final Map csarFiles - , final GlobalSubstitutionServiceTemplate gsst) { + private void handleImportDefinitions(final String fileName, final Map csarFiles, final GlobalSubstitutionServiceTemplate gsst) { final ToscaDefinitionImportHandler toscaDefinitionImportHandler = new ToscaDefinitionImportHandler(csarFiles, fileName); if (toscaDefinitionImportHandler.hasError()) { throw new InvalidToscaDefinitionImportException(toscaDefinitionImportHandler.getErrors()); } - final Map handledImportDefinitionFileMap = - toscaDefinitionImportHandler.getHandledImportDefinitionFileMap(); + final Map handledImportDefinitionFileMap = toscaDefinitionImportHandler + .getHandledImportDefinitionFileMap(); handledDefinitionFilesList.addAll(handledImportDefinitionFileMap.keySet()); for (final String file : handledDefinitionFilesList) { handleDefinitionTemplate(file, csarFiles, gsst); @@ -98,8 +94,8 @@ public abstract class AbstractToscaSolConverter extends AbstractToscaConverter { private String getMainServiceDefinitionFileName(FileContentHandler contentHandler) throws IOException { try { - ToscaMetadata toscaMetadata = OnboardingToscaMetadata.parseToscaMetadataFile( - contentHandler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); + ToscaMetadata toscaMetadata = OnboardingToscaMetadata + .parseToscaMetadataFile(contentHandler.getFileContentAsStream(TOSCA_META_PATH_FILE_NAME)); return toscaMetadata.getMetaEntries().get(ENTRY_DEFINITIONS.getName()); } catch (IOException e) { LOGGER.error(e.getMessage(), e); @@ -113,5 +109,4 @@ public abstract class AbstractToscaSolConverter extends AbstractToscaConverter { } return path; } - -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/GlobalSubstitutionServiceTemplate.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/GlobalSubstitutionServiceTemplate.java index 98d8d23751..4907451a06 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/GlobalSubstitutionServiceTemplate.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/GlobalSubstitutionServiceTemplate.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.impl; import static org.openecomp.core.converter.datatypes.Constants.ONAP_INDEX; @@ -35,15 +34,14 @@ import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypes public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { - public static final String GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME = - "GlobalSubstitutionTypesServiceTemplate.yaml"; + public static final String GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME = "GlobalSubstitutionTypesServiceTemplate.yaml"; public static final String TEMPLATE_NAME_PROPERTY = "template_name"; public static final String DEFINITION_VERSION = "tosca_simple_yaml_1_0_0"; public static final String HEAT_INDEX = "openecomp_heat_index"; public static final String HEAT_INDEX_IMPORT_FILE = "openecomp-heat/_index.yml"; public static final String ONAP_INDEX_IMPORT_FILE = "onap/_index.yml"; - // transient needed to avoid being parsed as a YAML String. Used parser is reading fields instead of getters, + // although it ignores static or transient fields. private final transient Map globalServiceTemplates; private final transient Map globalDataTypeMap; @@ -51,12 +49,11 @@ public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { public GlobalSubstitutionServiceTemplate() { super(); init(); - globalServiceTemplates = - GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.CSAR); + globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.CSAR); globalDataTypeMap = loadGlobalDataTypes(); } - public void init() { + public void init() { writeDefinitionSection(); writeMetadataSection(); writeImportsSection(); @@ -73,12 +70,10 @@ public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { if (MapUtils.isEmpty(dataTypeMap)) { return; } - dataTypeMap.entrySet().stream() - .filter(dataTypeEntry -> !isGlobalDataType(dataTypeEntry.getKey())) - .forEach(dataTypeEntry -> { - final Optional dataType = parseDataTypeToYamlObject(dataTypeEntry); - dataType.ifPresent(dataType1 -> getData_types().put(dataTypeEntry.getKey(), dataType1)); - }); + dataTypeMap.entrySet().stream().filter(dataTypeEntry -> !isGlobalDataType(dataTypeEntry.getKey())).forEach(dataTypeEntry -> { + final Optional dataType = parseDataTypeToYamlObject(dataTypeEntry); + dataType.ifPresent(dataType1 -> getData_types().put(dataTypeEntry.getKey(), dataType1)); + }); } private void writeImportsSection() { @@ -94,7 +89,6 @@ public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { stringImportMap.put(ONAP_INDEX, onapDefinitionsImport); } - private void writeMetadataSection() { Map metadata = new HashMap<>(); metadata.put(TEMPLATE_NAME_PROPERTY, "GlobalSubstitutionTypes"); @@ -105,22 +99,18 @@ public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { setTosca_definitions_version(DEFINITION_VERSION); } - private Optional> findNonGlobalTypesNodes(final Map nodes){ + private Optional> findNonGlobalTypesNodes(final Map nodes) { final Map globalNodeTypes = getAllGlobalNodeTypes(); if (MapUtils.isEmpty(globalNodeTypes)) { return Optional.of(nodes); } - final Map nodeTypesToAdd = new HashMap<>(); - - for(Map.Entry nodeTypeEntry : nodes.entrySet()){ - if(!globalNodeTypes.containsKey(nodeTypeEntry.getKey())){ + for (Map.Entry nodeTypeEntry : nodes.entrySet()) { + if (!globalNodeTypes.containsKey(nodeTypeEntry.getKey())) { Optional nodeType = parseNodeTypeToYamlObject(nodeTypeEntry); - nodeType - .ifPresent(nodeTypeValue -> nodeTypesToAdd.put(nodeTypeEntry.getKey(), nodeTypeValue)); + nodeType.ifPresent(nodeTypeValue -> nodeTypesToAdd.put(nodeTypeEntry.getKey(), nodeTypeValue)); } } - return Optional.of(nodeTypesToAdd); } @@ -128,37 +118,30 @@ public class GlobalSubstitutionServiceTemplate extends ServiceTemplate { if (MapUtils.isEmpty(globalDataTypeMap)) { return false; } - return globalDataTypeMap.containsKey(dataType); } private Optional parseNodeTypeToYamlObject(final Entry nodeTypeEntry) { - return ToscaConverterUtil - .createObjectFromClass(nodeTypeEntry.getKey(), nodeTypeEntry.getValue(), NodeType.class); + return ToscaConverterUtil.createObjectFromClass(nodeTypeEntry.getKey(), nodeTypeEntry.getValue(), NodeType.class); } private Optional parseDataTypeToYamlObject(final Entry dataTypeEntry) { - return ToscaConverterUtil - .createObjectFromClass(dataTypeEntry.getKey(), dataTypeEntry.getValue(), DataType.class); + return ToscaConverterUtil.createObjectFromClass(dataTypeEntry.getKey(), dataTypeEntry.getValue(), DataType.class); } private Map loadGlobalDataTypes() { - return globalServiceTemplates.values().stream() - .map(ServiceTemplate::getData_types) - .filter(MapUtils::isNotEmpty) + return globalServiceTemplates.values().stream().map(ServiceTemplate::getData_types).filter(MapUtils::isNotEmpty) .flatMap(stringDataTypeMap -> stringDataTypeMap.entrySet().stream()) .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (dataType, dataType2) -> dataType)); } - private Map getAllGlobalNodeTypes(){ + private Map getAllGlobalNodeTypes() { Map globalNodeTypes = new HashMap<>(); - - for(Map.Entry serviceTemplateEntry : globalServiceTemplates.entrySet()){ - if(isNodesServiceTemplate(serviceTemplateEntry.getKey())){ + for (Map.Entry serviceTemplateEntry : globalServiceTemplates.entrySet()) { + if (isNodesServiceTemplate(serviceTemplateEntry.getKey())) { globalNodeTypes.putAll(serviceTemplateEntry.getValue().getNode_types()); } } - return globalNodeTypes; } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/InvalidToscaDefinitionImportException.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/InvalidToscaDefinitionImportException.java index ac2e5eccc2..0c683fbf85 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/InvalidToscaDefinitionImportException.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/InvalidToscaDefinitionImportException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.impl; import java.util.List; @@ -33,15 +32,15 @@ public class InvalidToscaDefinitionImportException extends RuntimeException { /** * Builds the exception message based on the provided validation error list. - * @param validationErrorList The error list + * + * @param validationErrorList The error list */ public InvalidToscaDefinitionImportException(final List validationErrorList) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("The provided package is invalid as it contains descriptors import errors:\n"); if (CollectionUtils.isNotEmpty(validationErrorList)) { final StringJoiner joiner = new StringJoiner(";\n"); - validationErrorList.forEach( - errorMessage -> joiner.add(String.format("%s: %s", errorMessage.getLevel(), errorMessage.getMessage()))); + validationErrorList.forEach(errorMessage -> joiner.add(String.format("%s: %s", errorMessage.getLevel(), errorMessage.getMessage()))); message = stringBuilder.append(joiner.toString()).toString(); } else { message = stringBuilder.toString(); diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java index 6f50205f44..1d109bb457 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java @@ -13,58 +13,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.impl; +import static org.openecomp.core.converter.datatypes.Constants.GLOBAL_ST_NAME; +import static org.openecomp.core.converter.datatypes.Constants.MAIN_ST_NAME; + +import java.util.HashMap; +import java.util.Map; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.converter.ServiceTemplateReaderService; import org.openecomp.core.converter.datatypes.CsarFileTypes; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import java.util.HashMap; -import java.util.Map; - -import static org.openecomp.core.converter.datatypes.Constants.GLOBAL_ST_NAME; -import static org.openecomp.core.converter.datatypes.Constants.MAIN_ST_NAME; - public class ToscaConverterImpl extends AbstractToscaConverter { - @Override - public ToscaServiceModel convert(FileContentHandler fileContentHandler) { - Map csarFiles = new HashMap<>(fileContentHandler.getFiles()); - ToscaServiceModel toscaServiceModel = new ToscaServiceModel(); - Map serviceTemplates = new HashMap<>(); - FileContentHandler artifacts = new FileContentHandler(); - GlobalSubstitutionServiceTemplate gsst = new GlobalSubstitutionServiceTemplate(); - csarFiles.putAll(fileContentHandler.getFiles()); - for (Map.Entry fileEntry : csarFiles.entrySet()) { - CsarFileTypes fileType = getFileType(fileEntry.getKey()); - switch (fileType) { - case mainServiceTemplate: - handleServiceTemplate(MAIN_ST_NAME, fileEntry.getKey(), csarFiles, serviceTemplates); - break; - - case globalServiceTemplate: - handleServiceTemplate(GLOBAL_ST_NAME, fileEntry.getKey(), csarFiles, serviceTemplates); - break; - - case externalFile: - artifacts.addFile( - getConcreteArtifactFileName(fileEntry.getKey()), fileEntry.getValue()); - break; - - case definitionsFile: - handleDefinitionTemplate(fileEntry.getKey(), csarFiles, gsst); - break; - - default: - break; - } - } - handleMetadataFile(csarFiles); - updateToscaServiceModel(toscaServiceModel, serviceTemplates, artifacts, gsst, csarFiles, MAIN_ST_NAME); - return toscaServiceModel; + @Override + public ToscaServiceModel convert(FileContentHandler fileContentHandler) { + Map csarFiles = new HashMap<>(fileContentHandler.getFiles()); + ToscaServiceModel toscaServiceModel = new ToscaServiceModel(); + Map serviceTemplates = new HashMap<>(); + FileContentHandler artifacts = new FileContentHandler(); + GlobalSubstitutionServiceTemplate gsst = new GlobalSubstitutionServiceTemplate(); + csarFiles.putAll(fileContentHandler.getFiles()); + for (Map.Entry fileEntry : csarFiles.entrySet()) { + CsarFileTypes fileType = getFileType(fileEntry.getKey()); + switch (fileType) { + case mainServiceTemplate: + handleServiceTemplate(MAIN_ST_NAME, fileEntry.getKey(), csarFiles, serviceTemplates); + break; + case globalServiceTemplate: + handleServiceTemplate(GLOBAL_ST_NAME, fileEntry.getKey(), csarFiles, serviceTemplates); + break; + case externalFile: + artifacts.addFile(getConcreteArtifactFileName(fileEntry.getKey()), fileEntry.getValue()); + break; + case definitionsFile: + handleDefinitionTemplate(fileEntry.getKey(), csarFiles, gsst); + break; + default: + break; + } + } + handleMetadataFile(csarFiles); + updateToscaServiceModel(toscaServiceModel, serviceTemplates, artifacts, gsst, csarFiles, MAIN_ST_NAME); + return toscaServiceModel; } @Override diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java index a77c150a91..ffb953c89e 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java @@ -13,65 +13,56 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.impl; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.utils.CommonUtil; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - public class ToscaConverterUtil { - private static final String DEFAULT = "default"; - private static final String DEFAULT_CAPITAL = "Default"; - private static final Set DEFAULT_VALUE_KEYS; + private static final String DEFAULT = "default"; + private static final String DEFAULT_CAPITAL = "Default"; + private static final Set DEFAULT_VALUE_KEYS; - static { - DEFAULT_VALUE_KEYS = - Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet()); - } - - private ToscaConverterUtil() { - // static utility methods only, prevent instantiation - } - - static Optional createObjectFromClass(String objectId, - Object objectCandidate, - Class classToCreate) { - try { - return CommonUtil.createObjectUsingSetters(objectCandidate, classToCreate); - } catch (Exception ex) { - throw new CoreException( - new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId) - .build(), ex); + static { + DEFAULT_VALUE_KEYS = Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet()); } - } - - static Optional getDefaultValue(Object entryValue, - Object objectToAssignDefaultValue) { - if (!(entryValue instanceof Map) - || Objects.isNull(objectToAssignDefaultValue)) { - return Optional.empty(); + private ToscaConverterUtil() { + // static utility methods only, prevent instantiation } - return Optional.ofNullable(getDefaultParameterValue((Map) entryValue)); - } - - private static Object getDefaultParameterValue(Map entryValue) { - Object defaultValue = null; - Set keys = new HashSet<>(entryValue.keySet()); - keys.retainAll(DEFAULT_VALUE_KEYS); + static Optional createObjectFromClass(String objectId, Object objectCandidate, Class classToCreate) { + try { + return CommonUtil.createObjectUsingSetters(objectCandidate, classToCreate); + } catch (Exception ex) { + throw new CoreException(new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId).build(), ex); + } + } - if (CollectionUtils.isNotEmpty(keys)) { - defaultValue = entryValue.get(keys.iterator().next()); + static Optional getDefaultValue(Object entryValue, Object objectToAssignDefaultValue) { + if (!(entryValue instanceof Map) || Objects.isNull(objectToAssignDefaultValue)) { + return Optional.empty(); + } + return Optional.ofNullable(getDefaultParameterValue((Map) entryValue)); } - return defaultValue; - } + private static Object getDefaultParameterValue(Map entryValue) { + Object defaultValue = null; + Set keys = new HashSet<>(entryValue.keySet()); + keys.retainAll(DEFAULT_VALUE_KEYS); + if (CollectionUtils.isNotEmpty(keys)) { + defaultValue = entryValue.get(keys.iterator().next()); + } + return defaultValue; + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaDefinitionImportHandler.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaDefinitionImportHandler.java index 661cadc738..a48fb36374 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaDefinitionImportHandler.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaDefinitionImportHandler.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.impl; import static org.openecomp.sdc.tosca.csar.CSARConstants.NON_FILE_IMPORT_ATTRIBUTES; @@ -46,9 +45,7 @@ import org.slf4j.LoggerFactory; public class ToscaDefinitionImportHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ToscaDefinitionImportHandler.class); - private final Map fileMap; - /** * Stores all processed files during the import handling */ @@ -59,17 +56,17 @@ public class ToscaDefinitionImportHandler { /** * Reads the provided package structure starting from a main definition yaml file. - * @param fileStructureMap The package structure with file path and respective file byte - * @param mainDefinitionFilePath The main descriptor yaml file to start the reading + * + * @param fileStructureMap The package structure with file path and respective file byte + * @param mainDefinitionFilePath The main descriptor yaml file to start the reading */ - public ToscaDefinitionImportHandler(final Map fileStructureMap, - final String mainDefinitionFilePath) { + public ToscaDefinitionImportHandler(final Map fileStructureMap, final String mainDefinitionFilePath) { this.fileMap = fileStructureMap; readImportsFromMainDefinition(mainDefinitionFilePath); } private void readImportsFromMainDefinition(final String mainDefinitionFilePath) { - if(!checkMainDefinitionExists(mainDefinitionFilePath)) { + if (!checkMainDefinitionExists(mainDefinitionFilePath)) { return; } final ServiceTemplateReaderService readerService = parseToServiceTemplate(mainDefinitionFilePath).orElse(null); @@ -90,19 +87,16 @@ public class ToscaDefinitionImportHandler { return Optional.of(new ServiceTemplateReaderServiceImpl(fileMap.get(definitionFile))); } catch (final Exception ex) { LOGGER.debug("Could not parse '{}' to a ServiceTemplateReader", definitionFile, ex); - reportError(ErrorLevel.ERROR, - String.format(Messages.INVALID_YAML_FORMAT.getErrorMessage(), ex.getMessage())); + reportError(ErrorLevel.ERROR, String.format(Messages.INVALID_YAML_FORMAT.getErrorMessage(), ex.getMessage())); } - return Optional.empty(); } /** - * Reads and validates the descriptor imports recursively. - * Starts from the provided descriptor and goes until the end of the import tree. + * Reads and validates the descriptor imports recursively. Starts from the provided descriptor and goes until the end of the import tree. * Processes each file just once. * - * @param fileName the descriptor file path + * @param fileName the descriptor file path */ private void handleImports(final String fileName) { currentFile = fileName; @@ -113,14 +107,11 @@ public class ToscaDefinitionImportHandler { if (readerService == null) { return; } - handledImportDefinitionFileMap.put(fileName, readerService); final List imports = readerService.getImports(); final List extractImportFiles = extractFileImports(imports); - extractImportFiles.stream() - .map(importedFile -> resolveImportPath(FilenameUtils.getPath(fileName), importedFile)) - .filter(resolvedPath -> !handledImportDefinitionFileMap.containsKey(resolvedPath)) - .forEach(this::handleImports); + extractImportFiles.stream().map(importedFile -> resolveImportPath(FilenameUtils.getPath(fileName), importedFile)) + .filter(resolvedPath -> !handledImportDefinitionFileMap.containsKey(resolvedPath)).forEach(this::handleImports); } /** @@ -133,22 +124,19 @@ public class ToscaDefinitionImportHandler { * - yetAnotherDescriptor: * yetAnotherDescriptor: ../Definitions/yetAnotherDescriptor.yaml * - * @param imports the import statements - * @return - * The list of import file paths found + * + * @param imports the import statements + * @return The list of import file paths found */ private List extractFileImports(final List imports) { final List importedFileList = new ArrayList<>(); imports.forEach(importObject -> importedFileList.addAll(readImportStatement(importObject))); - return importedFileList; } /** - * Reads an import statement which can be a value, a [key:value] or a [key:[key:value]]. - * Ignores entries which contains the same keys as - * {@link org.openecomp.sdc.tosca.csar.CSARConstants#NON_FILE_IMPORT_ATTRIBUTES}. - * Reports invalid import statements. + * Reads an import statement which can be a value, a [key:value] or a [key:[key:value]]. Ignores entries which contains the same keys as {@link + * org.openecomp.sdc.tosca.csar.CSARConstants#NON_FILE_IMPORT_ATTRIBUTES}. Reports invalid import statements. *
                * example of yaml imports statements:
                * - /Artifacts/anImportedDescriptor.yaml
          @@ -156,9 +144,9 @@ public class ToscaDefinitionImportHandler {
                * - yetAnotherDescriptor:
                *     yetAnotherDescriptor: ../Definitions/yetAnotherDescriptor.yaml
                * 
          - * @param importObject the object representing the yaml import statement - * @return - * The list of import file paths found + * + * @param importObject the object representing the yaml import statement + * @return The list of import file paths found */ private List readImportStatement(final Object importObject) { final List importedFileList = new ArrayList<>(); @@ -172,43 +160,34 @@ public class ToscaDefinitionImportHandler { } } } else { - reportError(ErrorLevel.ERROR, - String.format(Messages.INVALID_IMPORT_STATEMENT.getErrorMessage(), currentFile, importObject)); + reportError(ErrorLevel.ERROR, String.format(Messages.INVALID_IMPORT_STATEMENT.getErrorMessage(), currentFile, importObject)); } - return importedFileList; } /** * Given a directory path, resolves the import path. - * @param directoryPath A directory path to resolve the import path - * @param importPath An import statement path - * @return - * The resolved path of the import, using as base the directory path + * + * @param directoryPath A directory path to resolve the import path + * @param importPath An import statement path + * @return The resolved path of the import, using as base the directory path */ private String resolveImportPath(final String directoryPath, final String importPath) { final String fixedParentDir; if (StringUtils.isEmpty(directoryPath)) { fixedParentDir = "/"; } else { - fixedParentDir = String.format("%s%s%s", - directoryPath.startsWith("/") ? "" : "/" - , directoryPath - , directoryPath.endsWith("/") ? "" : "/"); + fixedParentDir = String.format("%s%s%s", directoryPath.startsWith("/") ? "" : "/", directoryPath, directoryPath.endsWith("/") ? "" : "/"); } - final URI parentDirUri = URI.create(fixedParentDir); - String resolvedImportPath = parentDirUri.resolve(importPath).toString(); if (resolvedImportPath.contains("../")) { - reportError(ErrorLevel.ERROR, - Messages.INVALID_IMPORT_STATEMENT.formatMessage(currentFile, importPath)); + reportError(ErrorLevel.ERROR, Messages.INVALID_IMPORT_STATEMENT.formatMessage(currentFile, importPath)); return null; } if (resolvedImportPath.startsWith("/")) { resolvedImportPath = resolvedImportPath.substring(1); } - return resolvedImportPath; } @@ -221,28 +200,25 @@ public class ToscaDefinitionImportHandler { } /** - * Checks if the given file path exists inside the file structure. - * Reports an error if the file was not found. + * Checks if the given file path exists inside the file structure. Reports an error if the file was not found. * - * @param filePath file path to check inside the file structure - * @param errorMsg the error message to report - * @return - * {@code true} if the file exists, {@code false} otherwise + * @param filePath file path to check inside the file structure + * @param errorMsg the error message to report + * @return {@code true} if the file exists, {@code false} otherwise */ private boolean checkFileExists(final String filePath, final String errorMsg) { if (!fileMap.containsKey(filePath)) { reportError(ErrorLevel.ERROR, errorMsg); return false; } - return true; } /** * Adds an error to the validation error list. * - * @param errorLevel the error level - * @param errorMessage the error message + * @param errorLevel the error level + * @param errorMessage the error message */ private void reportError(final ErrorLevel errorLevel, final String errorMessage) { validationErrorList.add(new ErrorMessage(errorLevel, errorMessage)); @@ -250,8 +226,8 @@ public class ToscaDefinitionImportHandler { /** * Gets the list of errors. - * @return - * The import validation errors detected + * + * @return The import validation errors detected */ public List getErrors() { return validationErrorList; @@ -259,8 +235,8 @@ public class ToscaDefinitionImportHandler { /** * Checks if the handler detected a import error. - * @return - * {@code true} if the handler detected any error, {@code false} otherwise. + * + * @return {@code true} if the handler detected any error, {@code false} otherwise. */ public boolean hasError() { return !validationErrorList.isEmpty(); diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolConverterVnf.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolConverterVnf.java index 7d2a38f4f0..e43ed5383a 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolConverterVnf.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolConverterVnf.java @@ -19,7 +19,6 @@ * * ============LICENSE_END========================================================= * */ - package org.openecomp.core.impl; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -31,5 +30,4 @@ public class ToscaSolConverterVnf extends AbstractToscaSolConverter { public void convertTopologyTemplate(ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { new VnfTopologyTemplateConverter().convertTopologyTemplate(serviceTemplate, readerService); } - } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolModelDrivenConverterPnf.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolModelDrivenConverterPnf.java index b861980f24..425c57aeb9 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolModelDrivenConverterPnf.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaSolModelDrivenConverterPnf.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.impl; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; @@ -29,22 +28,19 @@ public class ToscaSolModelDrivenConverterPnf extends AbstractToscaSolConverter { /** * Calls the model driven engine to parse the onboarding PNF descriptor + * * @param serviceTemplate * @param readerService */ @Override - public void convertTopologyTemplate(final ServiceTemplate serviceTemplate, - final ServiceTemplateReaderService readerService) { - final PnfdTransformationEngine pnfdTransformationEngine = - new PnfdNodeTemplateTransformationEngine(readerService, serviceTemplate); + public void convertTopologyTemplate(final ServiceTemplate serviceTemplate, final ServiceTemplateReaderService readerService) { + final PnfdTransformationEngine pnfdTransformationEngine = new PnfdNodeTemplateTransformationEngine(readerService, serviceTemplate); pnfdTransformationEngine.transform(); } @Override - protected void convertNodeTypes(final ServiceTemplate serviceTemplate, - final ServiceTemplateReaderService readerService) { - final PnfdTransformationEngine pnfdTransformationEngine = - new PnfdNodeTypeTransformationEngine(readerService, serviceTemplate); + protected void convertNodeTypes(final ServiceTemplate serviceTemplate, final ServiceTemplateReaderService readerService) { + final PnfdTransformationEngine pnfdTransformationEngine = new PnfdNodeTypeTransformationEngine(readerService, serviceTemplate); pnfdTransformationEngine.transform(); } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/VnfTopologyTemplateConverter.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/VnfTopologyTemplateConverter.java index dd7e11ab2b..ec7e493464 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/VnfTopologyTemplateConverter.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/VnfTopologyTemplateConverter.java @@ -19,9 +19,20 @@ * * ============LICENSE_END========================================================= * */ - package org.openecomp.core.impl; +import static org.openecomp.core.converter.datatypes.Constants.CAPABILITIES; +import static org.openecomp.core.converter.datatypes.Constants.INPUTS; +import static org.openecomp.core.converter.datatypes.Constants.NODE_FILTER; +import static org.openecomp.core.converter.datatypes.Constants.NODE_TYPE; +import static org.openecomp.core.converter.datatypes.Constants.OUTPUTS; +import static org.openecomp.core.converter.datatypes.Constants.REQUIREMENTS; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections.MapUtils; import org.onap.sdc.tosca.datatypes.model.ArtifactDefinition; import org.onap.sdc.tosca.datatypes.model.CapabilityAssignment; @@ -39,19 +50,6 @@ import org.openecomp.core.converter.errors.SubstitutionMappingsConverterErrorBui import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.tosca.services.DataModelUtil; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -import static org.openecomp.core.converter.datatypes.Constants.CAPABILITIES; -import static org.openecomp.core.converter.datatypes.Constants.INPUTS; -import static org.openecomp.core.converter.datatypes.Constants.NODE_FILTER; -import static org.openecomp.core.converter.datatypes.Constants.NODE_TYPE; -import static org.openecomp.core.converter.datatypes.Constants.OUTPUTS; -import static org.openecomp.core.converter.datatypes.Constants.REQUIREMENTS; - public class VnfTopologyTemplateConverter { public void convertTopologyTemplate(ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { @@ -72,28 +70,23 @@ public class VnfTopologyTemplateConverter { addInputsOrOutputsToServiceTemplate(serviceTemplate, outputs, Constants.OUTPUTS); } - private void addInputsOrOutputsToServiceTemplate(ServiceTemplate serviceTemplate, Map mapToConvert, - String inputsOrOutputs) { + private void addInputsOrOutputsToServiceTemplate(ServiceTemplate serviceTemplate, Map mapToConvert, String inputsOrOutputs) { if (MapUtils.isEmpty(mapToConvert)) { return; } - for (Map.Entry entry : mapToConvert.entrySet()) { - Optional parameterDefinition = ToscaConverterUtil.createObjectFromClass(entry.getKey(), - entry.getValue(), ParameterDefinition.class); - + Optional parameterDefinition = ToscaConverterUtil + .createObjectFromClass(entry.getKey(), entry.getValue(), ParameterDefinition.class); parameterDefinition.ifPresent(parameterDefinitionValue -> { - Optional defaultValue = - ToscaConverterUtil.getDefaultValue(entry.getValue(), parameterDefinition.get()); + Optional defaultValue = ToscaConverterUtil.getDefaultValue(entry.getValue(), parameterDefinition.get()); defaultValue.ifPresent(parameterDefinitionValue::set_default); - addToServiceTemplateAccordingToSection(serviceTemplate, inputsOrOutputs, entry.getKey(), - parameterDefinition.get()); + addToServiceTemplateAccordingToSection(serviceTemplate, inputsOrOutputs, entry.getKey(), parameterDefinition.get()); }); } } - private void addToServiceTemplateAccordingToSection(ServiceTemplate serviceTemplate, String inputsOrOutputs, - String parameterId, ParameterDefinition parameterDefinition) { + private void addToServiceTemplateAccordingToSection(ServiceTemplate serviceTemplate, String inputsOrOutputs, String parameterId, + ParameterDefinition parameterDefinition) { if (inputsOrOutputs.equals(INPUTS)) { DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); } else if (inputsOrOutputs.equals(OUTPUTS)) { @@ -106,7 +99,6 @@ public class VnfTopologyTemplateConverter { if (MapUtils.isEmpty(nodeTemplates)) { return; } - for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) { NodeTemplate nodeTemplate = convertNodeTemplate(nodeTemplateEntry.getValue()); DataModelUtil.addNodeTemplate(serviceTemplate, nodeTemplateEntry.getKey(), nodeTemplate); @@ -115,7 +107,6 @@ public class VnfTopologyTemplateConverter { private NodeTemplate convertNodeTemplate(Object candidateNodeTemplate) { NodeTemplate nodeTemplate = new NodeTemplate(); - Map nodeTemplateAsMap = (Map) candidateNodeTemplate; nodeTemplate.setArtifacts((Map) nodeTemplateAsMap.get("artifacts")); nodeTemplate.setAttributes((Map) nodeTemplateAsMap.get("attributes")); @@ -128,7 +119,6 @@ public class VnfTopologyTemplateConverter { nodeTemplate.setRequirements((List>) nodeTemplateAsMap.get("requirements")); nodeTemplate.setType((String) nodeTemplateAsMap.get("type")); nodeTemplate.setCapabilities(convertCapabilities((Map) nodeTemplateAsMap.get("capabilities"))); - return nodeTemplate; } @@ -136,23 +126,17 @@ public class VnfTopologyTemplateConverter { if (MapUtils.isEmpty(capabilities)) { return null; } - Map convertedCapabilities = new HashMap<>(); for (Map.Entry capabilityAssignmentEntry : capabilities.entrySet()) { - Optional capabilityAssignment = ToscaConverterUtil.createObjectFromClass( - capabilityAssignmentEntry.getKey(), capabilityAssignmentEntry.getValue(), - CapabilityAssignment.class); - - capabilityAssignment.ifPresent(capabilityAssignmentValue -> convertedCapabilities - .put(capabilityAssignmentEntry.getKey(), - capabilityAssignmentValue)); - + Optional capabilityAssignment = ToscaConverterUtil + .createObjectFromClass(capabilityAssignmentEntry.getKey(), capabilityAssignmentEntry.getValue(), CapabilityAssignment.class); + capabilityAssignment + .ifPresent(capabilityAssignmentValue -> convertedCapabilities.put(capabilityAssignmentEntry.getKey(), capabilityAssignmentValue)); } return convertedCapabilities; } - private void convertSubstitutionMappings(ServiceTemplate serviceTemplate, - ServiceTemplateReaderService readerService) { + private void convertSubstitutionMappings(ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { Map substitutionMappings = readerService.getSubstitutionMappings(); if (MapUtils.isEmpty(substitutionMappings)) { return; @@ -163,53 +147,41 @@ public class VnfTopologyTemplateConverter { private SubstitutionMapping convertSubstitutionMappings(Map substitutionMappings) { SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - substitutionMapping.setNode_type((String) substitutionMappings.get(NODE_TYPE)); - substitutionMapping.setCapabilities( - convertSubstitutionMappingsSections(CAPABILITIES, substitutionMappings.get(CAPABILITIES))); - substitutionMapping.setRequirements( - convertSubstitutionMappingsSections(REQUIREMENTS, substitutionMappings.get(REQUIREMENTS))); + substitutionMapping.setCapabilities(convertSubstitutionMappingsSections(CAPABILITIES, substitutionMappings.get(CAPABILITIES))); + substitutionMapping.setRequirements(convertSubstitutionMappingsSections(REQUIREMENTS, substitutionMappings.get(REQUIREMENTS))); substitutionMapping.setSubstitution_filter((NodeFilter) substitutionMappings.get(NODE_FILTER)); - return substitutionMapping; } private Map> convertSubstitutionMappingsSections(String sectionName, Object sectionToConvert) { - if (Objects.isNull(sectionToConvert)) { return null; } - if (!(sectionToConvert instanceof Map)) { - throw new CoreException(new SubstitutionMappingsConverterErrorBuilder(sectionName, - sectionToConvert.getClass().getSimpleName()).build()); + throw new CoreException(new SubstitutionMappingsConverterErrorBuilder(sectionName, sectionToConvert.getClass().getSimpleName()).build()); } - return convertSection(sectionToConvert); } private Map> convertSection(Object sectionToConvert) { - Map sectionAsMap = (Map) sectionToConvert; Map> convertedSection = new HashMap<>(); - if (MapUtils.isEmpty(sectionAsMap)) { return null; } - for (Map.Entry entry : sectionAsMap.entrySet()) { if (entry.getValue() instanceof List) { convertedSection.put(entry.getKey(), (List) entry.getValue()); } } - return convertedSection; } private void convertPolicies(ServiceTemplate serviceTemplate, ServiceTemplateReaderService readerService) { List policiesList = readerService.getPolicies(); - policiesList.forEach(policiesListItem -> ((Map) policiesListItem).forEach((key, value) -> - DataModelUtil.addPolicyDefinition(serviceTemplate, key, convertPolicy(value)))); + policiesList.forEach(policiesListItem -> ((Map) policiesListItem) + .forEach((key, value) -> DataModelUtil.addPolicyDefinition(serviceTemplate, key, convertPolicy(value)))); } private PolicyDefinition convertPolicy(Object policyCandidate) { @@ -221,7 +193,6 @@ public class VnfTopologyTemplateConverter { policyDefinition.setProperties((Map) policy.get("properties")); policyDefinition.setTargets((List) policy.get("targets")); policyDefinition.setTriggers((Map) policy.get("triggers")); - return policyDefinition; } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/factory/ToscaConverterFactoryImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/factory/ToscaConverterFactoryImpl.java index d585868365..1e8a83e172 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/factory/ToscaConverterFactoryImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/factory/ToscaConverterFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.impl.factory; import org.openecomp.core.converter.ToscaConverter; @@ -25,8 +24,9 @@ import org.openecomp.core.converter.factory.ToscaConverterFactory; import org.openecomp.core.impl.ToscaConverterImpl; public class ToscaConverterFactoryImpl extends ToscaConverterFactory { - @Override - public ToscaConverter createInterface() { - return new ToscaConverterImpl(); - } + + @Override + public ToscaConverter createInterface() { + return new ToscaConverterImpl(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java index 9cd2d7ea07..421aeb60d2 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java @@ -17,15 +17,14 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.impl.services; -import static org.openecomp.core.converter.datatypes.Constants.POLICIES; import static org.openecomp.core.converter.datatypes.Constants.INPUTS; import static org.openecomp.core.converter.datatypes.Constants.METADATA; import static org.openecomp.core.converter.datatypes.Constants.NODE_TEMPLATES; import static org.openecomp.core.converter.datatypes.Constants.NODE_TYPES; import static org.openecomp.core.converter.datatypes.Constants.OUTPUTS; +import static org.openecomp.core.converter.datatypes.Constants.POLICIES; import static org.openecomp.core.converter.datatypes.Constants.SUBSTITUTION_MAPPINGS; import static org.openecomp.core.converter.datatypes.Constants.TOPOLOGY_TEMPLATE; import static org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum.DATA_TYPES; @@ -63,8 +62,7 @@ public class ServiceTemplateReaderServiceImpl implements ServiceTemplateReaderSe @Override public List getPolicies() { List policiesList = new ArrayList<>(); - if (Objects.nonNull(this.getTopologyTemplate()) && Objects.nonNull( - ((Map) this.getTopologyTemplate()).get(POLICIES))) { + if (Objects.nonNull(this.getTopologyTemplate()) && Objects.nonNull(((Map) this.getTopologyTemplate()).get(POLICIES))) { policiesList = (List) ((Map) this.getTopologyTemplate()).get(POLICIES); } return policiesList; @@ -112,8 +110,7 @@ public class ServiceTemplateReaderServiceImpl implements ServiceTemplateReaderSe @Override public Map getSubstitutionMappings() { return Objects.isNull(this.getTopologyTemplate()) ? new HashMap<>() - : (Map) ((Map) this.getTopologyTemplate()) - .get(SUBSTITUTION_MAPPINGS); + : (Map) ((Map) this.getTopologyTemplate()).get(SUBSTITUTION_MAPPINGS); } @Override diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AbstractOnboardingManifest.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AbstractOnboardingManifest.java index 372517c5f9..b24804be54 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AbstractOnboardingManifest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AbstractOnboardingManifest.java @@ -15,7 +15,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.csar; import com.google.common.collect.ImmutableList; @@ -106,7 +105,6 @@ abstract class AbstractOnboardingManifest implements Manifest { errors.add(Messages.MANIFEST_EMPTY.getErrorMessage()); return; } - processMetadata(); processBody(); } @@ -133,8 +131,7 @@ abstract class AbstractOnboardingManifest implements Manifest { throw new IOException("Manifest Input Stream cannot be null."); } final ImmutableList.Builder builder = ImmutableList.builder(); - try (final BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(manifestAsStream, StandardCharsets.UTF_8.newDecoder()))) { + try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(manifestAsStream, StandardCharsets.UTF_8.newDecoder()))) { bufferedReader.lines().forEach(builder::add); } return builder.build(); @@ -147,8 +144,7 @@ abstract class AbstractOnboardingManifest implements Manifest { * @return {@code true} if the line is a 'metadata' entry, {@code false} otherwise. */ protected boolean isMetadata(final String line) { - return line.trim() - .equals(ManifestTokenType.METADATA.getToken() + ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR.getToken()); + return line.trim().equals(ManifestTokenType.METADATA.getToken() + ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR.getToken()); } /** @@ -187,7 +183,7 @@ abstract class AbstractOnboardingManifest implements Manifest { * Reports a manifest invalid line error. * * @param lineNumber the line number - * @param line the line + * @param line the line */ protected void reportInvalidLine(final int lineNumber, final String line) { errors.add(Messages.MANIFEST_INVALID_LINE.formatMessage(lineNumber, line)); @@ -197,7 +193,7 @@ abstract class AbstractOnboardingManifest implements Manifest { * Reports a manifest error occurred in the current line. * * @param message The error message - * @param params The message params + * @param params The message params */ protected void reportError(final Messages message, final Object... params) { reportError(currentLineNumber, getCurrentLine().orElse(""), message, params); @@ -207,12 +203,11 @@ abstract class AbstractOnboardingManifest implements Manifest { * Reports a manifest error occurred in the specified line. * * @param lineNumber The line number - * @param line The line - * @param message The error message - * @param params The message params + * @param line The line + * @param message The error message + * @param params The message params */ - protected void reportError(final int lineNumber, final String line, final Messages message, - final Object... params) { + protected void reportError(final int lineNumber, final String line, final Messages message, final Object... params) { errors.add(Messages.MANIFEST_ERROR_WITH_LINE.formatMessage(message.formatMessage(params), lineNumber, line)); } @@ -240,12 +235,10 @@ abstract class AbstractOnboardingManifest implements Manifest { } currentLine = null; } - if (getCurrentLine().isPresent()) { currentLineNumber++; currentLine = null; } - return getCurrentLine(); } @@ -259,8 +252,7 @@ abstract class AbstractOnboardingManifest implements Manifest { } /** - * Reads the current line entry name. The entry name and value must be separated by {@link - * ManifestTokenType#ATTRIBUTE_VALUE_SEPARATOR}. + * Reads the current line entry name. The entry name and value must be separated by {@link ManifestTokenType#ATTRIBUTE_VALUE_SEPARATOR}. * * @return the entry value */ @@ -269,7 +261,6 @@ abstract class AbstractOnboardingManifest implements Manifest { if (line.isPresent()) { return readEntryName(line.get()); } - return Optional.empty(); } @@ -290,13 +281,11 @@ abstract class AbstractOnboardingManifest implements Manifest { if (StringUtils.isEmpty(attribute)) { return Optional.empty(); } - return Optional.of(attribute); } /** - * Reads the current line entry value. The entry name and value must be separated by {@link - * ManifestTokenType#ATTRIBUTE_VALUE_SEPARATOR}. + * Reads the current line entry value. The entry name and value must be separated by {@link ManifestTokenType#ATTRIBUTE_VALUE_SEPARATOR}. * * @return the entry value */ @@ -305,7 +294,6 @@ abstract class AbstractOnboardingManifest implements Manifest { if (line.isPresent()) { return readEntryValue(line.get()); } - return Optional.empty(); } @@ -326,13 +314,11 @@ abstract class AbstractOnboardingManifest implements Manifest { if (StringUtils.isEmpty(value)) { return Optional.empty(); } - return Optional.of(value); } /** - * Adds a entry to the metadata map. Only accepts new entries. If the entry is duplicated a manifest error is - * reported. + * Adds a entry to the metadata map. Only accepts new entries. If the entry is duplicated a manifest error is reported. * * @param entry the metadata entry * @param value the entry value @@ -343,7 +329,6 @@ abstract class AbstractOnboardingManifest implements Manifest { reportError(Messages.MANIFEST_METADATA_DUPLICATED_ENTRY, entry); return false; } - metadata.put(entry, value); return true; } @@ -388,7 +373,6 @@ abstract class AbstractOnboardingManifest implements Manifest { if (MapUtils.isEmpty(sourceAndChecksumMap)) { return Optional.empty(); } - return Optional.of(ImmutableMap.copyOf(sourceAndChecksumMap)); } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AlgorithmDigest.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AlgorithmDigest.java index 8ce0fb650b..409842e946 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AlgorithmDigest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/AlgorithmDigest.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import lombok.AllArgsConstructor; @@ -28,6 +27,7 @@ import lombok.Getter; @Getter @AllArgsConstructor public class AlgorithmDigest { + private final String hashAlgorithm; private final String digest; } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/CSARConstants.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/CSARConstants.java index 845d36cb4c..cd83cc816b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/CSARConstants.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/CSARConstants.java @@ -14,7 +14,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.csar; import static com.google.common.collect.ImmutableSet.of; @@ -23,37 +22,32 @@ import static org.openecomp.sdc.tosca.csar.ManifestTokenType.PNFD_ARCHIVE_VERSIO import static org.openecomp.sdc.tosca.csar.ManifestTokenType.PNFD_NAME; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.PNFD_PROVIDER; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.PNFD_RELEASE_DATE_TIME; +import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNFD_ID; +import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNFM_INFO; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_PACKAGE_VERSION; -import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_SOFTWARE_VERSION; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_PRODUCT_NAME; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_PROVIDER_ID; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_RELEASE_DATE_TIME; -import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNFD_ID; -import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNFM_INFO; +import static org.openecomp.sdc.tosca.csar.ManifestTokenType.VNF_SOFTWARE_VERSION; import com.google.common.collect.ImmutableSet; public class CSARConstants { - public static final ImmutableSet ELIGBLE_FOLDERS = of("Artifacts/","Definitions/", - "Licenses/", "TOSCA-Metadata/"); + public static final ImmutableSet ELIGBLE_FOLDERS = of("Artifacts/", "Definitions/", "Licenses/", "TOSCA-Metadata/"); public static final String ARTIFACTS_FOLDER = "Artifacts"; public static final String MAIN_SERVICE_TEMPLATE_MF_FILE_NAME = "MainServiceTemplate.mf"; public static final String MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME = "MainServiceTemplate.yaml"; - public static final ImmutableSet ELIGIBLE_FILES = - of(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME,MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME); - public static final ImmutableSet MANIFEST_PNF_METADATA = - of(PNFD_PROVIDER.getToken(), PNFD_NAME.getToken(), PNFD_RELEASE_DATE_TIME.getToken(), - PNFD_ARCHIVE_VERSION.getToken()); - public static final ImmutableSet MANIFEST_PNF_METADATA_VERSION_3 = - of(PNFD_PROVIDER.getToken(), PNFD_NAME.getToken(), PNFD_RELEASE_DATE_TIME.getToken(), - PNFD_ARCHIVE_VERSION.getToken(), COMPATIBLE_SPECIFICATION_VERSIONS.getToken()); - public static final ImmutableSet MANIFEST_VNF_METADATA = - of(VNF_PROVIDER_ID.getToken(), VNF_PRODUCT_NAME.getToken(), VNF_RELEASE_DATE_TIME.getToken(), - VNF_PACKAGE_VERSION.getToken()); - public static final ImmutableSet MANIFEST_VNF_METADATA_VERSION_3 = - of(COMPATIBLE_SPECIFICATION_VERSIONS.getToken(), VNFD_ID.getToken(), VNF_PROVIDER_ID.getToken(), VNF_PRODUCT_NAME.getToken(), VNF_RELEASE_DATE_TIME.getToken(), - VNF_PACKAGE_VERSION.getToken(), VNF_SOFTWARE_VERSION.getToken(), VNFM_INFO.getToken()); + public static final ImmutableSet ELIGIBLE_FILES = of(MAIN_SERVICE_TEMPLATE_MF_FILE_NAME, MAIN_SERVICE_TEMPLATE_YAML_FILE_NAME); + public static final ImmutableSet MANIFEST_PNF_METADATA = of(PNFD_PROVIDER.getToken(), PNFD_NAME.getToken(), + PNFD_RELEASE_DATE_TIME.getToken(), PNFD_ARCHIVE_VERSION.getToken()); + public static final ImmutableSet MANIFEST_PNF_METADATA_VERSION_3 = of(PNFD_PROVIDER.getToken(), PNFD_NAME.getToken(), + PNFD_RELEASE_DATE_TIME.getToken(), PNFD_ARCHIVE_VERSION.getToken(), COMPATIBLE_SPECIFICATION_VERSIONS.getToken()); + public static final ImmutableSet MANIFEST_VNF_METADATA = of(VNF_PROVIDER_ID.getToken(), VNF_PRODUCT_NAME.getToken(), + VNF_RELEASE_DATE_TIME.getToken(), VNF_PACKAGE_VERSION.getToken()); + public static final ImmutableSet MANIFEST_VNF_METADATA_VERSION_3 = of(COMPATIBLE_SPECIFICATION_VERSIONS.getToken(), VNFD_ID.getToken(), + VNF_PROVIDER_ID.getToken(), VNF_PRODUCT_NAME.getToken(), VNF_RELEASE_DATE_TIME.getToken(), VNF_PACKAGE_VERSION.getToken(), + VNF_SOFTWARE_VERSION.getToken(), VNFM_INFO.getToken()); public static final int MANIFEST_METADATA_LIMIT = 4; public static final int MANIFEST_VNF_METADATA_LIMIT_VERSION_3 = 8; public static final int MANIFEST_PNF_METADATA_LIMIT_VERSION_3 = 5; @@ -62,13 +56,11 @@ public class CSARConstants { public static final String CSAR_VERSION_1_1 = "1.1"; public static final String ETSI_VERSION_2_6_1 = "2.6.1"; public static final String ETSI_VERSION_2_7_1 = "2.7.1"; - public static final ImmutableSet NON_FILE_IMPORT_ATTRIBUTES = - ImmutableSet.of("repository", "namespace_uri", "namespace_prefix"); + public static final ImmutableSet NON_FILE_IMPORT_ATTRIBUTES = ImmutableSet.of("repository", "namespace_uri", "namespace_prefix"); public static final String TOSCA_TYPE_PNF = "pnf"; public static final String TOSCA_TYPE_VNF = "vnf"; public static final String TOSCA_MANIFEST_FILE_EXT = "mf"; private CSARConstants() { - } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/Manifest.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/Manifest.java index 31b04f0d8b..d87850ac4b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/Manifest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/Manifest.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import java.io.InputStream; @@ -29,44 +28,51 @@ import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; public interface Manifest { /** - * This Method will parse manifest, extracting fields mandatory/non-mandatory, - * if error occurred it's recorded and will be used for deciding if manifest is valid + * This Method will parse manifest, extracting fields mandatory/non-mandatory, if error occurred it's recorded and will be used for deciding if + * manifest is valid + * * @param is manifest file input stream */ void parse(InputStream is); /** * Returns if manifest is valid + * * @return true/false */ boolean isValid(); /** * Metadata section of manifest + * * @return */ Map getMetadata(); /** * Source section of manifest + * * @return */ List getSources(); /** * Validation errors of manifest + * * @return */ List getErrors(); /** * non mano section of manifest sol004 #4.3.7 + * * @return */ Map> getNonManoSources(); /** * Gets the type based on the metadata of manifest file (VF/PNF) + * * @return enum for type values */ Optional getType(); @@ -75,15 +81,15 @@ public interface Manifest { /** * Gets the CMS manifest signature if present in manifest - * @return - * the CMS manifest signature. + * + * @return the CMS manifest signature. */ Optional getCmsSignature(); /** * Gets the Map of source path and it correspondent checksum. - * @return - * The source and checksum map. + * + * @return The source and checksum map. */ Optional> getSourceAndChecksumMap(); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ManifestTokenType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ManifestTokenType.java index 7caa09f954..9b6b34f755 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ManifestTokenType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ManifestTokenType.java @@ -17,13 +17,13 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import java.util.Arrays; import java.util.Optional; public enum ManifestTokenType { + // @formatter:off ALGORITHM("Algorithm"), ATTRIBUTE_VALUE_SEPARATOR(":"), CMS_BEGIN("-----BEGIN CMS-----"), @@ -46,7 +46,7 @@ public enum ManifestTokenType { SIGNATURE("Signature"), CERTIFICATE("Certificate"), COMPATIBLE_SPECIFICATION_VERSIONS("compatible_specification_versions"); - + // @formatter:on private final String token; @@ -54,14 +54,14 @@ public enum ManifestTokenType { this.token = token; } - public String getToken() { - return token; - } - public static Optional parse(final String token) { return Arrays.stream(values()).filter(it -> it.getToken() != null && it.getToken().equals(token)).findFirst(); } + public String getToken() { + return token; + } + public boolean isMetadataEntry() { return isMetadataVnfEntry() || isMetadataPnfEntry(); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ONAPManifestOnboarding.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ONAPManifestOnboarding.java index 02ee12db13..ee6cc5f9f4 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ONAPManifestOnboarding.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ONAPManifestOnboarding.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import com.google.common.collect.ImmutableList; @@ -43,7 +42,6 @@ public class ONAPManifestOnboarding extends AbstractOnboardingManifest { return; } currentLine = readNextNonEmptyLine(); - while (currentLine.isPresent() && continueToProcess) { final String line = currentLine.get(); final String entry = readEntryName(line).orElse(null); @@ -54,7 +52,6 @@ public class ONAPManifestOnboarding extends AbstractOnboardingManifest { if (value == null) { reportInvalidLine(); } - final ManifestTokenType tokenType = ManifestTokenType.parse(entry).orElse(null); if (tokenType == ManifestTokenType.SOURCE) { sources.add(value); @@ -70,5 +67,4 @@ public class ONAPManifestOnboarding extends AbstractOnboardingManifest { protected void processBody() { //no implementation } - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/OnboardingToscaMetadata.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/OnboardingToscaMetadata.java index 20bcf84aa2..bc104335f5 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/OnboardingToscaMetadata.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/OnboardingToscaMetadata.java @@ -17,101 +17,96 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; +import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; +import static org.openecomp.sdc.tosca.csar.ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR; +import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.ENTRY_DEFINITIONS; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import java.util.Optional; -import org.openecomp.sdc.common.errors.Messages; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.error.ErrorMessage; -import java.io.InputStream; import java.io.IOException; -import org.apache.commons.io.IOUtils; - +import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters; -import static org.openecomp.sdc.tosca.csar.ManifestTokenType.ATTRIBUTE_VALUE_SEPARATOR; -import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.ENTRY_DEFINITIONS; +import java.util.Optional; +import org.apache.commons.io.IOUtils; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public class OnboardingToscaMetadata implements ToscaMetadata { - private Map metaEntries; - private List errors; + private Map metaEntries; + private List errors; - private OnboardingToscaMetadata(){ - metaEntries = new HashMap<>(); - errors = new ArrayList<>(); - } - - /** - * Method parses input stream of meta file, only block_0 is parsed, the rest of metadata ignored - * @param st meta file input stream - * @return OnboardingToscaMetadata instance - * @throws IOException - */ - public static ToscaMetadata parseToscaMetadataFile(InputStream st) throws IOException { - if(st == null) { - throw new IOException(Messages.METADATA_PARSER_INTERNAL.getErrorMessage()); + private OnboardingToscaMetadata() { + metaEntries = new HashMap<>(); + errors = new ArrayList<>(); } - OnboardingToscaMetadata meta = new OnboardingToscaMetadata(); - List metadataLines = IOUtils.readLines(st, "utf-8"); - for (String line : metadataLines) { - line = line.trim(); - if (line.isEmpty()) { + + /** + * Method parses input stream of meta file, only block_0 is parsed, the rest of metadata ignored + * + * @param st meta file input stream + * @return OnboardingToscaMetadata instance + * @throws IOException + */ + public static ToscaMetadata parseToscaMetadataFile(InputStream st) throws IOException { + if (st == null) { + throw new IOException(Messages.METADATA_PARSER_INTERNAL.getErrorMessage()); + } + OnboardingToscaMetadata meta = new OnboardingToscaMetadata(); + List metadataLines = IOUtils.readLines(st, "utf-8"); + for (String line : metadataLines) { + line = line.trim(); + if (line.isEmpty()) { + return meta; + } + String[] entry = line.split(ATTRIBUTE_VALUE_SEPARATOR.getToken()); + //No empty keys allowed, no empty values allowed + if (entry.length < 2 || entry[0].isEmpty()) { + meta.errors.add( + new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.METADATA_INVALID_ENTRY_DEFINITIONS.getErrorMessage(), line))); + //want to get all error lines in meta file block_0, no breaking loop + } else { + meta.metaEntries.put(entry[0].trim(), entry[1].trim()); + } + } + if (!meta.metaEntries.containsKey(ENTRY_DEFINITIONS.getName())) { + meta.errors.add(new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters(Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage()))); + } return meta; - } - String[] entry = line.split(ATTRIBUTE_VALUE_SEPARATOR.getToken()); - //No empty keys allowed, no empty values allowed - if (entry.length < 2 || entry[0].isEmpty()) { - meta.errors.add(new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters( - Messages.METADATA_INVALID_ENTRY_DEFINITIONS.getErrorMessage(), line))); - //want to get all error lines in meta file block_0, no breaking loop - } else { - meta.metaEntries.put(entry[0].trim(), entry[1].trim()); - } } - if (!meta.metaEntries.containsKey(ENTRY_DEFINITIONS.getName())) { - meta.errors.add(new ErrorMessage(ErrorLevel.ERROR, getErrorWithParameters( - Messages.METADATA_NO_ENTRY_DEFINITIONS.getErrorMessage()))); + @Override + public boolean isValid() { + return errors.isEmpty(); } - return meta; - } - @Override public boolean isValid(){ - return errors.isEmpty(); - } - - @Override - public List getErrors() { - return ImmutableList.copyOf(errors); - } - - - @Override - public Map getMetaEntries() { - if (!isValid()){ - return Collections.emptyMap(); + @Override + public List getErrors() { + return ImmutableList.copyOf(errors); } - return ImmutableMap.copyOf(metaEntries); - } - @Override - public boolean hasEntry(final String entry) { - return metaEntries.containsKey(entry); + @Override + public Map getMetaEntries() { + if (!isValid()) { + return Collections.emptyMap(); + } + return ImmutableMap.copyOf(metaEntries); + } - } + @Override + public boolean hasEntry(final String entry) { + return metaEntries.containsKey(entry); + } - @Override - public Optional getEntry(final ToscaMetaEntry entry) { - return Optional.ofNullable(metaEntries.get(entry.getName())); - } + @Override + public Optional getEntry(final ToscaMetaEntry entry) { + return Optional.ofNullable(metaEntries.get(entry.getName())); + } } - diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SOL004ManifestOnboarding.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SOL004ManifestOnboarding.java index 97f562979f..0d4deca6c0 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SOL004ManifestOnboarding.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SOL004ManifestOnboarding.java @@ -18,7 +18,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import static org.openecomp.sdc.tosca.csar.CSARConstants.ETSI_VERSION_2_6_1; @@ -27,17 +26,15 @@ import static org.openecomp.sdc.tosca.csar.CSARConstants.MANIFEST_PNF_METADATA_L import static org.openecomp.sdc.tosca.csar.CSARConstants.MANIFEST_VNF_METADATA_LIMIT_VERSION_3; import static org.openecomp.sdc.tosca.csar.ManifestTokenType.COMPATIBLE_SPECIFICATION_VERSIONS; +import com.vdurmont.semver4j.Semver; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.Optional; - import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.common.errors.Messages; -import com.vdurmont.semver4j.Semver; - /** * Processes a SOL004 Manifest. */ @@ -86,7 +83,6 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { getCurrentLine().ifPresent(line -> reportInvalidLine()); break; } - switch (manifestTokenType) { case CMS_BEGIN: readCmsSignature(); @@ -158,7 +154,6 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { if (manifestTokenType != ManifestTokenType.SOURCE) { break; } - final String value = readCurrentEntryValue().orElse(null); if (!StringUtils.isEmpty(value)) { nonManoSourceList.add(value); @@ -166,7 +161,6 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { reportError(Messages.MANIFEST_EMPTY_NON_MANO_SOURCE); break; } - readNextNonEmptyLine(); } return nonManoSourceList; @@ -182,10 +176,9 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { return; } final StringBuilder cmsSignatureBuilder = new StringBuilder(); - cmsSignatureBuilder.append(currentLine).append("\n"); Optional currentLine = readNextNonEmptyLine(); - if(!getCurrentLine().isPresent()) { + if (!getCurrentLine().isPresent()) { return; } while (currentLine.isPresent()) { @@ -196,12 +189,10 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { cmsSignatureBuilder.append(currentLine.get()).append("\n"); currentLine = readNextNonEmptyLine(); } - if (currentLine.isPresent()) { cmsSignature = cmsSignatureBuilder.toString(); readNextNonEmptyLine(); } - if (getCurrentLine().isPresent()) { reportError(Messages.MANIFEST_SIGNATURE_LAST_ENTRY); continueToProcess = false; @@ -237,32 +228,28 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { reportError(Messages.MANIFEST_NO_METADATA); return false; } - String key = metadata.keySet().stream().filter(k -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(k)) - .findFirst().orElse(null); + String key = metadata.keySet().stream().filter(k -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(k)).findFirst().orElse(null); final ManifestTokenType firstManifestEntryTokenType = ManifestTokenType.parse(key).orElse(null); if (firstManifestEntryTokenType == null) { reportError(Messages.MANIFEST_METADATA_INVALID_ENTRY1, key); return false; } for (final Entry manifestEntry : metadata.entrySet()) { - final ManifestTokenType manifestEntryTokenType = ManifestTokenType.parse(manifestEntry.getKey()) - .orElse(null); + final ManifestTokenType manifestEntryTokenType = ManifestTokenType.parse(manifestEntry.getKey()).orElse(null); if (manifestEntryTokenType == null) { reportError(Messages.MANIFEST_METADATA_INVALID_ENTRY1, manifestEntry.getKey()); return false; } - if ((firstManifestEntryTokenType.isMetadataVnfEntry() && !manifestEntryTokenType.isMetadataVnfEntry()) - || (firstManifestEntryTokenType.isMetadataPnfEntry() && !manifestEntryTokenType.isMetadataPnfEntry())) { + if ((firstManifestEntryTokenType.isMetadataVnfEntry() && !manifestEntryTokenType.isMetadataVnfEntry()) || ( + firstManifestEntryTokenType.isMetadataPnfEntry() && !manifestEntryTokenType.isMetadataPnfEntry())) { reportError(Messages.MANIFEST_METADATA_UNEXPECTED_ENTRY_TYPE); return false; } } - if (metadata.entrySet().size() != getMaxAllowedManifestMetaEntries()) { reportError(Messages.MANIFEST_METADATA_DOES_NOT_MATCH_LIMIT, getMaxAllowedManifestMetaEntries()); return false; } - return true; } @@ -278,10 +265,8 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { if (manifestTokenType != ManifestTokenType.SOURCE) { return; } - final String sourceLine = currentLine.get(); final String sourcePath = readEntryValue(sourceLine).orElse(null); - if (sourcePath == null) { reportError(Messages.MANIFEST_EXPECTED_SOURCE_PATH); return; @@ -293,13 +278,12 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { } /** - * Processes entries {@link ManifestTokenType#ALGORITHM} and {@link ManifestTokenType#HASH} of a {@link - * ManifestTokenType#SOURCE} entry. + * Processes entries {@link ManifestTokenType#ALGORITHM} and {@link ManifestTokenType#HASH} of a {@link ManifestTokenType#SOURCE} entry. * * @param sourcePath the source path related to the algorithm entry. */ private void readAlgorithmEntry(final String sourcePath) { - Optional currentLine = getCurrentLine(); + Optional currentLine = getCurrentLine(); if (!currentLine.isPresent()) { return; } @@ -319,14 +303,12 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { continueToProcess = false; return; } - currentLine = readNextNonEmptyLine(); if (!currentLine.isPresent() || detectLineEntry().orElse(null) != ManifestTokenType.HASH) { reportError(Messages.MANIFEST_EXPECTED_HASH_ENTRY); continueToProcess = false; return; } - final String hashLine = currentLine.get(); final String hash = readEntryValue(hashLine).orElse(null); if (hash == null) { @@ -339,13 +321,12 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { } /** - * Processes entries {@link ManifestTokenType#SIGNATURE} and {@link ManifestTokenType#CERTIFICATE} of a {@link - * ManifestTokenType#SOURCE} entry. + * Processes entries {@link ManifestTokenType#SIGNATURE} and {@link ManifestTokenType#CERTIFICATE} of a {@link ManifestTokenType#SOURCE} entry. * * @param sourcePath the source path related to the algorithm entry. */ private void readSignatureEntry(final String sourcePath) { - Optional currentLine = getCurrentLine(); + Optional currentLine = getCurrentLine(); if (!currentLine.isPresent()) { return; } @@ -365,13 +346,11 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { continueToProcess = false; return; } - currentLine = readNextNonEmptyLine(); if (!currentLine.isPresent() || detectLineEntry().orElse(null) != ManifestTokenType.CERTIFICATE) { sourceAndSignatureMap.put(sourcePath, new SignatureData(signatureFile, null)); return; } - final String certLine = currentLine.get(); final String certFile = readEntryValue(certLine).orElse(null); if (certFile == null) { @@ -385,23 +364,22 @@ public class SOL004ManifestOnboarding extends AbstractOnboardingManifest { private int getMaxAllowedManifestMetaEntries() { if (maxAllowedMetaEntries == 0) { - boolean isVersion3 = metadata.containsKey(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()) - && !getHighestCompatibleVersion().isLowerThan(ETSI_VERSION_2_7_1); + boolean isVersion3 = + metadata.containsKey(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()) && !getHighestCompatibleVersion().isLowerThan(ETSI_VERSION_2_7_1); //Both PNF and VNF share attribute COMPATIBLE_SPECIFICATION_VERSIONS - if (isVersion3) - maxAllowedMetaEntries = metadata.keySet().stream() - .anyMatch(k -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(k) - && isMetadataEntry(k) && ManifestTokenType.parse(k).get().isMetadataPnfEntry()) - ? MANIFEST_PNF_METADATA_LIMIT_VERSION_3 : MANIFEST_VNF_METADATA_LIMIT_VERSION_3; - else + if (isVersion3) { + maxAllowedMetaEntries = metadata.keySet().stream().anyMatch( + k -> !COMPATIBLE_SPECIFICATION_VERSIONS.getToken().equals(k) && isMetadataEntry(k) && ManifestTokenType.parse(k).get() + .isMetadataPnfEntry()) ? MANIFEST_PNF_METADATA_LIMIT_VERSION_3 : MANIFEST_VNF_METADATA_LIMIT_VERSION_3; + } else { maxAllowedMetaEntries = MAX_ALLOWED_MANIFEST_META_ENTRIES; + } } return maxAllowedMetaEntries; } private Semver getHighestCompatibleVersion() { - return Arrays.asList(metadata.get(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()).split(",")) - .stream().map(Semver::new).max((v1, v2) -> v1.compareTo(v2)) - .orElse(new Semver(ETSI_VERSION_2_6_1)); + return Arrays.asList(metadata.get(COMPATIBLE_SPECIFICATION_VERSIONS.getToken()).split(",")).stream().map(Semver::new) + .max((v1, v2) -> v1.compareTo(v2)).orElse(new Semver(ETSI_VERSION_2_6_1)); } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SignatureData.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SignatureData.java index 74277a627f..a4e04f22db 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SignatureData.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/SignatureData.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import lombok.AllArgsConstructor; @@ -29,6 +28,7 @@ import org.springframework.lang.Nullable; @Getter @AllArgsConstructor public class SignatureData { + private final String signatureFile; @Nullable private final String certificateFile; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetaEntry.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetaEntry.java index 3b669543fd..9219c77bea 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetaEntry.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetaEntry.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * (===========LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; import java.util.Arrays; @@ -30,6 +29,7 @@ import lombok.Getter; @AllArgsConstructor @Getter public enum ToscaMetaEntry { + // @formatter:off TOSCA_META_FILE_VERSION_ENTRY("TOSCA-Meta-File-Version"), CSAR_VERSION_ENTRY("CSAR-Version"), CREATED_BY_ENTRY("Created-By"), @@ -40,6 +40,7 @@ public enum ToscaMetaEntry { ETSI_ENTRY_LICENSES("ETSI-Entry-Licenses"), ETSI_ENTRY_CERTIFICATE("ETSI-Entry-Certificate"), OTHER_DEFINITIONS("Other-Definitions"); + // @formatter:on private final String name; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadata.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadata.java index c02c2f31c6..483afb7710 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadata.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadata.java @@ -17,14 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; -import java.util.Optional; -import org.openecomp.sdc.datatypes.error.ErrorMessage; - import java.util.List; import java.util.Map; +import java.util.Optional; +import org.openecomp.sdc.datatypes.error.ErrorMessage; public interface ToscaMetadata { diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadataFileInfo.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadataFileInfo.java index 9d2a95f992..91a8121d3f 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadataFileInfo.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/csar/ToscaMetadataFileInfo.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.csar; public class ToscaMetadataFileInfo { @@ -25,7 +24,5 @@ public class ToscaMetadataFileInfo { public static final String TOSCA_META_FILE_VERSION_1_0 = "1.0"; private ToscaMetadataFileInfo() { - } - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaArtifactType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaArtifactType.java index cc11144102..f80869630c 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaArtifactType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaArtifactType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,11 +25,7 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaArtifactType { - private static Configuration config = ConfigurationManager.lookup(); - - public static final String ARTIFACT_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_ARTIFACT_TYPE); - public static final String NATIVE_DEPLOYMENT = "tosca.artifacts.Deployment"; - + private static Configuration config = ConfigurationManager.lookup(); + public static final String ARTIFACT_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_ARTIFACT_TYPE); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaCapabilityType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaCapabilityType.java index 8be3433998..4840bc8f4e 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaCapabilityType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaCapabilityType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,11 +25,6 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaCapabilityType { - private static Configuration config = ConfigurationManager.lookup(); - - private static final String CAPABILITY_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_CAPABILITY_TYPE); - //TOSCA native types public static final String NATIVE_ROOT = "tosca.capabilities.Root"; public static final String NATIVE_NODE = "tosca.capabilities.Node"; @@ -43,12 +37,12 @@ public class ToscaCapabilityType { public static final String NATIVE_ATTACHMENT = "tosca.capabilities.Attachment"; public static final String NATIVE_NETWORK_LINKABLE = "tosca.capabilities.network.Linkable"; public static final String NATIVE_NFV_METRIC = "tosca.capabilities.nfv.Metric"; - + private static Configuration config = ConfigurationManager.lookup(); + private static final String CAPABILITY_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_CAPABILITY_TYPE); //Additional types public static final String METRIC = CAPABILITY_PREFIX + "Metric"; public static final String METRIC_CEILOMETER = CAPABILITY_PREFIX + "metric.Ceilometer"; public static final String METRIC_SNMP_TRAP = CAPABILITY_PREFIX + "metric.SnmpTrap"; public static final String METRIC_SNMP_POLLING = CAPABILITY_PREFIX + "metric.SnmpPolling"; public static final String FABRIC_CONFIGURATION = CAPABILITY_PREFIX + "FabricConfiguration"; - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaDataType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaDataType.java index a034b9ad38..48d6a37492 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaDataType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaDataType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,77 +25,54 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaDataType { - private static Configuration config = ConfigurationManager.lookup(); - - private static final String DATA_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_DATA_TYPE); - //TOSCA native types public static final String NATIVE_ROOT = "tosca.datatypes.Root"; public static final String NATIVE_NETWORK_NETWORK_INFO = "tosca.datatypes.network.NetworkInfo"; public static final String NATIVE_NETWORK_PORT_INFO = "tosca.datatypes.network.PortInfo"; - + private static Configuration config = ConfigurationManager.lookup(); + private static final String DATA_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_DATA_TYPE); //Additional types - public static final String NOVA_SERVER_PORT_EXTRA_PROPERTIES = - DATA_TYPE_PREFIX + "heat.novaServer.network.PortExtraProperties"; + public static final String NOVA_SERVER_PORT_EXTRA_PROPERTIES = DATA_TYPE_PREFIX + "heat.novaServer.network.PortExtraProperties"; public static final String NETWORK_ADDRESS_PAIR = DATA_TYPE_PREFIX + "heat.network.AddressPair"; public static final String NEUTRON_PORT_FIXED_IPS = DATA_TYPE_PREFIX + "heat.neutron.port.FixedIps"; public static final String CONTRAIL_NETWORK_RULE = DATA_TYPE_PREFIX + "heat.contrail.network.rule.Rule"; - public static final String CONTRAIL_NETWORK_RULE_LIST = - DATA_TYPE_PREFIX + "heat.contrail.network.rule.RuleList"; - public static final String CONTRAIL_NETWORK_RULE_PORT_PAIRS = - DATA_TYPE_PREFIX + "heat.contrail.network.rule.PortPairs"; - public static final String CONTRAIL_NETWORK_RULE_VIRTUAL_NETWORK = - DATA_TYPE_PREFIX + "heat.contrail.network.rule.VirtualNetwork"; - public static final String CONTRAILV2_NETWORK_RULE = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.Rule"; - public static final String CONTRAILV2_NETWORK_RULE_LIST = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.RuleList"; - public static final String CONTRAILV2_NETWORK_RULE_SRC_PORT_PAIRS = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.SrcPortPairs"; - public static final String CONTRAILV2_NETWORK_RULE_DST_PORT_PAIRS = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.DstPortPairs"; - public static final String CONTRAILV2_NETWORK_RULE_DST_VIRTUAL_NETWORK = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.DstVirtualNetwork"; - public static final String CONTRAILV2_NETWORK_RULE_SRC_VIRTUAL_NETWORK = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.SrcVirtualNetwork"; + public static final String CONTRAIL_NETWORK_RULE_LIST = DATA_TYPE_PREFIX + "heat.contrail.network.rule.RuleList"; + public static final String CONTRAIL_NETWORK_RULE_PORT_PAIRS = DATA_TYPE_PREFIX + "heat.contrail.network.rule.PortPairs"; + public static final String CONTRAIL_NETWORK_RULE_VIRTUAL_NETWORK = DATA_TYPE_PREFIX + "heat.contrail.network.rule.VirtualNetwork"; + public static final String CONTRAILV2_NETWORK_RULE = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.Rule"; + public static final String CONTRAILV2_NETWORK_RULE_LIST = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.RuleList"; + public static final String CONTRAILV2_NETWORK_RULE_SRC_PORT_PAIRS = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.SrcPortPairs"; + public static final String CONTRAILV2_NETWORK_RULE_DST_PORT_PAIRS = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.DstPortPairs"; + public static final String CONTRAILV2_NETWORK_RULE_DST_VIRTUAL_NETWORK = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.DstVirtualNetwork"; + public static final String CONTRAILV2_NETWORK_RULE_SRC_VIRTUAL_NETWORK = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.SrcVirtualNetwork"; public static final String CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_PROPERTIES = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.interface.Properties"; - public static final String CONTRAILV2_NETWORK_RULE_ACTION_LIST = - DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.ActionList"; - public static final String CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.IpamRefData"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.interface.Properties"; + public static final String CONTRAILV2_NETWORK_RULE_ACTION_LIST = DATA_TYPE_PREFIX + "heat.contrailV2.network.rule.ActionList"; + public static final String CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA = DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.IpamRefData"; public static final String CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET_LIST = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.ref.data.IpamSubnetList"; public static final String CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet"; - public static final String CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.RefData"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.ref.data.IpamSubnet"; + public static final String CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA = DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.RefData"; public static final String CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA_SEQUENCE = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.RefDataSequence"; - public static final String NOVA_SERVER_NETWORK_ADDRESS_INFO = - DATA_TYPE_PREFIX + "heat.novaServer.network.AddressInfo"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.network.rule.RefDataSequence"; + public static final String NOVA_SERVER_NETWORK_ADDRESS_INFO = DATA_TYPE_PREFIX + "heat.novaServer.network.AddressInfo"; public static final String NEUTRON_SUBNET = DATA_TYPE_PREFIX + "heat.network.neutron.Subnet"; public static final String NETWORK_ALLOCATION_POOL = DATA_TYPE_PREFIX + "heat.network.AllocationPool"; public static final String NETWORK_HOST_ROUTE = DATA_TYPE_PREFIX + "heat.network.subnet.HostRoute"; - public static final String SUBSTITUTION_FILTERING = - DATA_TYPE_PREFIX + "heat.substitution.SubstitutionFiltering"; - public static final String NEUTRON_SECURITY_RULES_RULE = - DATA_TYPE_PREFIX + "heat.network.neutron.SecurityRules.Rule"; - public static final String CONTRAIL_STATIC_ROUTE = - DATA_TYPE_PREFIX + "heat.network.contrail.port.StaticRoute"; - public static final String CONTRAIL_ADDRESS_PAIR = - DATA_TYPE_PREFIX + "heat.network.contrail.AddressPair"; - public static final String CONTRAIL_INTERFACE_DATA = - DATA_TYPE_PREFIX + "heat.network.contrail.InterfaceData"; + public static final String SUBSTITUTION_FILTERING = DATA_TYPE_PREFIX + "heat.substitution.SubstitutionFiltering"; + public static final String NEUTRON_SECURITY_RULES_RULE = DATA_TYPE_PREFIX + "heat.network.neutron.SecurityRules.Rule"; + public static final String CONTRAIL_STATIC_ROUTE = DATA_TYPE_PREFIX + "heat.network.contrail.port.StaticRoute"; + public static final String CONTRAIL_ADDRESS_PAIR = DATA_TYPE_PREFIX + "heat.network.contrail.AddressPair"; + public static final String CONTRAIL_INTERFACE_DATA = DATA_TYPE_PREFIX + "heat.network.contrail.InterfaceData"; public static final String CONTRAILV2_VIRTUAL_MACHINE_SUB_INTERFACE_PROPERTIES = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.Properties"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.Properties"; public static final String CONTRAILV2_VIRTUAL_MACHINE_SUB_INTERFACE_MAC_ADDRESS = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.MacAddress"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.MacAddress"; public static final String CONTRAILV2_VIRTUAL_MACHINE_SUB_INTERFACE_ADDRESS_PAIRS = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPairs"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPairs"; public static final String CONTRAILV2_VIRTUAL_MACHINE_SUB_INTERFACE_ADDRESS_PAIR = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPair"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPair"; public static final String CONTRAILV2_VIRTUAL_MACHINE_SUB_INTERFACE_ADDRESS_PAIR_IP = - DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPairIp"; + DATA_TYPE_PREFIX + "heat.contrailV2.virtual.machine.subInterface.AddressPairIp"; } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaElementTypes.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaElementTypes.java index 7aa3e04ad7..35edbb35cf 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaElementTypes.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaElementTypes.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,16 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; -public enum ToscaElementTypes { - CAPABILITY_TYPE, - NODE_TYPE, - ARTIFACT_TYPE, - DATA_TYPE, - INTERFACE_TYPE, - RELATIONSHIP_TYPE, - GROUP_TYPE, - POLICY_TYPE -} +public enum ToscaElementTypes {CAPABILITY_TYPE, NODE_TYPE, ARTIFACT_TYPE, DATA_TYPE, INTERFACE_TYPE, RELATIONSHIP_TYPE, GROUP_TYPE, POLICY_TYPE} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java index 04663071b7..729b25d419 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFlatData.java @@ -13,12 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.datatypes; import java.util.ArrayList; import java.util.List; - import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; @@ -30,7 +28,6 @@ public class ToscaFlatData { private Object flatEntity; private ToscaElementTypes elementType; - @Setter(AccessLevel.NONE) private List inheritanceHierarchyType; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFunctions.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFunctions.java index 5dbd05aada..43e061319c 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFunctions.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaFunctions.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import lombok.AllArgsConstructor; @@ -33,30 +32,24 @@ import lombok.Getter; @Getter @AllArgsConstructor public enum ToscaFunctions { - + // @formatter:off // Intrinsic functions, section 4.3 in TOSCA 1.3 CONCAT("concat"), JOIN("join"), // since 1.2 TOKEN("token"), - // Property functions, section 4.4 in TOSCA 1.3 - GET_INPUT("get_input"), - GET_PROPERTY("get_property"), - + GET_INPUT("get_input"), GET_PROPERTY("get_property"), // Attribute functions, section 4.5 in TOSCA 1.3 GET_ATTRIBUTE("get_attribute"), - // Operation functions, section 4.6 in TOSCA 1.3 GET_OPERATION_OUTPUT("get_operation_output"), - // Navigation functions, section 4.7 in TOSCA 1.3 GET_NODES_OF_TYPE("get_nodes_of_type"), - // Artifact functions, section 4.8 in TOSCA 1.3 GET_ARTIFACT("get_artifact"), - // non TOSCA-compliant function GET_POLICY("get_policy"); + // @formatter:of private String functionName; } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaGroupType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaGroupType.java index 92c2fc5402..fa891c09a9 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaGroupType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaGroupType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,14 +25,10 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaGroupType { - private static Configuration config = ConfigurationManager.lookup(); - - private static final String GROUP_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_GROUP_TYPE); - //TOSCA native types public static final String NATIVE_ROOT = "tosca.groups.Root"; - + private static Configuration config = ConfigurationManager.lookup(); + private static final String GROUP_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_GROUP_TYPE); //Additional types public static final String HEAT_STACK = GROUP_TYPE_PREFIX + "heat.HeatStack"; } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaInterfaceType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaInterfaceType.java index 4e74708e42..5db99e7e01 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaInterfaceType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaInterfaceType.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -21,9 +20,8 @@ import org.onap.config.api.ConfigurationManager; public class ToscaInterfaceType { - private static Configuration config = ConfigurationManager.lookup(); - //TOSCA native types public static final String NATIVE_ROOT = " tosca.interfaces.Root"; public static final String NATIVE_LIFECYCLE_STANDARD = "tosca.interfaces.node.lifecycle.Standard"; + private static Configuration config = ConfigurationManager.lookup(); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaNodeType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaNodeType.java index d03aa19c64..a0355f4b4d 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaNodeType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaNodeType.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.datatypes; import lombok.AccessLevel; @@ -25,22 +24,7 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class ToscaNodeType { - private static Configuration config = ConfigurationManager.lookup(); - - public static final String VFC_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_VFC); - public static final String CP_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_CP); - public static final String EXTERNAL_CP_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_EXTERNAL_CP); - public static final String NETWORK_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_NETWORK); - public static final String ABSTRACT_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_ABSTARCT); - public static final String RULE_NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_RULE); - public static final String NODE_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX); + private static final Configuration config = ConfigurationManager.lookup(); //TOSCA native types public static final String NATIVE_COMPUTE = "tosca.nodes.Compute"; @@ -48,58 +32,48 @@ public class ToscaNodeType { public static final String NATIVE_BLOCK_STORAGE = "tosca.nodes.BlockStorage"; public static final String NATIVE_NETWORK = "tosca.nodes.network.Network"; public static final String NATIVE_NETWORK_PORT = "tosca.nodes.network.Port"; - + public static final String ABSTRACT_NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_ABSTARCT); + public static final String NESTED_HEAT_RESOURCE_TYPE_PREFIX = ABSTRACT_NODE_TYPE_PREFIX + "heat."; + public static final String VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX = NESTED_HEAT_RESOURCE_TYPE_PREFIX + "subinterface."; + public static final String COMPUTE_TYPE_PREFIX = "org.openecomp.resource.vfc.compute.nodes.heat"; + public static final String VFC_TYPE_PREFIX = "org.openecomp.resource.vfc.nodes.heat"; + public static final String GROUP_TYPE_PREFIX = "org.openecomp.groups"; + public static final String VFC_INSTANCE_GROUP = ".VfcInstanceGroup"; + public static final String VFC_NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_VFC); //Additional types public static final String NOVA_SERVER = VFC_NODE_TYPE_PREFIX + "heat.nova.Server"; public static final String CINDER_VOLUME = VFC_NODE_TYPE_PREFIX + "heat.cinder.Volume"; public static final String COMPUTE = VFC_NODE_TYPE_PREFIX + "Compute"; public static final String CONTRAIL_COMPUTE = VFC_NODE_TYPE_PREFIX + "heat.contrail.Compute"; - - public static final String NEUTRON_SECURITY_RULES = - RULE_NODE_TYPE_PREFIX + "heat.network.neutron.SecurityRules"; - public static final String CONTRAILV2_NETWORK_RULE = - RULE_NODE_TYPE_PREFIX + "heat.network.contrailV2.NetworkRules"; - public static final String CONTRAIL_NETWORK_RULE = - RULE_NODE_TYPE_PREFIX + "heat.network.contrail.NetworkRules"; - - public static final String NEUTRON_NET = NETWORK_NODE_TYPE_PREFIX + "heat.network.neutron.Net"; - public static final String CONTRAILV2_VIRTUAL_NETWORK = - NETWORK_NODE_TYPE_PREFIX + "heat.network.contrailV2.VirtualNetwork"; - public static final String CONTRAIL_VIRTUAL_NETWORK = - NETWORK_NODE_TYPE_PREFIX + "heat.network.contrail.VirtualNetwork"; - public static final String NETWORK = NETWORK_NODE_TYPE_PREFIX + "network.Network"; - + public static final String CP_NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_CP); public static final String NEUTRON_PORT = CP_NODE_TYPE_PREFIX + "heat.network.neutron.Port"; - public static final String CONTRAILV2_VIRTUAL_MACHINE_INTERFACE = - CP_NODE_TYPE_PREFIX + "heat.contrailV2.VirtualMachineInterface"; + public static final String CONTRAILV2_VIRTUAL_MACHINE_INTERFACE = CP_NODE_TYPE_PREFIX + "heat.contrailV2.VirtualMachineInterface"; public static final String CONTRAIL_PORT = CP_NODE_TYPE_PREFIX + "heat.network.contrail.Port"; public static final String NETWORK_PORT = CP_NODE_TYPE_PREFIX + "network.Port"; - public static final String CONTRAILV2_VLAN_SUB_INTERFACE = CP_NODE_TYPE_PREFIX - + "heat.network.v2.contrailV2.VLANSubInterface"; - public static final String NESTED_HEAT_RESOURCE_TYPE_PREFIX = ABSTRACT_NODE_TYPE_PREFIX + "heat."; - public static final String VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX = - NESTED_HEAT_RESOURCE_TYPE_PREFIX + "subinterface."; + public static final String CONTRAILV2_VLAN_SUB_INTERFACE = CP_NODE_TYPE_PREFIX + "heat.network.v2.contrailV2.VLANSubInterface"; + public static final String EXTERNAL_CP_NODE_TYPE_PREFIX = config + .getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_EXTERNAL_CP); //Port Mirroring external node types public static final String EXTERNAL_CP = EXTERNAL_CP_NODE_TYPE_PREFIX + "extCP"; - public static final String EXTERNAL_CONTRAIL_PORT = EXTERNAL_CP_NODE_TYPE_PREFIX - + "extContrailCP"; - public static final String EXTERNAL_VMI_PORT = EXTERNAL_CP_NODE_TYPE_PREFIX - + "extVirtualMachineInterfaceCP"; + public static final String EXTERNAL_CONTRAIL_PORT = EXTERNAL_CP_NODE_TYPE_PREFIX + "extContrailCP"; + public static final String EXTERNAL_VMI_PORT = EXTERNAL_CP_NODE_TYPE_PREFIX + "extVirtualMachineInterfaceCP"; public static final String EXTERNAL_NEUTRON_PORT = EXTERNAL_CP_NODE_TYPE_PREFIX + "extNeutronCP"; - + public static final String NETWORK_NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_NETWORK); + public static final String NEUTRON_NET = NETWORK_NODE_TYPE_PREFIX + "heat.network.neutron.Net"; + public static final String CONTRAILV2_VIRTUAL_NETWORK = NETWORK_NODE_TYPE_PREFIX + "heat.network.contrailV2.VirtualNetwork"; + public static final String CONTRAIL_VIRTUAL_NETWORK = NETWORK_NODE_TYPE_PREFIX + "heat.network.contrail.VirtualNetwork"; + public static final String NETWORK = NETWORK_NODE_TYPE_PREFIX + "network.Network"; public static final String ABSTRACT_SUBSTITUTE = ABSTRACT_NODE_TYPE_PREFIX + "AbstractSubstitute"; public static final String VFC_ABSTRACT_SUBSTITUTE = ABSTRACT_NODE_TYPE_PREFIX + "VFC"; - public static final String CONTRAIL_ABSTRACT_SUBSTITUTE = - ABSTRACT_NODE_TYPE_PREFIX + "contrail.AbstractSubstitute"; + public static final String CONTRAIL_ABSTRACT_SUBSTITUTE = ABSTRACT_NODE_TYPE_PREFIX + "contrail.AbstractSubstitute"; public static final String COMPLEX_VFC_NODE_TYPE = ABSTRACT_NODE_TYPE_PREFIX + "ComplexVFC"; //Questionnaire to Tosca Types public static final String VNF_CONFIG_NODE_TYPE = ABSTRACT_NODE_TYPE_PREFIX + "VnfConfiguration"; public static final String MULTIFLAVOR_VFC_NODE_TYPE = ABSTRACT_NODE_TYPE_PREFIX + "MultiFlavorVFC"; - public static final String MULTIDEPLOYMENTFLAVOR_NODE_TYPE = ABSTRACT_NODE_TYPE_PREFIX - + "MultiDeploymentFlavor.CVFC"; - public static final String COMPUTE_TYPE_PREFIX = "org.openecomp.resource.vfc.compute.nodes.heat"; - public static final String VFC_TYPE_PREFIX = "org.openecomp.resource.vfc.nodes.heat"; - public static final String GROUP_TYPE_PREFIX = "org.openecomp.groups"; - public static final String VFC_INSTANCE_GROUP = ".VfcInstanceGroup"; + public static final String MULTIDEPLOYMENTFLAVOR_NODE_TYPE = ABSTRACT_NODE_TYPE_PREFIX + "MultiDeploymentFlavor.CVFC"; + public static final String RULE_NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_NODE_TYPE_RULE); + public static final String NEUTRON_SECURITY_RULES = RULE_NODE_TYPE_PREFIX + "heat.network.neutron.SecurityRules"; + public static final String CONTRAILV2_NETWORK_RULE = RULE_NODE_TYPE_PREFIX + "heat.network.contrailV2.NetworkRules"; + public static final String CONTRAIL_NETWORK_RULE = RULE_NODE_TYPE_PREFIX + "heat.network.contrail.NetworkRules"; + public static final String NODE_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX); } - diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaPolicyType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaPolicyType.java index 39383f1ef8..90af85053b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaPolicyType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaPolicyType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,14 +25,10 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaPolicyType { - private static Configuration config = ConfigurationManager.lookup(); - - private static final String POLICY_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_POLICY_TYPE); - //TOSCA native types public static final String NATIVE_PLACEMENT = "tosca.policy.placement"; - + private static Configuration config = ConfigurationManager.lookup(); + private static final String POLICY_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_POLICY_TYPE); //Additional types public static final String PLACEMENT_ANTILOCATE = POLICY_TYPE_PREFIX + "placement.Antilocate"; public static final String PLACEMENT_COLOCATE = POLICY_TYPE_PREFIX + "placement.Colocate"; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaRelationshipType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaRelationshipType.java index 370911b1ad..8d1860d9c1 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaRelationshipType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaRelationshipType.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import org.onap.config.api.Configuration; @@ -26,18 +25,13 @@ import org.openecomp.sdc.tosca.services.ConfigConstants; public class ToscaRelationshipType { - private static Configuration config = ConfigurationManager.lookup(); - - private static final String RELATIONSHIP_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_RELATIONSHIP_TYPE); - public static final String NATIVE_ROOT = "tosca.relationships.Root"; public static final String NATIVE_ATTACHES_TO = "tosca.relationships.AttachesTo"; public static final String NATIVE_DEPENDS_ON = "tosca.relationships.DependsOn"; public static final String NATIVE_NETWORK_LINK_TO = "tosca.relationships.network.LinksTo"; public static final String NATIVE_NETWORK_BINDS_TO = "tosca.relationships.network.BindsTo"; - public static final String CINDER_VOLUME_ATTACHES_TO = - RELATIONSHIP_TYPE_PREFIX + "VolumeAttachesTo"; + private static Configuration config = ConfigurationManager.lookup(); + private static final String RELATIONSHIP_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_RELATIONSHIP_TYPE); + public static final String CINDER_VOLUME_ATTACHES_TO = RELATIONSHIP_TYPE_PREFIX + "VolumeAttachesTo"; public static final String ATTACHES_TO = RELATIONSHIP_TYPE_PREFIX + "AttachesTo"; - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaServiceModel.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaServiceModel.java index bbbcb202ef..90e1d2e863 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaServiceModel.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaServiceModel.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; import java.util.Collections; @@ -49,6 +48,16 @@ public class ToscaServiceModel implements AsdcModel { private Map serviceTemplates; private String entryDefinitionServiceTemplate; + /** + * Gets cloned service model. + * + * @param toscaServiceModel the tosca service model + * @return the cloned service model + */ + public static ToscaServiceModel getClonedServiceModel(ToscaServiceModel toscaServiceModel) { + return ToscaServiceModel.class.cast(DataModelUtil.getClonedObject(toscaServiceModel)); + } + /** * Gets service templates. * @@ -59,26 +68,13 @@ public class ToscaServiceModel implements AsdcModel { } public Optional getServiceTemplate(String serviceTemplateName) { - return MapUtils.isEmpty(this.serviceTemplates) ? Optional.empty() - : Optional.of(this.serviceTemplates.get(serviceTemplateName)); + return MapUtils.isEmpty(this.serviceTemplates) ? Optional.empty() : Optional.of(this.serviceTemplates.get(serviceTemplateName)); } - public void addServiceTemplate(String serviceTemplateName, - ServiceTemplate serviceTemplate) { + public void addServiceTemplate(String serviceTemplateName, ServiceTemplate serviceTemplate) { if (MapUtils.isEmpty(serviceTemplates)) { serviceTemplates = new HashMap<>(); } - serviceTemplates.put(serviceTemplateName, serviceTemplate); } - - /** - * Gets cloned service model. - * - * @param toscaServiceModel the tosca service model - * @return the cloned service model - */ - public static ToscaServiceModel getClonedServiceModel(ToscaServiceModel toscaServiceModel) { - return ToscaServiceModel.class.cast(DataModelUtil.getClonedObject(toscaServiceModel)); - } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaTopologyTemplateElements.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaTopologyTemplateElements.java index ae067cd393..1ac8b67a13 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaTopologyTemplateElements.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/ToscaTopologyTemplateElements.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,14 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes; -public enum ToscaTopologyTemplateElements { - NODE_TEMPLATE, - RELATIONSHIP_TEMPLATE, - GROUP, - POLICY, - WORKFLOW -} - +public enum ToscaTopologyTemplateElements {NODE_TEMPLATE, RELATIONSHIP_TEMPLATE, GROUP, POLICY, WORKFLOW} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/extend/ToscaAnnotationType.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/extend/ToscaAnnotationType.java index c66896d771..3406879858 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/extend/ToscaAnnotationType.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/extend/ToscaAnnotationType.java @@ -13,22 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.datatypes.extend; import org.onap.config.api.Configuration; import org.onap.config.api.ConfigurationManager; import org.openecomp.sdc.tosca.services.ConfigConstants; - public class ToscaAnnotationType { - private static Configuration config = ConfigurationManager.lookup(); - public static final String ANNOTATION_TYPE_PREFIX = - config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_ANNOTATION_TYPE); - - public static final String SOURCE = - ANNOTATION_TYPE_PREFIX + "Source"; - + private static Configuration config = ConfigurationManager.lookup(); + public static final String ANNOTATION_TYPE_PREFIX = config.getAsString(ConfigConstants.NAMESPACE, ConfigConstants.PREFIX_ANNOTATION_TYPE); + public static final String SOURCE = ANNOTATION_TYPE_PREFIX + "Source"; } - diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/model/Old1610ServiceTemplate.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/model/Old1610ServiceTemplate.java index 883aabba6f..90ea0e20c1 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/model/Old1610ServiceTemplate.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/datatypes/model/Old1610ServiceTemplate.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,144 +17,139 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.datatypes.model; -import org.onap.sdc.tosca.datatypes.model.*; - import java.util.Map; +import org.onap.sdc.tosca.datatypes.model.ArtifactType; +import org.onap.sdc.tosca.datatypes.model.CapabilityType; +import org.onap.sdc.tosca.datatypes.model.DataType; +import org.onap.sdc.tosca.datatypes.model.GroupType; +import org.onap.sdc.tosca.datatypes.model.Import; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.PolicyType; +import org.onap.sdc.tosca.datatypes.model.RelationshipType; +import org.onap.sdc.tosca.datatypes.model.TopologyTemplate; /** * Created by Talio on 3/30/2017. */ public class Old1610ServiceTemplate { - private String tosca_definitions_version; - private Map metadata; - private String description; - private Map imports; - private Map artifact_types; - private Map data_types; - private Map capability_types; - private Map interface_types; - private Map relationship_types; - private Map node_types; - private Map group_types; - private Map policy_types; - private TopologyTemplate topology_template; - - public String getTosca_definitions_version() { - return tosca_definitions_version; - } - - public void setTosca_definitions_version(String tosca_definitions_version) { - this.tosca_definitions_version = tosca_definitions_version; - } - - public Map getMetadata() { - return metadata; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - - public Map getImports() { - return this.imports; - } - - public void setImports( - Map imports) { - this.imports = imports; - } - - public Map getArtifact_types() { - return artifact_types; - } - - public void setArtifact_types( - Map artifact_types) { - this.artifact_types = artifact_types; - } - - public Map getData_types() { - return data_types; - } - - public void setData_types( - Map data_types) { - this.data_types = data_types; - } - - public Map getCapability_types() { - return capability_types; - } - - public void setCapability_types( - Map capability_types) { - this.capability_types = capability_types; - } - - public Map getInterface_types() { - return interface_types; - } - - public void setInterface_types(Map interface_types) { - this.interface_types = interface_types; - } - - public Map getRelationship_types() { - return relationship_types; - } - - public void setRelationship_types( - Map relationship_types) { - this.relationship_types = relationship_types; - } - - public Map getNode_types() { - return node_types; - } - - public void setNode_types( - Map node_types) { - this.node_types = node_types; - } - - public Map getGroup_types() { - return group_types; - } - - public void setGroup_types( - Map group_types) { - this.group_types = group_types; - } - - public Map getPolicy_types() { - return policy_types; - } - - public void setPolicy_types( - Map policy_types) { - this.policy_types = policy_types; - } - - public TopologyTemplate getTopology_template() { - return topology_template; - } - - public void setTopology_template( - TopologyTemplate topology_template) { - this.topology_template = topology_template; - } -} + private String tosca_definitions_version; + private Map metadata; + private String description; + private Map imports; + private Map artifact_types; + private Map data_types; + private Map capability_types; + private Map interface_types; + private Map relationship_types; + private Map node_types; + private Map group_types; + private Map policy_types; + private TopologyTemplate topology_template; + + public String getTosca_definitions_version() { + return tosca_definitions_version; + } + + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } + + public Map getMetadata() { + return metadata; + } + + public void setMetadata(Map metadata) { + this.metadata = metadata; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map getImports() { + return this.imports; + } + + public void setImports(Map imports) { + this.imports = imports; + } + + public Map getArtifact_types() { + return artifact_types; + } + + public void setArtifact_types(Map artifact_types) { + this.artifact_types = artifact_types; + } + + public Map getData_types() { + return data_types; + } + + public void setData_types(Map data_types) { + this.data_types = data_types; + } + + public Map getCapability_types() { + return capability_types; + } + + public void setCapability_types(Map capability_types) { + this.capability_types = capability_types; + } + + public Map getInterface_types() { + return interface_types; + } + + public void setInterface_types(Map interface_types) { + this.interface_types = interface_types; + } + + public Map getRelationship_types() { + return relationship_types; + } + + public void setRelationship_types(Map relationship_types) { + this.relationship_types = relationship_types; + } + + public Map getNode_types() { + return node_types; + } + + public void setNode_types(Map node_types) { + this.node_types = node_types; + } + + public Map getGroup_types() { + return group_types; + } + + public void setGroup_types(Map group_types) { + this.group_types = group_types; + } + + public Map getPolicy_types() { + return policy_types; + } + + public void setPolicy_types(Map policy_types) { + this.policy_types = policy_types; + } + + public TopologyTemplate getTopology_template() { + return topology_template; + } + public void setTopology_template(TopologyTemplate topology_template) { + this.topology_template = topology_template; + } +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceObjectErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceObjectErrorBuilder.java index aa5c537397..7e9e843a3a 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceObjectErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceObjectErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,20 +24,16 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class CreateInterfaceObjectErrorBuilder { - private static final String COULD_NOT_CREATE_OBJECT_MSG = - "Could not create %s from %s. Reason - %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + private static final String COULD_NOT_CREATE_OBJECT_MSG = "Could not create %s from %s. Reason - %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public CreateInterfaceObjectErrorBuilder(String interfaceClassName, - String interfaceId, - String reason) { - builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(COULD_NOT_CREATE_OBJECT_MSG, interfaceClassName, interfaceId, reason)); - } + public CreateInterfaceObjectErrorBuilder(String interfaceClassName, String interfaceId, String reason) { + builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(COULD_NOT_CREATE_OBJECT_MSG, interfaceClassName, interfaceId, reason)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceOperationObjectErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceOperationObjectErrorBuilder.java index c22fdbc07f..606763db8b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceOperationObjectErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/CreateInterfaceOperationObjectErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,26 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; public class CreateInterfaceOperationObjectErrorBuilder { - private static final String COULD_NOT_CREATE_OBJECT_MSG = - "Could not create Operation from %s. Reason - %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public CreateInterfaceOperationObjectErrorBuilder(String operationId, - String reason) { - builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(COULD_NOT_CREATE_OBJECT_MSG, operationId, reason)); - } + private static final String COULD_NOT_CREATE_OBJECT_MSG = "Could not create Operation from %s. Reason - %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + public CreateInterfaceOperationObjectErrorBuilder(String operationId, String reason) { + builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(COULD_NOT_CREATE_OBJECT_MSG, operationId, reason)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidAddActionNullEntityErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidAddActionNullEntityErrorBuilder.java index 68d7da1b36..43f76fdab6 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidAddActionNullEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidAddActionNullEntityErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,25 +24,22 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class InvalidAddActionNullEntityErrorBuilder { - private static final String INVALID_ACTION_NULL_ENTITY_ERR_MSG = - "Invalid action, can't add '%s' to '%s', '%s' entity is NULL."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Invalid Action Error builder. - * @param addedData Added data - * @param updatedEntity Updated Entity - */ - public InvalidAddActionNullEntityErrorBuilder(String addedData, String updatedEntity) { - builder.withId(ToscaErrorCodes.TOSCA_INVALID_ADD_ACTION_NULL_ENTITY); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(INVALID_ACTION_NULL_ENTITY_ERR_MSG, addedData, updatedEntity, updatedEntity)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String INVALID_ACTION_NULL_ENTITY_ERR_MSG = "Invalid action, can't add '%s' to '%s', '%s' entity is NULL."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Invalid Action Error builder. + * + * @param addedData Added data + * @param updatedEntity Updated Entity + */ + public InvalidAddActionNullEntityErrorBuilder(String addedData, String updatedEntity) { + builder.withId(ToscaErrorCodes.TOSCA_INVALID_ADD_ACTION_NULL_ENTITY); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_ACTION_NULL_ENTITY_ERR_MSG, addedData, updatedEntity, updatedEntity)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidRequirementAssignmentErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidRequirementAssignmentErrorBuilder.java index 1947ce950b..3f50b28646 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidRequirementAssignmentErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidRequirementAssignmentErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,24 +24,22 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class InvalidRequirementAssignmentErrorBuilder { - private static final String INVALID_REQ_ASSIGNMENT_ERR_ID = "INVALID_REQ_ASSIGNMENT_ERR_ID"; - private static final String INVALID_REQ_ASSIGNMENT_ERR_MSG = - "Invalid Requirement Assignment, Node value is NULL, Requirement ID '%s'."; - - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Invalid Requirement Assignment Error Builder. - * @param requirementId. - */ - public InvalidRequirementAssignmentErrorBuilder(String requirementId) { - builder.withId(INVALID_REQ_ASSIGNMENT_ERR_ID); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_REQ_ASSIGNMENT_ERR_MSG, requirementId)); - } - - public ErrorCode build() { - return builder.build(); - } - + private static final String INVALID_REQ_ASSIGNMENT_ERR_ID = "INVALID_REQ_ASSIGNMENT_ERR_ID"; + private static final String INVALID_REQ_ASSIGNMENT_ERR_MSG = "Invalid Requirement Assignment, Node value is NULL, Requirement ID '%s'."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Invalid Requirement Assignment Error Builder. + * + * @param requirementId. + */ + public InvalidRequirementAssignmentErrorBuilder(String requirementId) { + builder.withId(INVALID_REQ_ASSIGNMENT_ERR_ID); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_REQ_ASSIGNMENT_ERR_MSG, requirementId)); + } + + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaFile.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaFile.java index 1bea2bbce6..d7a8ceb90b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaFile.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaFile.java @@ -17,17 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - public class InvalidToscaFile { - private static final String INVALID_TOSCA_FILE = - "Tosca file '%s' is not following TOSCA spec, can't be parsed. Related error - '%s'"; + private static final String INVALID_TOSCA_FILE = "Tosca file '%s' is not following TOSCA spec, can't be parsed. Related error - '%s'"; private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); /** diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaMetaFile.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaMetaFile.java index 54e22c97ae..5b03ceba43 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaMetaFile.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/InvalidToscaMetaFile.java @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - public class InvalidToscaMetaFile { private static final String INVALID_TOSCA_META_FILE = "Missing data - TOSCA.meta file must include '%s' data."; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaElementTypeNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaElementTypeNotFoundErrorBuilder.java index dd33bf79a2..5b486ea513 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaElementTypeNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaElementTypeNotFoundErrorBuilder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -23,28 +22,28 @@ import org.openecomp.sdc.common.errors.ErrorCode; * The type Tosca data type not found error builder. */ public class ToscaElementTypeNotFoundErrorBuilder { - private static final String ENTRY_NOT_FOUND_MSG = - "Entity Type '%s' or one of its derivedFrom type hierarchy, " - + "is not defined in tosca service model"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca data type not found error builder. - * - * @param elementType element type - */ - public ToscaElementTypeNotFoundErrorBuilder(String elementType) { - builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, elementType)); - } + private static final String ENTRY_NOT_FOUND_MSG = + "Entity Type '%s' or one of its derivedFrom type hierarchy, " + "is not defined in tosca service model"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Tosca data type not found error builder. + * + * @param elementType element type + */ + public ToscaElementTypeNotFoundErrorBuilder(String elementType) { + builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, elementType)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaEntryDefinitionWasNotFound.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaEntryDefinitionWasNotFound.java index bb34d3a485..2b259cc6ce 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaEntryDefinitionWasNotFound.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaEntryDefinitionWasNotFound.java @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - public class ToscaEntryDefinitionWasNotFound { private static final String ENTRY_DEFINITION_WAS_NOT_FOUND = "TOSCA Entry Definition was not found"; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaErrorCodes.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaErrorCodes.java index aec4091e68..eed9742fa8 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaErrorCodes.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaErrorCodes.java @@ -17,28 +17,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; class ToscaErrorCodes { - private ToscaErrorCodes() { - throw new IllegalStateException("Utility class"); - } - - static final String INVALID_SUBSTITUTE_NODE_TEMPLATE = "INVALID_SUBSTITUTE_NODE_TEMPLATE"; - static final String INVALID_SUBSTITUTION_SERVICE_TEMPLATE = - "INVALID_SUBSTITUTION_SERVICE_TEMPLATE"; - static final String TOSCA_ENTRY_NOT_FOUND = "TOSCA_ENTRY_NOT_FOUND"; - static final String MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP = - "MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP"; - static final String TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE = - "TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE"; - static final String TOSCA_INVALID_ADD_ACTION_NULL_ENTITY = "TOSCA_INVALID_ADD_ACTION_NULL_ENTITY"; - static final String INVALID_INTERFACE_VALUE = "INVALID_INTERFACE_VALUE"; - static final String INVALID_TOSCA_FILE = "INVALID_TOSCA_FILE"; - static final String INVALID_TOSCA_META_FILE = "INVALID_TOSCA_META_FILE"; - static final String INVALID_TOSCA_ENTRY_DEF_WAS_NOT_FOUND = "INVALID_TOSCA_ENTRY_DEF_WAS_NOT_FOUND"; - + static final String INVALID_SUBSTITUTE_NODE_TEMPLATE = "INVALID_SUBSTITUTE_NODE_TEMPLATE"; + static final String INVALID_SUBSTITUTION_SERVICE_TEMPLATE = "INVALID_SUBSTITUTION_SERVICE_TEMPLATE"; + static final String TOSCA_ENTRY_NOT_FOUND = "TOSCA_ENTRY_NOT_FOUND"; + static final String MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP = "MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP"; + static final String TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE = "TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE"; + static final String TOSCA_INVALID_ADD_ACTION_NULL_ENTITY = "TOSCA_INVALID_ADD_ACTION_NULL_ENTITY"; + static final String INVALID_INTERFACE_VALUE = "INVALID_INTERFACE_VALUE"; + static final String INVALID_TOSCA_FILE = "INVALID_TOSCA_FILE"; + static final String INVALID_TOSCA_META_FILE = "INVALID_TOSCA_META_FILE"; + static final String INVALID_TOSCA_ENTRY_DEF_WAS_NOT_FOUND = "INVALID_TOSCA_ENTRY_DEF_WAS_NOT_FOUND"; + private ToscaErrorCodes() { + throw new IllegalStateException("Utility class"); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaFileNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaFileNotFoundErrorBuilder.java index b06cd1f625..fa07f61424 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaFileNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaFileNotFoundErrorBuilder.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -23,27 +22,27 @@ import org.openecomp.sdc.common.errors.ErrorCode; * The Tosca file not found error builder. */ public class ToscaFileNotFoundErrorBuilder { - private static final String ENTRY_NOT_FOUND_MSG = - "Tosca file '%s' was not found in tosca service model"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca file not found error builder. - * - * @param fileName the file name - */ - public ToscaFileNotFoundErrorBuilder(String fileName) { - builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, fileName)); - } + private static final String ENTRY_NOT_FOUND_MSG = "Tosca file '%s' was not found in tosca service model"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Tosca file not found error builder. + * + * @param fileName the file name + */ + public ToscaFileNotFoundErrorBuilder(String fileName) { + builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, fileName)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidEntryNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidEntryNotFoundErrorBuilder.java index 7e05d18755..4495eb9c2d 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidEntryNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidEntryNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -27,29 +26,29 @@ import org.openecomp.sdc.common.errors.ErrorCode; * The type Tosca invalid entry not found error builder. */ public class ToscaInvalidEntryNotFoundErrorBuilder { - // - private static final String ENTRY_NOT_FOUND_MSG = - "Invalid Tosca model data, missing '%s' entry for '%s' id %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca invalid entry not found error builder. - * - * @param entryName the entry name - * @param entryId the entry id - */ - public ToscaInvalidEntryNotFoundErrorBuilder(String entryName, String entryId) { - builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, entryName, entryName, entryId)); - } + // + private static final String ENTRY_NOT_FOUND_MSG = "Invalid Tosca model data, missing '%s' entry for '%s' id %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Tosca invalid entry not found error builder. + * + * @param entryName the entry name + * @param entryId the entry id + */ + public ToscaInvalidEntryNotFoundErrorBuilder(String entryName, String entryId) { + builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, entryName, entryName, entryId)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidInterfaceValueErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidInterfaceValueErrorBuilder.java index 5ba8a59d7d..b6c444a1d5 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidInterfaceValueErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidInterfaceValueErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -25,17 +24,16 @@ import org.openecomp.sdc.common.errors.ErrorCode; public class ToscaInvalidInterfaceValueErrorBuilder { - private static final String INVALID_INTERFACE_MSG = - "Cannot create interface object. reason - %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + private static final String INVALID_INTERFACE_MSG = "Cannot create interface object. reason - %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - public ToscaInvalidInterfaceValueErrorBuilder(String reason) { - builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_INTERFACE_MSG, reason)); - } + public ToscaInvalidInterfaceValueErrorBuilder(String reason) { + builder.withId(ToscaErrorCodes.INVALID_INTERFACE_VALUE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_INTERFACE_MSG, reason)); + } - public ErrorCode build() { - return builder.build(); - } + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplateErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplateErrorBuilder.java index bab2e77c75..b41ea13668 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplateErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplateErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,39 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - /** * The type Tosca invalid substitute node template error builder. */ public class ToscaInvalidSubstituteNodeTemplateErrorBuilder { - private static final String INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG = - "Invalid substitute node template, directives with substitutable value must be defined." - + " node template id %s"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca invalid substitute node template error builder. - * - * @param nodeTemplateId the node template id - */ - public ToscaInvalidSubstituteNodeTemplateErrorBuilder(String nodeTemplateId) { - builder.withId(ToscaErrorCodes.TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG, nodeTemplateId)); - } + private static final String INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG = + "Invalid substitute node template, directives with substitutable value must be defined." + " node template id %s"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Tosca invalid substitute node template error builder. + * + * @param nodeTemplateId the node template id + */ + public ToscaInvalidSubstituteNodeTemplateErrorBuilder(String nodeTemplateId) { + builder.withId(ToscaErrorCodes.TOSCA_INVALID_SUBSTITUTE_NODE_TEMPLATE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG, nodeTemplateId)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder.java index 90c681efc9..dac2a7cd99 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,43 +17,39 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.tosca.services.ToscaConstants; - /** * The type Tosca invalid substitute node template properties error builder. */ public class ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder { - private static final String INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG = - "Invalid Substitute Node Template %s, mandatory map property %s with mandatory " - + "key %s must be defined."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + private static final String INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG = + "Invalid Substitute Node Template %s, mandatory map property %s with mandatory " + "key %s must be defined."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca invalid substitute node template properties error builder. - * - * @param nodeTemplateId the node template id - */ - public ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(String nodeTemplateId) { - builder.withId(ToscaErrorCodes.INVALID_SUBSTITUTE_NODE_TEMPLATE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG, nodeTemplateId, - ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, - ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME)); - } + /** + * Instantiates a new Tosca invalid substitute node template properties error builder. + * + * @param nodeTemplateId the node template id + */ + public ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(String nodeTemplateId) { + builder.withId(ToscaErrorCodes.INVALID_SUBSTITUTE_NODE_TEMPLATE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_SUBSTITUTE_NODE_TEMPLATE_MSG, nodeTemplateId, ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, + ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstitutionServiceTemplateErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstitutionServiceTemplateErrorBuilder.java index c240992597..70de61432a 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstitutionServiceTemplateErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaInvalidSubstitutionServiceTemplateErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,41 +17,37 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; - /** * The type Tosca invalid substitution service template error builder. */ public class ToscaInvalidSubstitutionServiceTemplateErrorBuilder { - private static final String INVALID_SUBSTITUTION_SERVICE_TEMPLATE_MSG = - "Invalid Substitution Service Template %s, missing mandatory file 'Node type' " - + "in substitution mapping."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + private static final String INVALID_SUBSTITUTION_SERVICE_TEMPLATE_MSG = + "Invalid Substitution Service Template %s, missing mandatory file 'Node type' " + "in substitution mapping."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca invalid substitution service template error builder. - * - * @param serviceTemplateFileName the service template file name - */ - public ToscaInvalidSubstitutionServiceTemplateErrorBuilder(String serviceTemplateFileName) { - builder.withId(ToscaErrorCodes.INVALID_SUBSTITUTION_SERVICE_TEMPLATE); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage( - String.format(INVALID_SUBSTITUTION_SERVICE_TEMPLATE_MSG, serviceTemplateFileName)); - } + /** + * Instantiates a new Tosca invalid substitution service template error builder. + * + * @param serviceTemplateFileName the service template file name + */ + public ToscaInvalidSubstitutionServiceTemplateErrorBuilder(String serviceTemplateFileName) { + builder.withId(ToscaErrorCodes.INVALID_SUBSTITUTION_SERVICE_TEMPLATE); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(INVALID_SUBSTITUTION_SERVICE_TEMPLATE_MSG, serviceTemplateFileName)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaMissingSubstitutionMappingForReqCapErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaMissingSubstitutionMappingForReqCapErrorBuilder.java index c41e2fa137..2902d209a0 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaMissingSubstitutionMappingForReqCapErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaMissingSubstitutionMappingForReqCapErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -28,50 +27,44 @@ import org.openecomp.sdc.common.errors.ErrorCode; */ public class ToscaMissingSubstitutionMappingForReqCapErrorBuilder { - private static final String MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP_MSG = - "Invalid Substitution, Missing Substitution Mapping for %s with Id %s."; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - - /** - * Instantiates a new Tosca missing substitution mapping for req cap error builder. - * - * @param exposedEntry the exposed entry - * @param id the id - */ - public ToscaMissingSubstitutionMappingForReqCapErrorBuilder(MappingExposedEntry exposedEntry, - String id) { - builder.withId(ToscaErrorCodes.MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String - .format(MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP_MSG, exposedEntry.getDisplayName(), id)); - } + private static final String MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP_MSG = "Invalid Substitution, Missing Substitution Mapping for %s with Id %s."; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Instantiates a new Tosca missing substitution mapping for req cap error builder. + * + * @param exposedEntry the exposed entry + * @param id the id + */ + public ToscaMissingSubstitutionMappingForReqCapErrorBuilder(MappingExposedEntry exposedEntry, String id) { + builder.withId(ToscaErrorCodes.MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(MISSING_SUBSTITUTION_MAPPING_FOR_REQ_CAP_MSG, exposedEntry.getDisplayName(), id)); + } - /** - * The enum Mapping exposed entry. - */ - public enum MappingExposedEntry { + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } - CAPABILITY("Capability"), - REQUIREMENT("Requirement"),; + /** + * The enum Mapping exposed entry. + */ + public enum MappingExposedEntry { + CAPABILITY("Capability"), REQUIREMENT("Requirement"); - private String displayName; + private String displayName; - MappingExposedEntry(String displayName) { - this.displayName = displayName; - } + MappingExposedEntry(String displayName) { + this.displayName = displayName; + } - public String getDisplayName() { - return displayName; + public String getDisplayName() { + return displayName; + } } - - } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaNodeTypeNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaNodeTypeNotFoundErrorBuilder.java index 1a2c124f4f..37a16516a9 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaNodeTypeNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/errors/ToscaNodeTypeNotFoundErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.errors; import org.openecomp.sdc.common.errors.ErrorCategory; @@ -27,28 +26,28 @@ import org.openecomp.sdc.common.errors.ErrorCode; * The type Tosca node type not found error builder. */ public class ToscaNodeTypeNotFoundErrorBuilder { - private static final String ENTRY_NOT_FOUND_MSG = - "NodeType '%s' or one of its derivedFrom node type hierarchy, " - + "is not defined in tosca service model"; - private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); - /** - * Instantiates a new Tosca node type not found error builder. - * - * @param nodeType the node type - */ - public ToscaNodeTypeNotFoundErrorBuilder(String nodeType) { - builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); - builder.withCategory(ErrorCategory.APPLICATION); - builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, nodeType)); - } + private static final String ENTRY_NOT_FOUND_MSG = + "NodeType '%s' or one of its derivedFrom node type hierarchy, " + "is not defined in tosca service model"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Tosca node type not found error builder. + * + * @param nodeType the node type + */ + public ToscaNodeTypeNotFoundErrorBuilder(String nodeType) { + builder.withId(ToscaErrorCodes.TOSCA_ENTRY_NOT_FOUND); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(String.format(ENTRY_NOT_FOUND_MSG, nodeType)); + } - /** - * Build error code. - * - * @return the error code - */ - public ErrorCode build() { - return builder.build(); - } + /** + * Build error code. + * + * @return the error code + */ + public ErrorCode build() { + return builder.build(); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarCreationErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarCreationErrorBuilder.java index 42e38a854a..bc34f1128f 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarCreationErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarCreationErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.exceptions; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -25,16 +24,15 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public class CsarCreationErrorBuilder extends BaseErrorBuilder { - private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = - "Failed to create CSAR file from ToscaServiceModel"; - private static final String ZIP_FILE_CREATION = "ZIP_FILE_CREATION"; + private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = "Failed to create CSAR file from ToscaServiceModel"; + private static final String ZIP_FILE_CREATION = "ZIP_FILE_CREATION"; - /** - * Constructor. - */ - public CsarCreationErrorBuilder() { - getErrorCodeBuilder().withId(ZIP_FILE_CREATION); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(MANDATORY_PROPERTY_IS_MISSING_MSG); - } + /** + * Constructor. + */ + public CsarCreationErrorBuilder() { + getErrorCodeBuilder().withId(ZIP_FILE_CREATION); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(MANDATORY_PROPERTY_IS_MISSING_MSG); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarMissingEntryPointErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarMissingEntryPointErrorBuilder.java index 94dd138d03..b7bfa07369 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarMissingEntryPointErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/CsarMissingEntryPointErrorBuilder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.exceptions; import org.openecomp.sdc.common.errors.BaseErrorBuilder; @@ -25,17 +24,16 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public class CsarMissingEntryPointErrorBuilder extends BaseErrorBuilder { - private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = - "Failed to create CSAR file from ToscaServiceModel,missing mandatory " - + "EntryDefinitionServiceTemplate "; - private static final String ZIP_FILE_CREATION = "ZIP_FILE_CREATION__MISSING_ENTRY_DEFINITION"; + private static final String MANDATORY_PROPERTY_IS_MISSING_MSG = + "Failed to create CSAR file from ToscaServiceModel,missing mandatory " + "EntryDefinitionServiceTemplate "; + private static final String ZIP_FILE_CREATION = "ZIP_FILE_CREATION__MISSING_ENTRY_DEFINITION"; - /** - * Constructor. - */ - public CsarMissingEntryPointErrorBuilder() { - getErrorCodeBuilder().withId(ZIP_FILE_CREATION); - getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); - getErrorCodeBuilder().withMessage(MANDATORY_PROPERTY_IS_MISSING_MSG); - } + /** + * Constructor. + */ + public CsarMissingEntryPointErrorBuilder() { + getErrorCodeBuilder().withId(ZIP_FILE_CREATION); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(MANDATORY_PROPERTY_IS_MISSING_MSG); + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/OnboardingManifestInstantiationException.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/OnboardingManifestInstantiationException.java index c637623926..f3b578265b 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/OnboardingManifestInstantiationException.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/exceptions/OnboardingManifestInstantiationException.java @@ -17,7 +17,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.exceptions; /** @@ -28,4 +27,4 @@ public class OnboardingManifestInstantiationException extends RuntimeException { public OnboardingManifestInstantiationException(String message, Throwable e) { super(message, e); } -} \ No newline at end of file +} diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ConfigConstants.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ConfigConstants.java index 8666da9833..863d396585 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ConfigConstants.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ConfigConstants.java @@ -13,31 +13,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services; public class ConfigConstants { - //namespaces - public static final String NAMESPACE = "ToscaModel"; - - //keys - public static final String PREFIX = "tosca.entity.namespace.prefix"; - public static final String PREFIX_CAPABILITY_TYPE = PREFIX + ".capabilityType"; - public static final String PREFIX_DATA_TYPE = PREFIX + ".dataType"; - public static final String PREFIX_GROUP_TYPE = PREFIX + ".groupType"; - public static final String PREFIX_POLICY_TYPE = PREFIX + ".policyType"; - public static final String PREFIX_ARTIFACT_TYPE = PREFIX + ".artifactType"; - public static final String PREFIX_RELATIONSHIP_TYPE = PREFIX + ".relationshipType"; - public static final String PREFIX_ANNOTATION_TYPE = PREFIX + ".annotationType"; - public static final String PREFIX_NODE_TYPE_VFC = PREFIX + ".nodeType.vfc"; - public static final String PREFIX_NODE_TYPE_NETWORK = PREFIX + ".nodeType.network"; - public static final String PREFIX_NODE_TYPE_CP = PREFIX + ".nodeType.connectionPoint"; - public static final String PREFIX_NODE_TYPE_EXTERNAL_CP = PREFIX + ".nodeType" - + ".external.connectionPoint"; - public static final String PREFIX_NODE_TYPE_ABSTARCT = PREFIX + ".nodeType.abstract"; - public static final String PREFIX_NODE_TYPE_RULE = PREFIX + ".nodeType.rule"; + //namespaces + public static final String NAMESPACE = "ToscaModel"; + //keys + public static final String PREFIX = "tosca.entity.namespace.prefix"; + public static final String PREFIX_CAPABILITY_TYPE = PREFIX + ".capabilityType"; + public static final String PREFIX_DATA_TYPE = PREFIX + ".dataType"; + public static final String PREFIX_GROUP_TYPE = PREFIX + ".groupType"; + public static final String PREFIX_POLICY_TYPE = PREFIX + ".policyType"; + public static final String PREFIX_ARTIFACT_TYPE = PREFIX + ".artifactType"; + public static final String PREFIX_RELATIONSHIP_TYPE = PREFIX + ".relationshipType"; + public static final String PREFIX_ANNOTATION_TYPE = PREFIX + ".annotationType"; + public static final String PREFIX_NODE_TYPE_VFC = PREFIX + ".nodeType.vfc"; + public static final String PREFIX_NODE_TYPE_NETWORK = PREFIX + ".nodeType.network"; + public static final String PREFIX_NODE_TYPE_CP = PREFIX + ".nodeType.connectionPoint"; + public static final String PREFIX_NODE_TYPE_EXTERNAL_CP = PREFIX + ".nodeType" + ".external.connectionPoint"; + public static final String PREFIX_NODE_TYPE_ABSTARCT = PREFIX + ".nodeType.abstract"; + public static final String PREFIX_NODE_TYPE_RULE = PREFIX + ".nodeType.rule"; - private ConfigConstants() { - } + private ConfigConstants() { + } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java index 22b6eb847e..f60e823916 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/DataModelUtil.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services; import java.io.ByteArrayInputStream; @@ -30,7 +29,6 @@ import java.util.ListIterator; import java.util.Map; import java.util.Objects; import java.util.Optional; - import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.collections4.CollectionUtils; @@ -84,13 +82,10 @@ public class DataModelUtil { * @param serviceTemplate the service template * @param substitutionMapping the substitution mapping */ - public static void addSubstitutionMapping(ServiceTemplate serviceTemplate, - SubstitutionMapping substitutionMapping) { + public static void addSubstitutionMapping(ServiceTemplate serviceTemplate, SubstitutionMapping substitutionMapping) { if (serviceTemplate == null) { - throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", SERVICE_TEMPLATE) - .build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping", SERVICE_TEMPLATE).build()); } - if (serviceTemplate.getTopology_template() == null) { serviceTemplate.setTopology_template(new TopologyTemplate()); } @@ -117,15 +112,11 @@ public class DataModelUtil { * @param substitutionMappingRequirementId the substitution mapping requirement id * @param substitutionMappingRequirementList the substitution mapping requirement list */ - public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate, - String substitutionMappingRequirementId, + public static void addSubstitutionMappingReq(ServiceTemplate serviceTemplate, String substitutionMappingRequirementId, List substitutionMappingRequirementList) { if (serviceTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements", SERVICE_TEMPLATE) - .build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Requirements", SERVICE_TEMPLATE).build()); } - if (serviceTemplate.getTopology_template() == null) { serviceTemplate.setTopology_template(new TopologyTemplate()); } @@ -135,9 +126,8 @@ public class DataModelUtil { if (serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() == null) { serviceTemplate.getTopology_template().getSubstitution_mappings().setRequirements(new HashMap<>()); } - serviceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .put(substitutionMappingRequirementId, substitutionMappingRequirementList); + .put(substitutionMappingRequirementId, substitutionMappingRequirementList); } /** @@ -147,14 +137,11 @@ public class DataModelUtil { * @param substitutionMappingCapabilityId the substitution mapping capability id * @param substitutionMappingCapabilityList the substitution mapping capability list */ - public static void addSubstitutionMappingCapability(ServiceTemplate serviceTemplate, - String substitutionMappingCapabilityId, + public static void addSubstitutionMappingCapability(ServiceTemplate serviceTemplate, String substitutionMappingCapabilityId, List substitutionMappingCapabilityList) { if (serviceTemplate == null) { - throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities", - SERVICE_TEMPLATE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Substitution Mapping Capabilities", SERVICE_TEMPLATE).build()); } - if (serviceTemplate.getTopology_template() == null) { serviceTemplate.setTopology_template(new TopologyTemplate()); } @@ -164,9 +151,8 @@ public class DataModelUtil { if (serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() == null) { serviceTemplate.getTopology_template().getSubstitution_mappings().setCapabilities(new HashMap<>()); } - serviceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList); + .putIfAbsent(substitutionMappingCapabilityId, substitutionMappingCapabilityList); } /** @@ -176,11 +162,10 @@ public class DataModelUtil { * @return the service template node templates and empty map if not present */ public static Map getNodeTemplates(ServiceTemplate serviceTemplate) { - if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template()) - || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates())) { + if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template()) || MapUtils + .isEmpty(serviceTemplate.getTopology_template().getNode_templates())) { return new HashMap<>(); } - return serviceTemplate.getTopology_template().getNode_templates(); } @@ -191,11 +176,10 @@ public class DataModelUtil { * @return the service template groups and empty map if not present */ public static Map getGroups(ServiceTemplate serviceTemplate) { - if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template()) - || MapUtils.isEmpty(serviceTemplate.getTopology_template().getGroups())) { + if (Objects.isNull(serviceTemplate) || Objects.isNull(serviceTemplate.getTopology_template()) || MapUtils + .isEmpty(serviceTemplate.getTopology_template().getGroups())) { return new HashMap<>(); } - return serviceTemplate.getTopology_template().getGroups(); } @@ -206,11 +190,9 @@ public class DataModelUtil { * @param nodeTemplateId the node template id * @param nodeTemplate the node template */ - public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId, - NodeTemplate nodeTemplate) { + public static void addNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId, NodeTemplate nodeTemplate) { if (serviceTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Node Template", SERVICE_TEMPLATE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Node Template", SERVICE_TEMPLATE).build()); } TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); if (Objects.isNull(topologyTemplate)) { @@ -233,16 +215,12 @@ public class DataModelUtil { if (MapUtils.isEmpty(capabilities)) { return; } - if (nodeType == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE).build()); } - if (MapUtils.isEmpty(nodeType.getCapabilities())) { nodeType.setCapabilities(new HashMap<>()); } - for (Map.Entry entry : capabilities.entrySet()) { nodeType.getCapabilities().put(entry.getKey(), entry.getValue()); } @@ -258,19 +236,14 @@ public class DataModelUtil { if (MapUtils.isEmpty(capabilities)) { return; } - if (nodeType == null) { - throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE) - .build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Capability Definition", NODE_TYPE).build()); } - if (MapUtils.isEmpty(nodeType.getCapabilities())) { nodeType.setCapabilities(new HashMap<>()); } - if (MapUtils.isNotEmpty(capabilities)) { nodeType.setCapabilities(new HashMap<>()); - for (Map.Entry entry : capabilities.entrySet()) { nodeType.getCapabilities().put(entry.getKey(), entry.getValue()); } @@ -284,11 +257,9 @@ public class DataModelUtil { * @param policyId the policy id * @param policyDefinition the policy definition */ - public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId, - PolicyDefinition policyDefinition) { + public static void addPolicyDefinition(ServiceTemplate serviceTemplate, String policyId, PolicyDefinition policyDefinition) { if (serviceTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Policy Definition", SERVICE_TEMPLATE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Policy Definition", SERVICE_TEMPLATE).build()); } TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); if (Objects.isNull(topologyTemplate)) { @@ -318,20 +289,16 @@ public class DataModelUtil { serviceTemplate.getNode_types().put(nodeTypeId, nodeType); } - public static void addDataType(final ServiceTemplate serviceTemplate, final String key, - final DataType nodeTypeValue) { + public static void addDataType(final ServiceTemplate serviceTemplate, final String key, final DataType nodeTypeValue) { if (serviceTemplate == null) { throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Data Type", SERVICE_TEMPLATE).build()); } - if (serviceTemplate.getData_types() == null) { serviceTemplate.setData_types(new HashMap<>()); } - serviceTemplate.getData_types().put(key, nodeTypeValue); } - /** * Add relationship template. * @@ -342,8 +309,7 @@ public class DataModelUtil { public static void addRelationshipTemplate(ServiceTemplate serviceTemplate, String relationshipTemplateId, RelationshipTemplate relationshipTemplate) { if (serviceTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Relationship Template", SERVICE_TEMPLATE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Relationship Template", SERVICE_TEMPLATE).build()); } if (serviceTemplate.getTopology_template() == null) { serviceTemplate.setTopology_template(new TopologyTemplate()); @@ -351,8 +317,7 @@ public class DataModelUtil { if (serviceTemplate.getTopology_template().getRelationship_templates() == null) { serviceTemplate.getTopology_template().setRelationship_templates(new HashMap<>()); } - serviceTemplate.getTopology_template().getRelationship_templates() - .put(relationshipTemplateId, relationshipTemplate); + serviceTemplate.getTopology_template().getRelationship_templates().put(relationshipTemplateId, relationshipTemplate); } /** @@ -362,17 +327,13 @@ public class DataModelUtil { * @param requirementId the requirement id * @param requirementAssignment the requirement assignment */ - public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId, - RequirementAssignment requirementAssignment) { + public static void addRequirementAssignment(NodeTemplate nodeTemplate, String requirementId, RequirementAssignment requirementAssignment) { if (nodeTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", - "Node Template").build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Requirement Assignment", "Node Template").build()); } if (requirementAssignment.getNode() == null) { throw new CoreException(new InvalidRequirementAssignmentErrorBuilder(requirementId).build()); } - Map requirement = new HashMap<>(); requirement.put(requirementId, requirementAssignment); nodeTemplate.addRequirements(requirement); @@ -401,7 +362,7 @@ public class DataModelUtil { */ public static NodeTemplate getNodeTemplate(ServiceTemplate serviceTemplate, String nodeTemplateId) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getNode_templates() == null) { + || serviceTemplate.getTopology_template().getNode_templates() == null) { return null; } return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId); @@ -428,8 +389,7 @@ public class DataModelUtil { * @param requirementDefinitionId the requirement definition id * @return the requirement definition */ - public static Optional getRequirementDefinition(NodeType nodeType, - String requirementDefinitionId) { + public static Optional getRequirementDefinition(NodeType nodeType, String requirementDefinitionId) { if (nodeType == null || nodeType.getRequirements() == null || requirementDefinitionId == null) { return Optional.empty(); } @@ -442,18 +402,16 @@ public class DataModelUtil { * @param requirementsDefinitionList requirement definition list * @param requirementKey requirement key */ - public static Optional getRequirementDefinition( - List> requirementsDefinitionList, String requirementKey) { + public static Optional getRequirementDefinition(List> requirementsDefinitionList, + String requirementKey) { if (CollectionUtils.isEmpty(requirementsDefinitionList)) { return Optional.empty(); } - ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); for (Map requirementMap : requirementsDefinitionList) { if (requirementMap.containsKey(requirementKey)) { - RequirementDefinition requirementDefinition = toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementMap.get(requirementKey)), - RequirementDefinition.class); + RequirementDefinition requirementDefinition = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementMap.get(requirementKey)), RequirementDefinition.class); return Optional.of(requirementDefinition); } } @@ -467,8 +425,7 @@ public class DataModelUtil { * @param capabilityDefinitionId the capability definition id * @return the capability definition */ - public static Optional getCapabilityDefinition(NodeType nodeType, - String capabilityDefinitionId) { + public static Optional getCapabilityDefinition(NodeType nodeType, String capabilityDefinitionId) { if (nodeType == null || nodeType.getCapabilities() == null || capabilityDefinitionId == null) { return Optional.empty(); } @@ -482,13 +439,10 @@ public class DataModelUtil { * @param groupName the group name * @param group the group */ - public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate, String groupName, - GroupDefinition group) { + public static void addGroupDefinitionToTopologyTemplate(ServiceTemplate serviceTemplate, String groupName, GroupDefinition group) { if (serviceTemplate == null) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Group Definition", SERVICE_TEMPLATE).build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Group Definition", SERVICE_TEMPLATE).build()); } - TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); if (Objects.isNull(topologyTemplate)) { topologyTemplate = new TopologyTemplate(); @@ -501,7 +455,6 @@ public class DataModelUtil { Map groups = new HashMap<>(); serviceTemplate.getTopology_template().setGroups(groups); } - serviceTemplate.getTopology_template().getGroups().put(groupName, group); } @@ -514,16 +467,13 @@ public class DataModelUtil { */ public static void addGroupMember(ServiceTemplate serviceTemplate, String groupName, String groupMemberId) { TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); - if (Objects.isNull(topologyTemplate) || topologyTemplate.getGroups() == null - || topologyTemplate.getGroups().get(groupName) == null) { + if (Objects.isNull(topologyTemplate) || topologyTemplate.getGroups() == null || topologyTemplate.getGroups().get(groupName) == null) { return; } - GroupDefinition groupDefinition = topologyTemplate.getGroups().get(groupName); if (CollectionUtils.isEmpty(groupDefinition.getMembers())) { groupDefinition.setMembers(new ArrayList<>()); } - if (!groupDefinition.getMembers().contains(groupMemberId)) { groupDefinition.getMembers().add(groupMemberId); } @@ -540,9 +490,8 @@ public class DataModelUtil { * @param defaultVal the default val * @return the property definition */ - public static ParameterDefinition createParameterDefinition(String type, String description, Boolean required, - List constraints, EntrySchema entrySchema, - Object defaultVal) { + public static ParameterDefinition createParameterDefinition(String type, String description, Boolean required, List constraints, + EntrySchema entrySchema, Object defaultVal) { ParameterDefinition paramDef = new ParameterDefinition(); paramDef.setType(type); paramDef.setDescription(description); @@ -562,8 +511,7 @@ public class DataModelUtil { * @param occurrences the occurrences * @return the requirement definition */ - public static RequirementDefinition createRequirement(String capability, String node, String relationship, - Object[] occurrences) { + public static RequirementDefinition createRequirement(String capability, String node, String relationship, Object[] occurrences) { RequirementDefinition requirementDefinition = new RequirementDefinition(); requirementDefinition.setCapability(capability); requirementDefinition.setNode(node); @@ -586,7 +534,6 @@ public class DataModelUtil { if (Objects.isNull(type) && Objects.isNull(description) && CollectionUtils.isEmpty(constraints)) { return null; } - EntrySchema entrySchema = new EntrySchema(); entrySchema.setType(type); entrySchema.setDescription(description); @@ -602,8 +549,7 @@ public class DataModelUtil { * @param nestedPropertyName the nested property name * @return the map */ - public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName, int indexInTheList, - String... nestedPropertyName) { + public static Map createGetInputPropertyValueFromListParameter(String inputPropertyListName, int indexInTheList, String... nestedPropertyName) { List propertyList = new ArrayList<>(); propertyList.add(inputPropertyListName); propertyList.add(indexInTheList); @@ -625,7 +571,6 @@ public class DataModelUtil { if (propertyDefinition == null) { return null; } - ParameterDefinitionExt parameterDefinition = new ParameterDefinitionExt(); parameterDefinition.setType(propertyDefinition.getType()); parameterDefinition.setDescription(propertyDefinition.getDescription()); @@ -633,8 +578,8 @@ public class DataModelUtil { parameterDefinition.set_default(propertyDefinition.get_default()); parameterDefinition.setStatus(propertyDefinition.getStatus()); parameterDefinition.setConstraints(propertyDefinition.getConstraints()); - parameterDefinition.setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null : - propertyDefinition.getEntry_schema().clone()); + parameterDefinition + .setEntry_schema(Objects.isNull(propertyDefinition.getEntry_schema()) ? null : propertyDefinition.getEntry_schema().clone()); parameterDefinition.setHidden(false); parameterDefinition.setImmutable(false); return parameterDefinition; @@ -647,8 +592,7 @@ public class DataModelUtil { * @param outputValue the output value * @return the parameter definition ext */ - public static ParameterDefinitionExt convertAttributeDefToParameterDef(AttributeDefinition attributeDefinition, - Map outputValue) { + public static ParameterDefinitionExt convertAttributeDefToParameterDef(AttributeDefinition attributeDefinition, Map outputValue) { if (attributeDefinition == null) { return null; } @@ -660,7 +604,7 @@ public class DataModelUtil { public static boolean isNodeTemplate(String entryId, ServiceTemplate serviceTemplate) { return serviceTemplate.getTopology_template().getNode_templates() != null - && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null; + && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null; } /** @@ -670,13 +614,10 @@ public class DataModelUtil { * @param parameterDefinitionId the parameter definition id * @param parameterDefinition the parameter definition */ - public static void addInputParameterToTopologyTemplate(ServiceTemplate serviceTemplate, - String parameterDefinitionId, + public static void addInputParameterToTopologyTemplate(ServiceTemplate serviceTemplate, String parameterDefinitionId, ParameterDefinition parameterDefinition) { if (Objects.isNull(serviceTemplate)) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter", SERVICE_TEMPLATE) - .build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Topology Template Input Parameter", SERVICE_TEMPLATE).build()); } TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); if (Objects.isNull(topologyTemplate)) { @@ -696,13 +637,10 @@ public class DataModelUtil { * @param parameterDefinitionId the parameter definition id * @param parameterDefinition the parameter definition */ - public static void addOutputParameterToTopologyTemplate(ServiceTemplate serviceTemplate, - String parameterDefinitionId, + public static void addOutputParameterToTopologyTemplate(ServiceTemplate serviceTemplate, String parameterDefinitionId, ParameterDefinition parameterDefinition) { if (Objects.isNull(serviceTemplate)) { - throw new CoreException( - new InvalidAddActionNullEntityErrorBuilder("Topology Template Output Parameter", SERVICE_TEMPLATE) - .build()); + throw new CoreException(new InvalidAddActionNullEntityErrorBuilder("Topology Template Output Parameter", SERVICE_TEMPLATE).build()); } TopologyTemplate topologyTemplate = serviceTemplate.getTopology_template(); if (Objects.isNull(topologyTemplate)) { @@ -729,7 +667,6 @@ public class DataModelUtil { if (requirementList == null) { requirementList = new ArrayList<>(); } - for (Map.Entry entry : requirementDef.entrySet()) { CommonMethods.mergeEntryInList(entry.getKey(), entry.getValue(), requirementList); } @@ -745,7 +682,6 @@ public class DataModelUtil { return null; } List> templateRequirements = nodeTemplate.getRequirements(); - Map nodeTemplateRequirementsAssignment = new HashMap<>(); if (CollectionUtils.isEmpty(templateRequirements)) { return nodeTemplateRequirementsAssignment; @@ -753,8 +689,8 @@ public class DataModelUtil { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); for (Map requirementAssignmentMap : templateRequirements) { for (Map.Entry requirementEntry : requirementAssignmentMap.entrySet()) { - RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementEntry.getValue()), RequirementAssignment.class)); + RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementEntry.getValue()), RequirementAssignment.class)); nodeTemplateRequirementsAssignment.put(requirementEntry.getKey(), requirementAssignment); } } @@ -779,8 +715,8 @@ public class DataModelUtil { Map requirement = reqListIterator.next(); Map concreteRequirement = new HashMap<>(); for (Map.Entry reqEntry : requirement.entrySet()) { - RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()), RequirementAssignment.class)); + RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqEntry.getValue()), RequirementAssignment.class)); concreteRequirement.put(reqEntry.getKey(), requirementAssignment); concreteRequirementList.add(concreteRequirement); reqListIterator.remove(); @@ -799,19 +735,17 @@ public class DataModelUtil { * @param requirementsAssignmentList requirement definition list * @param requirementKey requirement key */ - public static Optional> getRequirementAssignment( - List> requirementsAssignmentList, String requirementKey) { + public static Optional> getRequirementAssignment(List> requirementsAssignmentList, + String requirementKey) { if (CollectionUtils.isEmpty(requirementsAssignmentList)) { return Optional.empty(); } - List matchRequirementAssignmentList = new ArrayList<>(); for (Map requirementMap : requirementsAssignmentList) { if (requirementMap.containsKey(requirementKey)) { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(requirementMap.get(requirementKey)), - RequirementAssignment.class)); + RequirementAssignment requirementAssignment = (toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementMap.get(requirementKey)), RequirementAssignment.class)); matchRequirementAssignmentList.add(requirementAssignment); } } @@ -827,12 +761,10 @@ public class DataModelUtil { * @param requirementsDefinitionList requirement definition list * @param requirementKey requirement key */ - public static void removeRequirementsDefinition(List> requirementsDefinitionList, - String requirementKey) { + public static void removeRequirementsDefinition(List> requirementsDefinitionList, String requirementKey) { if (requirementsDefinitionList == null) { return; } - List> mapToBeRemoved = new ArrayList<>(); for (Map reqMap : requirementsDefinitionList) { reqMap.remove(requirementKey); @@ -851,12 +783,10 @@ public class DataModelUtil { * @param requirementsAssignmentList requirement Assignment list * @param requirementKey requirement key */ - public static void removeRequirementsAssignment(List> requirementsAssignmentList, - String requirementKey) { + public static void removeRequirementsAssignment(List> requirementsAssignmentList, String requirementKey) { if (requirementsAssignmentList == null) { return; } - List> mapToBeRemoved = new ArrayList<>(); for (Map reqMap : requirementsAssignmentList) { reqMap.remove(requirementKey); @@ -869,7 +799,6 @@ public class DataModelUtil { } } - /** * Remove requirement assignment. * @@ -884,19 +813,14 @@ public class DataModelUtil { if (nodeTemplateRequirements == null) { return; } - ListIterator> iter = nodeTemplateRequirements.listIterator(); while (iter.hasNext()) { Map reqMap = iter.next(); RequirementAssignment requirementAssignment = reqMap.get(requirementKey); if (requirementAssignment != null) { boolean isDesiredRequirementAssignment = toscaAnalyzerService - .isDesiredRequirementAssignment(requirementAssignment, - requirementAssignmentToBeDeleted - .getCapability(), - requirementAssignmentToBeDeleted.getNode(), - requirementAssignmentToBeDeleted - .getRelationship()); + .isDesiredRequirementAssignment(requirementAssignment, requirementAssignmentToBeDeleted.getCapability(), + requirementAssignmentToBeDeleted.getNode(), requirementAssignmentToBeDeleted.getRelationship()); if (isDesiredRequirementAssignment) { iter.remove(); } @@ -946,7 +870,7 @@ public class DataModelUtil { */ public static ParameterDefinition getOuputParameter(ServiceTemplate serviceTemplate, String outputParameterId) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getOutputs() == null) { + || serviceTemplate.getTopology_template().getOutputs() == null) { return null; } return serviceTemplate.getTopology_template().getOutputs().get(outputParameterId); @@ -959,8 +883,7 @@ public class DataModelUtil { * @return the input parameters */ public static Map getInputParameters(ServiceTemplate serviceTemplate) { - if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getInputs() == null) { + if (serviceTemplate == null || serviceTemplate.getTopology_template() == null || serviceTemplate.getTopology_template().getInputs() == null) { return null; } return serviceTemplate.getTopology_template().getInputs(); @@ -974,7 +897,7 @@ public class DataModelUtil { */ public static Map getRelationshipTemplates(ServiceTemplate serviceTemplate) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getRelationship_templates() == null) { + || serviceTemplate.getTopology_template().getRelationship_templates() == null) { return null; } return serviceTemplate.getTopology_template().getRelationship_templates(); @@ -1001,11 +924,10 @@ public class DataModelUtil { * @param nodeTemplateId node template id * @return node template properties */ - public static Map getNodeTemplateProperties(ServiceTemplate serviceTemplate, - String nodeTemplateId) { + public static Map getNodeTemplateProperties(ServiceTemplate serviceTemplate, String nodeTemplateId) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getNode_templates() == null - || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) { + || serviceTemplate.getTopology_template().getNode_templates() == null + || serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) == null) { return null; } return serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId).getProperties(); @@ -1022,11 +944,9 @@ public class DataModelUtil { if (Objects.isNull(nodeTemplate)) { return; } - if (MapUtils.isEmpty(nodeTemplate.getProperties())) { nodeTemplate.setProperties(new HashMap<>()); } - nodeTemplate.getProperties().put(propertyKey, propertyValue); } @@ -1038,13 +958,12 @@ public class DataModelUtil { */ public static SubstitutionMapping getSubstitutionMappings(ServiceTemplate serviceTemplate) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) { + || serviceTemplate.getTopology_template().getSubstitution_mappings() == null) { return null; } return serviceTemplate.getTopology_template().getSubstitution_mappings(); } - /** * Compare two requirement assignment objects for equality. * @@ -1053,8 +972,8 @@ public class DataModelUtil { * @return true if objects are equal and false otherwise */ public static boolean compareRequirementAssignment(RequirementAssignment first, RequirementAssignment second) { - return (first.getCapability().equals(second.getCapability()) && first.getNode().equals(second.getNode()) - && first.getRelationship().equals(second.getRelationship())); + return (first.getCapability().equals(second.getCapability()) && first.getNode().equals(second.getNode()) && first.getRelationship() + .equals(second.getRelationship())); } /** @@ -1138,15 +1057,13 @@ public class DataModelUtil { * @param mapping the mapping * @return the substitution mapping */ - public static SubstitutionMapping createSubstitutionTemplateSubMapping(String nodeTypeKey, - NodeType substitutionNodeType, + public static SubstitutionMapping createSubstitutionTemplateSubMapping(String nodeTypeKey, NodeType substitutionNodeType, Map>> mapping) { SubstitutionMapping substitutionMapping = new SubstitutionMapping(); substitutionMapping.setNode_type(nodeTypeKey); - substitutionMapping.setCapabilities(manageCapabilityMapping(substitutionNodeType.getCapabilities(), - mapping.get(ToscaConstants.CAPABILITY))); - substitutionMapping.setRequirements( - manageRequirementMapping(substitutionNodeType.getRequirements(), mapping.get(ToscaConstants.REQUIREMENT))); + substitutionMapping.setCapabilities(manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get(ToscaConstants.CAPABILITY))); + substitutionMapping + .setRequirements(manageRequirementMapping(substitutionNodeType.getRequirements(), mapping.get(ToscaConstants.REQUIREMENT))); return substitutionMapping; } @@ -1158,8 +1075,7 @@ public class DataModelUtil { * @param capabilityProperties the capability properties * @param capabilityAttributes the capability attributes */ - public static void addNodeTemplateCapability(NodeTemplate nodeTemplate, String capabilityId, - Map capabilityProperties, + public static void addNodeTemplateCapability(NodeTemplate nodeTemplate, String capabilityId, Map capabilityProperties, Map capabilityAttributes) { Map capabilities = nodeTemplate.getCapabilities(); if (Objects.isNull(capabilities)) { @@ -1172,9 +1088,8 @@ public class DataModelUtil { nodeTemplate.setCapabilities(capabilities); } - private static Map> manageRequirementMapping( - List> requirementList, - Map> requirementSubstitutionMapping) { + private static Map> manageRequirementMapping(List> requirementList, + Map> requirementSubstitutionMapping) { if (requirementList == null) { return null; } @@ -1196,7 +1111,6 @@ public class DataModelUtil { if (capabilities == null) { return null; } - Map> capabilityMapping = new HashMap<>(); String capabilityKey; List capabilityMap; @@ -1208,8 +1122,7 @@ public class DataModelUtil { return capabilityMapping; } - public static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType, - List> requirementsList, + public static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType, List> requirementsList, String templateName) { if (CollectionUtils.isEmpty(requirementsList)) { return; @@ -1217,7 +1130,6 @@ public class DataModelUtil { if (substitutionNodeType.getRequirements() == null) { substitutionNodeType.setRequirements(new ArrayList<>()); } - for (Map requirementDef : requirementsList) { for (Map.Entry entry : requirementDef.entrySet()) { Map requirementMap = new HashMap<>(); @@ -1228,8 +1140,7 @@ public class DataModelUtil { } public static boolean isNodeTemplateSectionMissingFromServiceTemplate(ServiceTemplate serviceTemplate) { - return Objects.isNull(serviceTemplate.getTopology_template()) || MapUtils.isEmpty( - serviceTemplate.getTopology_template().getNode_templates()); + return Objects.isNull(serviceTemplate.getTopology_template()) || MapUtils.isEmpty(serviceTemplate.getTopology_template().getNode_templates()); } /** @@ -1239,15 +1150,12 @@ public class DataModelUtil { * @param relationshipId the relationship id * @return the relationship template */ - public static Optional getRelationshipTemplate(ServiceTemplate serviceTemplate, - String relationshipId) { + public static Optional getRelationshipTemplate(ServiceTemplate serviceTemplate, String relationshipId) { if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getRelationship_templates() == null - || serviceTemplate.getTopology_template().getRelationship_templates().get(relationshipId) == null) { + || serviceTemplate.getTopology_template().getRelationship_templates() == null + || serviceTemplate.getTopology_template().getRelationship_templates().get(relationshipId) == null) { return Optional.empty(); } return Optional.of(serviceTemplate.getTopology_template().getRelationship_templates().get(relationshipId)); } - - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java index b21d847a07..b15f32644a 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaAnalyzerService.java @@ -13,78 +13,76 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services; -import org.onap.sdc.tosca.datatypes.model.*; -import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; -import org.openecomp.sdc.tosca.datatypes.ToscaFlatData; -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; - import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; +import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.onap.sdc.tosca.datatypes.model.DefinitionOfDataType; +import org.onap.sdc.tosca.datatypes.model.InterfaceDefinitionType; +import org.onap.sdc.tosca.datatypes.model.NodeTemplate; +import org.onap.sdc.tosca.datatypes.model.NodeType; +import org.onap.sdc.tosca.datatypes.model.PropertyDefinition; +import org.onap.sdc.tosca.datatypes.model.RequirementAssignment; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; +import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; +import org.openecomp.sdc.tosca.datatypes.ToscaFlatData; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; public interface ToscaAnalyzerService { /* node template with type equal to node type or derived from node type */ - Map getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType, - ToscaServiceModel toscaServiceModel); + Map getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType, ToscaServiceModel toscaServiceModel); Optional fetchNodeType(String nodeTypeKey, Collection serviceTemplates); - boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel); + boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel); boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel); + ToscaServiceModel toscaServiceModel); - boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel); + boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel); boolean isTypeOf(CapabilityDefinition capabilityDefinition, String capabilityType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel); + ToscaServiceModel toscaServiceModel); List getRequirements(NodeTemplate nodeTemplate, String requirementId); Optional getNodeTemplateById(ServiceTemplate serviceTemplate, String nodeTemplateId); - Optional getSubstituteServiceTemplateName(String substituteNodeTemplateId, - NodeTemplate substitutableNodeTemplate); + Optional getSubstituteServiceTemplateName(String substituteNodeTemplateId, NodeTemplate substitutableNodeTemplate); Map getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate); Optional> getSubstitutionMappedNodeTemplateByExposedReq(String substituteServiceTemplateFileName, - ServiceTemplate substituteServiceTemplate, - String requirementId); + ServiceTemplate substituteServiceTemplate, + String requirementId); /* match only for the input which is not null */ - boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability, String node, - String relationship); + boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability, String node, String relationship); - ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String type, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaModel); + ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String type, ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel); boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate); - NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, - String nodeTypeDerivedFromValue); + NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, String nodeTypeDerivedFromValue); - boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId, - RequirementAssignment requirementAssignment); + boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId, RequirementAssignment requirementAssignment); Map manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate); Map calculateExposedCapabilities(Map nodeTypeCapabilitiesDefinition, - Map> fullFilledRequirementsDefinitionMap); + Map> fullFilledRequirementsDefinitionMap); List> calculateExposedRequirements(List> nodeTypeRequirementsDefinitionList, - Map nodeTemplateRequirementsAssignment); + Map nodeTemplateRequirementsAssignment); ToscaServiceModel loadToscaCsarPackage(byte[] toscaCsarPackage); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java index ea9a6cde04..509553db8d 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaConstants.java @@ -13,11 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services; - - public class ToscaConstants { //TOSCA Requirement Ids @@ -27,13 +24,10 @@ public class ToscaConstants { public static final String LOCAL_STORAGE_REQUIREMENT_ID = "local_storage"; public static final String NETWORK_REQUIREMENT_ID = "network"; public static final String PORT_REQUIREMENT_ID = "port"; - //TOSCA Capability Ids public static final String PORT_MIRRORING_CAPABILITY_ID = "port_mirroring"; - //TOSCA Annotation Ids public static final String SOURCE_ANNOTATION_ID = "source"; - //General public static final String TOSCA_DEFINITIONS_VERSION = "tosca_simple_yaml_1_0_0"; public static final String MODELABLE_ENTITY_NAME_SELF = "SELF"; @@ -66,15 +60,14 @@ public class ToscaConstants { // properties valid values public static final String HEAT_SOURCE_TYPE = "HEAT"; public static final String CONTRAIL_SERVICE_INSTANCE_IND = "contrail_service_instance_ind"; - static final String ST_METADATA_FILE_NAME = "filename"; public static final String MANDATORY_PROPERTY_NAME = "mandatory"; public static final String HEAT_NODE_TYPE_SUFFIX = "heat."; public static final String CAPABILITY = "capability"; public static final String REQUIREMENT = "requirement"; public static final String SERVICE_TEMPLATE_FILE_POSTFIX = "ServiceTemplate.yaml"; + static final String ST_METADATA_FILE_NAME = "filename"; private ToscaConstants() { //Hiding the implicit public constructor } - } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java index 7ec2fffa2b..334ff6f567 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaFileOutputService.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.services; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; public interface ToscaFileOutputService { - byte[] createOutputFile(ToscaServiceModel toscaServiceModel, - FileContentHandler externalArtifacts); - String createMetaFile(String entryDefinitionsFileName); + byte[] createOutputFile(ToscaServiceModel toscaServiceModel, FileContentHandler externalArtifacts); - String getArtifactsFolderName(); + String createMetaFile(String entryDefinitionsFileName); + String getArtifactsFolderName(); } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java index 7c8e48ac88..66230250d5 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/ToscaUtil.java @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.tosca.services; import java.util.Collections; @@ -26,7 +25,6 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; - import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.commons.collections4.MapUtils; @@ -66,11 +64,9 @@ public class ToscaUtil { if (metadata.get(ToscaConstants.ST_METADATA_FILE_NAME) != null) { return metadata.get(ToscaConstants.ST_METADATA_FILE_NAME); } else if (metadata.get(ToscaConstants.ST_METADATA_TEMPLATE_NAME) != null) { - return metadata.get(ToscaConstants.ST_METADATA_TEMPLATE_NAME) - + ToscaConstants.SERVICE_TEMPLATE_FILE_POSTFIX; + return metadata.get(ToscaConstants.ST_METADATA_TEMPLATE_NAME) + ToscaConstants.SERVICE_TEMPLATE_FILE_POSTFIX; } - return UUID.randomUUID().toString() + ToscaConstants.SERVICE_TEMPLATE_FILE_POSTFIX; - + return UUID.randomUUID().toString() + ToscaConstants.SERVICE_TEMPLATE_FILE_POSTFIX; } public static String getServiceTemplateFileName(String templateName) { @@ -79,59 +75,41 @@ public class ToscaUtil { return getServiceTemplateFileName(metadata); } - public static Optional getSubstitutableGroupMemberId(String heatFileName, - ServiceTemplate serviceTemplate) { - - Map nodeTemplates = - DataModelUtil.getNodeTemplates(serviceTemplate); - + public static Optional getSubstitutableGroupMemberId(String heatFileName, ServiceTemplate serviceTemplate) { + Map nodeTemplates = DataModelUtil.getNodeTemplates(serviceTemplate); if (MapUtils.isEmpty(nodeTemplates)) { return Optional.empty(); } - String heatFileNameWithoutExt = FileUtils.getFileWithoutExtention(heatFileName); - for (Map.Entry nodeTemplateEntry : nodeTemplates.entrySet()) { - String subServiceTemplateName = - getSubstitutionServiceTemplateNameFromProperties(nodeTemplateEntry); - - if (Objects.nonNull(subServiceTemplateName) - && isGroupMemberIdSubstitutable(heatFileNameWithoutExt, subServiceTemplateName)) { + String subServiceTemplateName = getSubstitutionServiceTemplateNameFromProperties(nodeTemplateEntry); + if (Objects.nonNull(subServiceTemplateName) && isGroupMemberIdSubstitutable(heatFileNameWithoutExt, subServiceTemplateName)) { return Optional.of(nodeTemplateEntry.getKey()); } } - return Optional.empty(); } - private static boolean isGroupMemberIdSubstitutable(String heatFileNameWithoutExt, - String subServiceTemplateName) { + private static boolean isGroupMemberIdSubstitutable(String heatFileNameWithoutExt, String subServiceTemplateName) { return subServiceTemplateName.startsWith(heatFileNameWithoutExt); } - private static String getSubstitutionServiceTemplateNameFromProperties( - Map.Entry nodeTemplateEntry) { + private static String getSubstitutionServiceTemplateNameFromProperties(Map.Entry nodeTemplateEntry) { Map properties = - nodeTemplateEntry.getValue().getProperties() == null ? Collections.emptyMap() : - nodeTemplateEntry.getValue().getProperties(); - + nodeTemplateEntry.getValue().getProperties() == null ? Collections.emptyMap() : nodeTemplateEntry.getValue().getProperties(); Map serviceTemplateFilter = - properties.containsKey(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) ? - (Map) properties.get(ToscaConstants - .SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) : Collections.emptyMap(); - + properties.containsKey(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) ? (Map) properties + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) : Collections.emptyMap(); return (String) serviceTemplateFilter.get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME); } - /** * Add service template to map with key file name. * * @param serviceTemplateMap the service template map * @param serviceTemplate the service template */ - public static void addServiceTemplateToMapWithKeyFileName( - Map serviceTemplateMap, ServiceTemplate serviceTemplate) { + public static void addServiceTemplateToMapWithKeyFileName(Map serviceTemplateMap, ServiceTemplate serviceTemplate) { serviceTemplateMap.put(ToscaUtil.getServiceTemplateFileName(serviceTemplate), serviceTemplate); } } diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java index 3ce9badea0..c5deee4ebd 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services.impl; import java.io.ByteArrayInputStream; @@ -91,18 +90,58 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { private static final String TOSCA_META_FILE = "TOSCA-Metadata/TOSCA.meta"; private static final String ENTRY_DEFINITIONS = "Entry-Definitions"; + private static boolean isFile(String currentEntryName) { + return !(currentEntryName.endsWith("\\") || currentEntryName.endsWith("/")); + } + + private static boolean evaluateRequirementFulfillment(RequirementDefinition requirementDefinition) { + Object[] occurrences = requirementDefinition.getOccurrences(); + if (occurrences == null) { + requirementDefinition.setOccurrences(new Object[]{1, 1}); + return false; + } + if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { + return false; + } + if (occurrences[1].equals(1)) { + return true; + } + occurrences[1] = (Integer) occurrences[1] - 1; + return false; + } + + private static boolean evaluateCapabilityFulfillment(CapabilityDefinition capabilityDefinition) { + Object[] occurrences = capabilityDefinition.getOccurrences(); + if (occurrences == null) { + capabilityDefinition.setOccurrences(new Object[]{1, ToscaConstants.UNBOUNDED}); + return false; + } + if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { + return false; + } + if (occurrences[1].equals(1)) { + return true; + } + occurrences[1] = (Integer) occurrences[1] - 1; + return false; + } + + private static boolean isPrimitiveType(String toscaType) { + return (toscaType.equals(PropertyType.STRING.getDisplayName()) || toscaType.equals(PropertyType.INTEGER.getDisplayName()) || toscaType + .equals(PropertyType.FLOAT.getDisplayName())); + } + @Override public List> calculateExposedRequirements( - List> nodeTypeRequirementsDefinitionList, - Map nodeTemplateRequirementsAssignment) { - + List> nodeTypeRequirementsDefinitionList, + Map nodeTemplateRequirementsAssignment) { if (nodeTypeRequirementsDefinitionList == null) { return Collections.emptyList(); } for (Map.Entry entry : nodeTemplateRequirementsAssignment.entrySet()) { if (entry.getValue().getNode() != null) { - Optional requirementDefinition = - DataModelUtil.getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry.getKey()); + Optional requirementDefinition = DataModelUtil + .getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry.getKey()); RequirementDefinition cloneRequirementDefinition; if (requirementDefinition.isPresent()) { cloneRequirementDefinition = requirementDefinition.get().clone(); @@ -122,7 +161,6 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { ToscaServiceModel toscaServiceModel = new ToscaServiceModel(); ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); FileContentHandler artifactFiles = new FileContentHandler(); - try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(toscaCsarPackage))) { ZipEntry zipEntry; while ((zipEntry = inputZipStream.getNextEntry()) != null) { @@ -144,7 +182,6 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (StringUtils.isEmpty(toscaServiceModel.getEntryDefinitionServiceTemplate())) { handleToscaCsarWithoutToscaMetadata(toscaServiceModel); } - } catch (IOException | ZipSlipException exc) { throw new SdcRuntimeException(exc.getMessage(), exc); } @@ -172,22 +209,16 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { toscaServiceModel.setEntryDefinitionServiceTemplate(entryDefinition); } - void loadToscaYamlFile(ToscaServiceModel toscaServiceModel, ToscaExtensionYamlUtil toscaExtensionYamlUtil, - byte[] fileContent, String fileFullName) { + void loadToscaYamlFile(ToscaServiceModel toscaServiceModel, ToscaExtensionYamlUtil toscaExtensionYamlUtil, byte[] fileContent, + String fileFullName) { try { - ServiceTemplate serviceTemplate = - toscaExtensionYamlUtil.yamlToObject(new String(fileContent), ServiceTemplate.class); + ServiceTemplate serviceTemplate = toscaExtensionYamlUtil.yamlToObject(new String(fileContent), ServiceTemplate.class); toscaServiceModel.addServiceTemplate(fileFullName, serviceTemplate); - } catch (Exception exc) { throw new CoreException(new InvalidToscaFile(fileFullName, exc.getMessage()).build()); } } - private static boolean isFile(String currentEntryName) { - return !(currentEntryName.endsWith("\\") || currentEntryName.endsWith("/")); - } - private boolean isYamlFile(String fileName) { return fileName.endsWith("yaml") || fileName.endsWith("yml"); } @@ -198,57 +229,33 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { } private void updateMinMaxOccurencesForNodeTypeRequirement(Map.Entry entry, - Map nodeTypeRequirementsMap) { + Map nodeTypeRequirementsMap) { Object max = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null - && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 - ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[1] : 1; + && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 ? nodeTypeRequirementsMap.get(entry.getKey()) + .getOccurrences()[1] : 1; Object min = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null - && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 - ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[0] : 1; - nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[] {min, max}); + && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 ? nodeTypeRequirementsMap.get(entry.getKey()) + .getOccurrences()[0] : 1; + nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[]{min, max}); } - private void updateRequirementDefinition( - List> nodeTypeRequirementsDefinitionList, - Map.Entry entry, RequirementDefinition cloneRequirementDefinition) { + private void updateRequirementDefinition(List> nodeTypeRequirementsDefinitionList, + Map.Entry entry, RequirementDefinition cloneRequirementDefinition) { if (!evaluateRequirementFulfillment(cloneRequirementDefinition)) { - CommonMethods - .mergeEntryInList(entry.getKey(), cloneRequirementDefinition, nodeTypeRequirementsDefinitionList); + CommonMethods.mergeEntryInList(entry.getKey(), cloneRequirementDefinition, nodeTypeRequirementsDefinitionList); } else { DataModelUtil.removeRequirementsDefinition(nodeTypeRequirementsDefinitionList, entry.getKey()); } } - private static boolean evaluateRequirementFulfillment(RequirementDefinition requirementDefinition) { - Object[] occurrences = requirementDefinition.getOccurrences(); - if (occurrences == null) { - requirementDefinition.setOccurrences(new Object[] {1, 1}); - return false; - } - if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { - return false; - } - - if (occurrences[1].equals(1)) { - return true; - } - occurrences[1] = (Integer) occurrences[1] - 1; - return false; - } - @Override - public Map calculateExposedCapabilities( - Map nodeTypeCapabilitiesDefinition, - Map> fullFilledRequirementsDefinitionMap) { - + public Map calculateExposedCapabilities(Map nodeTypeCapabilitiesDefinition, + Map> fullFilledRequirementsDefinitionMap) { String capabilityKey; String capability; String node; - for (Map.Entry> entry : fullFilledRequirementsDefinitionMap - .entrySet()) { + for (Map.Entry> entry : fullFilledRequirementsDefinitionMap.entrySet()) { for (Map.Entry fullFilledEntry : entry.getValue().entrySet()) { - - capability = fullFilledEntry.getValue().getCapability(); node = fullFilledEntry.getValue().getNode(); capabilityKey = capability + "_" + node; @@ -256,12 +263,10 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (capabilityDefinition != null) { CapabilityDefinition clonedCapabilityDefinition = capabilityDefinition.clone(); nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityDefinition.clone()); - updateNodeTypeCapabilitiesDefinition(nodeTypeCapabilitiesDefinition, capabilityKey, - clonedCapabilityDefinition); + updateNodeTypeCapabilitiesDefinition(nodeTypeCapabilitiesDefinition, capabilityKey, clonedCapabilityDefinition); } } } - Map exposedCapabilitiesDefinition = new HashMap<>(); for (Map.Entry entry : nodeTypeCapabilitiesDefinition.entrySet()) { exposedCapabilitiesDefinition.put(entry.getKey(), entry.getValue()); @@ -269,8 +274,8 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return exposedCapabilitiesDefinition; } - private void updateNodeTypeCapabilitiesDefinition(Map nodeTypeCapabilitiesDefinition, - String capabilityKey, CapabilityDefinition clonedCapabilityDefinition) { + private void updateNodeTypeCapabilitiesDefinition(Map nodeTypeCapabilitiesDefinition, String capabilityKey, + CapabilityDefinition clonedCapabilityDefinition) { if (evaluateCapabilityFulfillment(clonedCapabilityDefinition)) { nodeTypeCapabilitiesDefinition.remove(capabilityKey); } else { @@ -278,40 +283,18 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { } } - private static boolean evaluateCapabilityFulfillment(CapabilityDefinition capabilityDefinition) { - - Object[] occurrences = capabilityDefinition.getOccurrences(); - if (occurrences == null) { - capabilityDefinition.setOccurrences(new Object[] {1, ToscaConstants.UNBOUNDED}); - return false; - } - if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { - return false; - } - - if (occurrences[1].equals(1)) { - return true; - } - occurrences[1] = (Integer) occurrences[1] - 1; - return false; - } - /* node template with type equal to node type or derived from node type */ @Override - public Map getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType, - ToscaServiceModel toscaServiceModel) { + public Map getNodeTemplatesByType(ServiceTemplate serviceTemplate, String nodeType, ToscaServiceModel toscaServiceModel) { Map nodeTemplates = new HashMap<>(); - - if (Objects.nonNull(serviceTemplate.getTopology_template()) && MapUtils.isNotEmpty( - serviceTemplate.getTopology_template().getNode_templates())) { - for (Map.Entry nodeTemplateEntry : serviceTemplate.getTopology_template() - .getNode_templates().entrySet()) { + if (Objects.nonNull(serviceTemplate.getTopology_template()) && MapUtils + .isNotEmpty(serviceTemplate.getTopology_template().getNode_templates())) { + for (Map.Entry nodeTemplateEntry : serviceTemplate.getTopology_template().getNode_templates().entrySet()) { if (isTypeOf(nodeTemplateEntry.getValue(), nodeType, serviceTemplate, toscaServiceModel)) { nodeTemplates.put(nodeTemplateEntry.getKey(), nodeTemplateEntry.getValue()); } - } } return nodeTemplates; @@ -320,38 +303,31 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { @Override public Optional fetchNodeType(String nodeTypeKey, Collection serviceTemplates) { Optional> nodeTypeMap = serviceTemplates.stream().map(ServiceTemplate::getNode_types) - .filter(nodeTypes -> Objects.nonNull(nodeTypes) - && nodeTypes - .containsKey( - nodeTypeKey)) - .findFirst(); + .filter(nodeTypes -> Objects.nonNull(nodeTypes) && nodeTypes.containsKey(nodeTypeKey)).findFirst(); return nodeTypeMap.map(stringNodeTypeMap -> stringNodeTypeMap.get(nodeTypeKey)); } @Override - public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel) { + public boolean isTypeOf(NodeTemplate nodeTemplate, String nodeType, ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { return isTypeOf(nodeTemplate, nodeType, GET_NODE_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel); } @Override - public boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { - return isTypeOf(interfaceDefinition, interfaceType, GET_INTERFACE_TYPE_METHOD_NAME, serviceTemplate, - toscaServiceModel); + public boolean isTypeOf(InterfaceDefinitionType interfaceDefinition, String interfaceType, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel) { + return isTypeOf(interfaceDefinition, interfaceType, GET_INTERFACE_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel); } @Override public boolean isTypeOf(DefinitionOfDataType parameterDefinition, String dataType, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel) { + ToscaServiceModel toscaServiceModel) { return isTypeOf(parameterDefinition, dataType, GET_DATA_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel); } @Override - public boolean isTypeOf(CapabilityDefinition capabilityDefinition, String capabilityType, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { - return isTypeOf(capabilityDefinition, capabilityType, GET_CAPABILITY_TYPE_METHOD_NAME, serviceTemplate, - toscaServiceModel); + public boolean isTypeOf(CapabilityDefinition capabilityDefinition, String capabilityType, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel) { + return isTypeOf(capabilityDefinition, capabilityType, GET_CAPABILITY_TYPE_METHOD_NAME, serviceTemplate, toscaServiceModel); } @Override @@ -361,8 +337,8 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (requirementList != null) { requirementList.stream().filter(reqMap -> reqMap.get(requirementId) != null).forEach(reqMap -> { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - RequirementAssignment reqAssignment = toscaExtensionYamlUtil.yamlToObject( - toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)), RequirementAssignment.class); + RequirementAssignment reqAssignment = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(reqMap.get(requirementId)), RequirementAssignment.class); requirements.add(reqAssignment); }); } @@ -371,53 +347,43 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { @Override public Optional getNodeTemplateById(ServiceTemplate serviceTemplate, String nodeTemplateId) { - if ((serviceTemplate.getTopology_template() != null) && ( - serviceTemplate.getTopology_template().getNode_templates() != null) && ( - serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) != null)) { + if ((serviceTemplate.getTopology_template() != null) && (serviceTemplate.getTopology_template().getNode_templates() != null) && ( + serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId) != null)) { return Optional.of(serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId)); } return Optional.empty(); } @Override - public Optional getSubstituteServiceTemplateName(String substituteNodeTemplateId, - NodeTemplate substitutableNodeTemplate) { + public Optional getSubstituteServiceTemplateName(String substituteNodeTemplateId, NodeTemplate substitutableNodeTemplate) { if (!isSubstitutableNodeTemplate(substitutableNodeTemplate)) { return Optional.empty(); } - - if (substitutableNodeTemplate.getProperties() != null && - substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) - != null) { - Object serviceTemplateFilter = - substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + if (substitutableNodeTemplate.getProperties() != null + && substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME) != null) { + Object serviceTemplateFilter = substitutableNodeTemplate.getProperties().get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); if (serviceTemplateFilter instanceof Map) { - Object substituteServiceTemplate = - ((Map) serviceTemplateFilter).get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME); + Object substituteServiceTemplate = ((Map) serviceTemplateFilter).get(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME); handleNoSubstituteServiceTemplate(substituteNodeTemplateId, substituteServiceTemplate); return Optional.of(substituteServiceTemplate.toString()); } } - throw new CoreException( - new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId).build()); + throw new CoreException(new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId).build()); } private void handleNoSubstituteServiceTemplate(String substituteNodeTemplateId, Object substituteServiceTemplate) { if (substituteServiceTemplate == null) { - throw new CoreException( - new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId).build()); + throw new CoreException(new ToscaInvalidSubstituteNodeTemplatePropertiesErrorBuilder(substituteNodeTemplateId).build()); } } @Override public Map getSubstitutableNodeTemplates(ServiceTemplate serviceTemplate) { Map substitutableNodeTemplates = new HashMap<>(); - if (serviceTemplate == null || serviceTemplate.getTopology_template() == null - || serviceTemplate.getTopology_template().getNode_templates() == null) { + || serviceTemplate.getTopology_template().getNode_templates() == null) { return substitutableNodeTemplates; } - Map nodeTemplates = serviceTemplate.getTopology_template().getNode_templates(); for (Map.Entry entry : nodeTemplates.entrySet()) { String nodeTemplateId = entry.getKey(); @@ -426,24 +392,23 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { substitutableNodeTemplates.put(nodeTemplateId, nodeTemplate); } } - return substitutableNodeTemplates; } @Override - public Optional> getSubstitutionMappedNodeTemplateByExposedReq( - String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate, String requirementId) { + public Optional> getSubstitutionMappedNodeTemplateByExposedReq(String substituteServiceTemplateFileName, + ServiceTemplate substituteServiceTemplate, + String requirementId) { if (isSubstitutionServiceTemplate(substituteServiceTemplateFileName, substituteServiceTemplate)) { - Map> substitutionMappingRequirements = - substituteServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements(); + Map> substitutionMappingRequirements = substituteServiceTemplate.getTopology_template().getSubstitution_mappings() + .getRequirements(); if (substitutionMappingRequirements != null) { List requirementMapping = substitutionMappingRequirements.get(requirementId); if (requirementMapping != null && !requirementMapping.isEmpty()) { String mappedNodeTemplateId = requirementMapping.get(0); - Optional mappedNodeTemplate = - getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId); - mappedNodeTemplate.orElseThrow(() -> new CoreException( - new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", mappedNodeTemplateId).build())); + Optional mappedNodeTemplate = getNodeTemplateById(substituteServiceTemplate, mappedNodeTemplateId); + mappedNodeTemplate.orElseThrow( + () -> new CoreException(new ToscaInvalidEntryNotFoundErrorBuilder("Node Template", mappedNodeTemplateId).build())); Map.Entry mappedNodeTemplateEntry = new Map.Entry() { @Override public String getKey() { @@ -471,47 +436,36 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { match only for the input which is not null */ @Override - public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability, - String node, String relationship) { + public boolean isDesiredRequirementAssignment(RequirementAssignment requirementAssignment, String capability, String node, String relationship) { if (isSameCapability(requirementAssignment, capability)) { return false; } - if (isSameRequirement(requirementAssignment, node)) { return false; } - if (isSameRelationship(requirementAssignment, relationship)) { return false; } - return !(capability == null && node == null && relationship == null); - } private boolean isSameRelationship(RequirementAssignment requirementAssignment, String relationship) { - return relationship != null && (requirementAssignment.getRelationship() == null || !requirementAssignment - .getRelationship() - .equals(relationship)); + return relationship != null && (requirementAssignment.getRelationship() == null || !requirementAssignment.getRelationship() + .equals(relationship)); } private boolean isSameRequirement(RequirementAssignment requirementAssignment, String node) { - return node != null && (requirementAssignment.getNode() == null || !requirementAssignment.getNode() - .equals(node)); + return node != null && (requirementAssignment.getNode() == null || !requirementAssignment.getNode().equals(node)); } private boolean isSameCapability(RequirementAssignment requirementAssignment, String capability) { - return capability != null && (requirementAssignment.getCapability() == null || !requirementAssignment - .getCapability() - .equals(capability)); + return capability != null && (requirementAssignment.getCapability() == null || !requirementAssignment.getCapability().equals(capability)); } @Override - public ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String typeId, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaModel) { + public ToscaFlatData getFlatEntity(ToscaElementTypes elementType, String typeId, ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel) { ToscaFlatData flatData = new ToscaFlatData(); flatData.setElementType(elementType); - switch (elementType) { case CAPABILITY_TYPE: flatData.setFlatEntity(new CapabilityType()); @@ -525,87 +479,69 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { default: throw new SdcRuntimeException("Entity[" + elementType + "] id[" + typeId + "] flat not supported"); } - - boolean isEntityFound = - scanAnFlatEntity(elementType, typeId, flatData, serviceTemplate, toscaModel, new ArrayList<>(), 0); + boolean isEntityFound = scanAnFlatEntity(elementType, typeId, flatData, serviceTemplate, toscaModel, new ArrayList<>(), 0); if (!isEntityFound) { throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build()); } - return flatData; } @Override public boolean isSubstitutableNodeTemplate(NodeTemplate nodeTemplate) { - return nodeTemplate.getDirectives() != null && nodeTemplate.getDirectives().contains( - ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + return nodeTemplate.getDirectives() != null && nodeTemplate.getDirectives().contains(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); } - private Optional isTypeExistInServiceTemplateHierarchy(String typeToMatch, String typeToSearch, - String getTypesMethodName, ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, - Set analyzedImportFiles) - throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { - Map searchableTypes = - (Map) serviceTemplate.getClass().getMethod(getTypesMethodName).invoke(serviceTemplate); - + private Optional isTypeExistInServiceTemplateHierarchy(String typeToMatch, String typeToSearch, String getTypesMethodName, + ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, + Set analyzedImportFiles) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Map searchableTypes = (Map) serviceTemplate.getClass().getMethod(getTypesMethodName).invoke(serviceTemplate); if (!MapUtils.isEmpty(searchableTypes)) { T typeObject = searchableTypes.get(typeToSearch); if (Objects.nonNull(typeObject)) { - String derivedFromTypeVal = - (String) typeObject.getClass().getMethod(GET_DERIVED_FROM_METHOD_NAME).invoke(typeObject); + String derivedFromTypeVal = (String) typeObject.getClass().getMethod(GET_DERIVED_FROM_METHOD_NAME).invoke(typeObject); if (Objects.equals(derivedFromTypeVal, typeToMatch)) { return Optional.of(true); } else if (Objects.isNull(derivedFromTypeVal) || isTypeIsToscaRoot(derivedFromTypeVal)) { return Optional.of(false); } else { - return isTypeExistInServiceTemplateHierarchy(typeToMatch, derivedFromTypeVal, getTypesMethodName, - serviceTemplate, toscaServiceModel, null); + return isTypeExistInServiceTemplateHierarchy(typeToMatch, derivedFromTypeVal, getTypesMethodName, serviceTemplate, + toscaServiceModel, null); } } else { - return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate, - toscaServiceModel, analyzedImportFiles); + return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate, toscaServiceModel, analyzedImportFiles); } } - return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate, toscaServiceModel, - analyzedImportFiles); + return isTypeExistInImports(typeToMatch, typeToSearch, getTypesMethodName, serviceTemplate, toscaServiceModel, analyzedImportFiles); } private Optional isTypeExistInImports(String typeToMatch, String typeToSearch, String getTypesMethodName, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, Set filesScanned) - throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { + ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel, Set filesScanned) + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { List> imports = serviceTemplate.getImports(); if (CollectionUtils.isEmpty(imports)) { return Optional.empty(); } - Set createdFilesScanned = createFilesScannedSet(filesScanned); - for (Map map : imports) { ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); - Import anImport = toscaExtensionYamlUtil - .yamlToObject(toscaExtensionYamlUtil.objectToYaml(map.values().iterator().next()), - Import.class); + Import anImport = toscaExtensionYamlUtil.yamlToObject(toscaExtensionYamlUtil.objectToYaml(map.values().iterator().next()), Import.class); handleImportWithNoFileEntry(anImport); String importFile = anImport.getFile(); - ServiceTemplate template = toscaServiceModel.getServiceTemplates() - .get(fetchFullFileNameForImport(importFile, - serviceTemplate.getMetadata() == null ? null : - serviceTemplate.getMetadata().get("filename"), - serviceTemplate, toscaServiceModel)); - if (Objects.isNull(template) || createdFilesScanned - .contains(ToscaUtil.getServiceTemplateFileName(template))) { + ServiceTemplate template = toscaServiceModel.getServiceTemplates().get( + fetchFullFileNameForImport(importFile, serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get("filename"), + serviceTemplate, toscaServiceModel)); + if (Objects.isNull(template) || createdFilesScanned.contains(ToscaUtil.getServiceTemplateFileName(template))) { continue; } else { createdFilesScanned.add(ToscaUtil.getServiceTemplateFileName(template)); } - Optional typeExistInServiceTemplateHierarchy = - isTypeExistInServiceTemplateHierarchy(typeToMatch, typeToSearch, getTypesMethodName, template, - toscaServiceModel, createdFilesScanned); + Optional typeExistInServiceTemplateHierarchy = isTypeExistInServiceTemplateHierarchy(typeToMatch, typeToSearch, + getTypesMethodName, template, toscaServiceModel, createdFilesScanned); if (typeExistInServiceTemplateHierarchy.isPresent() && (typeExistInServiceTemplateHierarchy.get())) { createdFilesScanned.clear(); return Optional.of(true); } - } return Optional.of(false); } @@ -628,29 +564,21 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return (type.contains(TOSCA_DOT) && type.contains(DOT_ROOT)); } - private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName, - ServiceTemplate substituteServiceTemplate) { + private boolean isSubstitutionServiceTemplate(String substituteServiceTemplateFileName, ServiceTemplate substituteServiceTemplate) { if (substituteServiceTemplate != null && substituteServiceTemplate.getTopology_template() != null - && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) { + && substituteServiceTemplate.getTopology_template().getSubstitution_mappings() != null) { if (substituteServiceTemplate.getTopology_template().getSubstitution_mappings().getNode_type() == null) { - throw new CoreException( - new ToscaInvalidSubstitutionServiceTemplateErrorBuilder(substituteServiceTemplateFileName) - .build()); + throw new CoreException(new ToscaInvalidSubstitutionServiceTemplateErrorBuilder(substituteServiceTemplateFileName).build()); } return true; } return false; - } - private boolean scanAnFlatEntity(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, List filesScanned, - int rootScanStartInx) { - - - boolean entityFound = - enrichEntityFromCurrentServiceTemplate(elementType, typeId, flatData, serviceTemplate, toscaModel, - filesScanned, rootScanStartInx); + private boolean scanAnFlatEntity(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel, List filesScanned, int rootScanStartInx) { + boolean entityFound = enrichEntityFromCurrentServiceTemplate(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, + rootScanStartInx); if (!entityFound) { List> imports = serviceTemplate.getImports(); if (CollectionUtils.isEmpty(imports)) { @@ -661,25 +589,21 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (found) { return true; } - found = isFlatEntity(importMap, flatData, serviceTemplate, filesScanned, toscaModel, elementType, - typeId); + found = isFlatEntity(importMap, flatData, serviceTemplate, filesScanned, toscaModel, elementType, typeId); } return found; } return true; } - private boolean isFlatEntity(Map importMap, ToscaFlatData flatData, ServiceTemplate serviceTemplate, - List filesScanned, ToscaServiceModel toscaModel, ToscaElementTypes elementType, String typeId) { + private boolean isFlatEntity(Map importMap, ToscaFlatData flatData, ServiceTemplate serviceTemplate, List filesScanned, + ToscaServiceModel toscaModel, ToscaElementTypes elementType, String typeId) { boolean found = false; ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); for (Object importObject : importMap.values()) { - Import importServiceTemplate = toscaExtensionYamlUtil - .yamlToObject(toscaExtensionYamlUtil.objectToYaml(importObject), - Import.class); + Import importServiceTemplate = toscaExtensionYamlUtil.yamlToObject(toscaExtensionYamlUtil.objectToYaml(importObject), Import.class); String fileName = fetchFullFileNameForImport(importServiceTemplate.getFile(), - serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get("filename"), - serviceTemplate, toscaModel); + serviceTemplate.getMetadata() == null ? null : serviceTemplate.getMetadata().get("filename"), serviceTemplate, toscaModel); if (filesScanned.contains(fileName)) { return false; } else { @@ -689,28 +613,24 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (Objects.isNull(template)) { throw new CoreException(new ToscaFileNotFoundErrorBuilder(fileName).build()); } - found = scanAnFlatEntity(elementType, typeId, flatData, template, toscaModel, filesScanned, - filesScanned.size()); + found = scanAnFlatEntity(elementType, typeId, flatData, template, toscaModel, filesScanned, filesScanned.size()); } return found; } - String fetchFullFileNameForImport(String importServiceTemplateFile, String currentMetadatafileName, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaServiceModel) { - Optional> serviceTemplateEntry = - toscaServiceModel.getServiceTemplates().entrySet().stream() - .filter(entry -> entry.getValue() == serviceTemplate).findFirst(); + String fetchFullFileNameForImport(String importServiceTemplateFile, String currentMetadatafileName, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaServiceModel) { + Optional> serviceTemplateEntry = toscaServiceModel.getServiceTemplates().entrySet().stream() + .filter(entry -> entry.getValue() == serviceTemplate).findFirst(); if (!serviceTemplateEntry.isPresent()) { if (importServiceTemplateFile.contains("../")) { return importServiceTemplateFile.replace("../", ""); } else if (currentMetadatafileName != null && currentMetadatafileName.indexOf('/') != -1) { - return currentMetadatafileName.substring(0, currentMetadatafileName.indexOf('/')) + "/" - + importServiceTemplateFile; + return currentMetadatafileName.substring(0, currentMetadatafileName.indexOf('/')) + "/" + importServiceTemplateFile; } else { return importServiceTemplateFile; } } - Path currentPath = Paths.get(serviceTemplateEntry.get().getKey()).getParent(); if (currentPath == null) { currentPath = Paths.get(""); @@ -718,52 +638,43 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return currentPath.resolve(importServiceTemplateFile).normalize().toString().replaceAll("\\\\", "/"); } - private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType, String typeId, - ToscaFlatData flatData, ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, - List filesScanned, int rootScanStartInx) { + private boolean enrichEntityFromCurrentServiceTemplate(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, + ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, List filesScanned, + int rootScanStartInx) { switch (elementType) { case CAPABILITY_TYPE: - if (enrichCapabilityType(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx)) { + if (enrichCapabilityType(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, rootScanStartInx)) { return false; } break; case NODE_TYPE: - if (enrichNodeTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx)) { + if (enrichNodeTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, rootScanStartInx)) { return false; } break; case DATA_TYPE: - if (enrichDataTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx)) { + if (enrichDataTypeInfo(elementType, typeId, flatData, serviceTemplate, toscaModel, filesScanned, rootScanStartInx)) { return false; } break; default: throw new SdcRuntimeException("Entity[" + elementType + "] id[" + typeId + "] flat not supported"); } - return true; - - } - private boolean enrichNodeTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, List filesScanned, - int rootScanStartInx) { + private boolean enrichNodeTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel, List filesScanned, int rootScanStartInx) { String derivedFrom; if (serviceTemplate.getNode_types() != null && serviceTemplate.getNode_types().containsKey(typeId)) { - filesScanned.clear(); flatData.addInheritanceHierarchyType(typeId); NodeType targetNodeType = (NodeType) flatData.getFlatEntity(); NodeType sourceNodeType = serviceTemplate.getNode_types().get(typeId); derivedFrom = sourceNodeType.getDerived_from(); if (derivedFrom != null) { - boolean isEntityFound = - scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx); + boolean isEntityFound = scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, + rootScanStartInx); if (!isEntityFound) { throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build()); } @@ -775,21 +686,18 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return false; } - private boolean enrichDataTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, List filesScanned, - int rootScanStartInx) { + private boolean enrichDataTypeInfo(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel, List filesScanned, int rootScanStartInx) { String derivedFrom; if (serviceTemplate.getData_types() != null && serviceTemplate.getData_types().containsKey(typeId)) { - filesScanned.clear(); flatData.addInheritanceHierarchyType(typeId); DataType targetDataType = (DataType) flatData.getFlatEntity(); DataType sourceDataType = serviceTemplate.getData_types().get(typeId); derivedFrom = sourceDataType.getDerived_from(); if (derivedFrom != null && !isPrimitiveType(derivedFrom)) { - boolean isEntityFound = - scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx); + boolean isEntityFound = scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, + rootScanStartInx); if (!isEntityFound) { throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build()); } @@ -801,28 +709,18 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return false; } - private static boolean isPrimitiveType(String toscaType) { - return (toscaType.equals(PropertyType.STRING.getDisplayName()) || toscaType.equals(PropertyType.INTEGER - .getDisplayName()) - || toscaType.equals(PropertyType.FLOAT.getDisplayName())); - } - - private boolean enrichCapabilityType(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, - ServiceTemplate serviceTemplate, ToscaServiceModel toscaModel, List filesScanned, - int rootScanStartInx) { + private boolean enrichCapabilityType(ToscaElementTypes elementType, String typeId, ToscaFlatData flatData, ServiceTemplate serviceTemplate, + ToscaServiceModel toscaModel, List filesScanned, int rootScanStartInx) { String derivedFrom; - if (serviceTemplate.getCapability_types() != null && serviceTemplate.getCapability_types() - .containsKey(typeId)) { - + if (serviceTemplate.getCapability_types() != null && serviceTemplate.getCapability_types().containsKey(typeId)) { filesScanned.clear(); flatData.addInheritanceHierarchyType(typeId); CapabilityType targetCapabilityType = (CapabilityType) flatData.getFlatEntity(); CapabilityType sourceCapabilityType = serviceTemplate.getCapability_types().get(typeId); derivedFrom = sourceCapabilityType.getDerived_from(); if (derivedFrom != null) { - boolean isEntityFound = - scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, - rootScanStartInx); + boolean isEntityFound = scanAnFlatEntity(elementType, derivedFrom, flatData, serviceTemplate, toscaModel, filesScanned, + rootScanStartInx); if (!isEntityFound) { throw new CoreException(new ToscaElementTypeNotFoundErrorBuilder(typeId).build()); } @@ -838,18 +736,12 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { targetNodeType.setDerived_from(sourceNodeType.getDerived_from()); targetNodeType.setDescription(sourceNodeType.getDescription()); targetNodeType.setVersion(sourceNodeType.getVersion()); - targetNodeType - .setProperties(CommonMethods.mergeMaps(targetNodeType.getProperties(), sourceNodeType.getProperties())); + targetNodeType.setProperties(CommonMethods.mergeMaps(targetNodeType.getProperties(), sourceNodeType.getProperties())); combineNodeTypeInterfaceInfo(sourceNodeType, targetNodeType); - targetNodeType - .setArtifacts(CommonMethods.mergeMaps(targetNodeType.getArtifacts(), sourceNodeType.getArtifacts())); - targetNodeType - .setAttributes(CommonMethods.mergeMaps(targetNodeType.getAttributes(), sourceNodeType.getAttributes())); - targetNodeType.setCapabilities( - CommonMethods.mergeMaps(targetNodeType.getCapabilities(), sourceNodeType.getCapabilities())); - targetNodeType.setRequirements( - CommonMethods.mergeListsOfMap(targetNodeType.getRequirements(), sourceNodeType.getRequirements())); - + targetNodeType.setArtifacts(CommonMethods.mergeMaps(targetNodeType.getArtifacts(), sourceNodeType.getArtifacts())); + targetNodeType.setAttributes(CommonMethods.mergeMaps(targetNodeType.getAttributes(), sourceNodeType.getAttributes())); + targetNodeType.setCapabilities(CommonMethods.mergeMaps(targetNodeType.getCapabilities(), sourceNodeType.getCapabilities())); + targetNodeType.setRequirements(CommonMethods.mergeListsOfMap(targetNodeType.getRequirements(), sourceNodeType.getRequirements())); } private void combineNodeTypeInterfaceInfo(NodeType sourceNodeType, NodeType targetNodeType) { @@ -868,22 +760,19 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { Map combineInterfaces = new HashMap<>(); for (Map.Entry sourceInterfaceDefEntry : sourceNodeType.getInterfaces().entrySet()) { String interfaceName = sourceInterfaceDefEntry.getKey(); - if (!MapUtils.isEmpty(targetNodeType.getInterfaces()) && targetNodeType.getInterfaces() - .containsKey(interfaceName)) { - combineInterfaces.put(interfaceName, combineInterfaceDefinition(sourceInterfaceDefEntry.getValue(), - targetNodeType.getInterfaces().get(interfaceName))); + if (!MapUtils.isEmpty(targetNodeType.getInterfaces()) && targetNodeType.getInterfaces().containsKey(interfaceName)) { + combineInterfaces.put(interfaceName, + combineInterfaceDefinition(sourceInterfaceDefEntry.getValue(), targetNodeType.getInterfaces().get(interfaceName))); } else { combineInterfaces.put(sourceInterfaceDefEntry.getKey(), sourceInterfaceDefEntry.getValue()); } } - for (Map.Entry targetInterfaceDefEntry : targetNodeType.getInterfaces().entrySet()) { String interfaceName = targetInterfaceDefEntry.getKey(); if (!sourceNodeType.getInterfaces().containsKey(interfaceName)) { combineInterfaces.put(targetInterfaceDefEntry.getKey(), targetInterfaceDefEntry.getValue()); } } - return Optional.of(combineInterfaces); } @@ -891,16 +780,13 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if ((MapUtils.isEmpty(sourceNodeType.getInterfaces()) && MapUtils.isEmpty(targetNodeType.getInterfaces()))) { return Optional.empty(); } - if (MapUtils.isEmpty(sourceNodeType.getInterfaces()) && !MapUtils.isEmpty(targetNodeType.getInterfaces())) { return Optional.of(targetNodeType.getInterfaces()); } - if (!MapUtils.isEmpty(sourceNodeType.getInterfaces()) && MapUtils.isEmpty(targetNodeType.getInterfaces())) { return Optional.of(sourceNodeType.getInterfaces()); } return Optional.empty(); - } private Object combineInterfaceDefinition(Object sourceInterfaceDefType, Object targetInterfaceDefType) { @@ -909,9 +795,7 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { InterfaceDefinitionType combineInterface = new InterfaceDefinitionType(); combineInterface.setType(sourceInterface.getType()); combineInterface.setInputs(CommonMethods.mergeMaps(targetInterface.getInputs(), sourceInterface.getInputs())); - combineInterface.setOperations( - CommonMethods.mergeMaps(targetInterface.getOperations(), sourceInterface.getOperations())); - + combineInterface.setOperations(CommonMethods.mergeMaps(targetInterface.getOperations(), sourceInterface.getOperations())); Optional interfaceDefObject = combineInterface.convertInterfaceDefinitionTypeToToscaObj(); if (!interfaceDefObject.isPresent()) { throw new SdcRuntimeException("Illegal Statement"); @@ -923,22 +807,15 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { targetDataType.setDerived_from(sourceDataType.getDerived_from()); targetDataType.setDescription(sourceDataType.getDescription()); targetDataType.setVersion(sourceDataType.getVersion()); - targetDataType - .setProperties(CommonMethods.mergeMaps(targetDataType.getProperties(), sourceDataType.getProperties())); - targetDataType.setConstraints( - CommonMethods.mergeLists(targetDataType.getConstraints(), sourceDataType.getConstraints())); + targetDataType.setProperties(CommonMethods.mergeMaps(targetDataType.getProperties(), sourceDataType.getProperties())); + targetDataType.setConstraints(CommonMethods.mergeLists(targetDataType.getConstraints(), sourceDataType.getConstraints())); } private void combineCapabilityTypeInfo(CapabilityType sourceCapabilityType, CapabilityType targetCapabilityType) { - - targetCapabilityType.setAttributes( - CommonMethods.mergeMaps(targetCapabilityType.getAttributes(), sourceCapabilityType.getAttributes())); - targetCapabilityType.setProperties( - CommonMethods.mergeMaps(targetCapabilityType.getProperties(), sourceCapabilityType.getProperties())); - targetCapabilityType.setValid_source_types(CommonMethods - .mergeLists(targetCapabilityType.getValid_source_types(), - sourceCapabilityType.getValid_source_types())); - + targetCapabilityType.setAttributes(CommonMethods.mergeMaps(targetCapabilityType.getAttributes(), sourceCapabilityType.getAttributes())); + targetCapabilityType.setProperties(CommonMethods.mergeMaps(targetCapabilityType.getProperties(), sourceCapabilityType.getProperties())); + targetCapabilityType.setValid_source_types( + CommonMethods.mergeLists(targetCapabilityType.getValid_source_types(), sourceCapabilityType.getValid_source_types())); if (StringUtils.isNotEmpty(sourceCapabilityType.getDerived_from())) { targetCapabilityType.setDerived_from(sourceCapabilityType.getDerived_from()); } @@ -948,11 +825,8 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { if (StringUtils.isNotEmpty(sourceCapabilityType.getVersion())) { targetCapabilityType.setVersion(sourceCapabilityType.getVersion()); } - - } - /* * Create node type according to the input substitution service template, while the substitution * service template can be mappted to this node type, for substitution mapping. @@ -962,8 +836,7 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { * @return the node type */ @Override - public NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, - String nodeTypeDerivedFromValue) { + public NodeType createInitSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate, String nodeTypeDerivedFromValue) { NodeType substitutionNodeType = new NodeType(); substitutionNodeType.setDerived_from(nodeTypeDerivedFromValue); substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); @@ -973,21 +846,18 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { } @Override - public Map manageSubstitutionNodeTypeProperties( - ServiceTemplate substitutionServiceTemplate) { + public Map manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) { Map substitutionNodeTypeProperties = new HashMap<>(); Map properties = substitutionServiceTemplate.getTopology_template().getInputs(); if (properties == null) { return null; } - PropertyDefinition propertyDefinition; String toscaPropertyName; for (Map.Entry entry : properties.entrySet()) { toscaPropertyName = entry.getKey(); propertyDefinition = new PropertyDefinition(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); propertyDefinition.setType(parameterDefinition.getType()); propertyDefinition.setDescription(parameterDefinition.getDescription()); propertyDefinition.set_default(parameterDefinition.get_default()); @@ -1009,9 +879,7 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { return substitutionNodeTypeProperties; } - - private Map manageSubstitutionNodeTypeAttributes( - ServiceTemplate substitutionServiceTemplate) { + private Map manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) { Map substitutionNodeTypeAttributes = new HashMap<>(); Map attributes = substitutionServiceTemplate.getTopology_template().getOutputs(); if (attributes == null) { @@ -1019,12 +887,10 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { } AttributeDefinition attributeDefinition; String toscaAttributeName; - for (Map.Entry entry : attributes.entrySet()) { attributeDefinition = new AttributeDefinition(); toscaAttributeName = entry.getKey(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); + ParameterDefinition parameterDefinition = substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { attributeDefinition.setType(parameterDefinition.getType()); } else { @@ -1050,36 +916,29 @@ public class ToscaAnalyzerServiceImpl implements ToscaAnalyzerService { * @return true if the requirement already exists and false otherwise */ @Override - public boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId, - RequirementAssignment requirementAssignment) { + public boolean isRequirementExistInNodeTemplate(NodeTemplate nodeTemplate, String requirementId, RequirementAssignment requirementAssignment) { List> nodeTemplateRequirements = nodeTemplate.getRequirements(); return nodeTemplateRequirements != null && nodeTemplateRequirements.stream().anyMatch( - requirement -> requirement.containsKey(requirementId) && DataModelUtil.compareRequirementAssignment( - requirementAssignment, requirement.get(requirementId))); + requirement -> requirement.containsKey(requirementId) && DataModelUtil + .compareRequirementAssignment(requirementAssignment, requirement.get(requirementId))); } private boolean isTypeOf(T object, String type, String getTypesMethodName, ServiceTemplate serviceTemplate, - ToscaServiceModel toscaServiceModel) { + ToscaServiceModel toscaServiceModel) { if (object == null) { return false; } - try { String objectType = (String) object.getClass().getMethod(GET_TYPE_METHOD_NAME).invoke(object); if (Objects.equals(objectType, type)) { return true; } - - Optional typeExistInServiceTemplateHierarchy = - isTypeExistInServiceTemplateHierarchy(type, objectType, getTypesMethodName, serviceTemplate, - toscaServiceModel, null); - return typeExistInServiceTemplateHierarchy.orElseThrow( - () -> new CoreException(new ToscaElementTypeNotFoundErrorBuilder(objectType).build())); - + Optional typeExistInServiceTemplateHierarchy = isTypeExistInServiceTemplateHierarchy(type, objectType, getTypesMethodName, + serviceTemplate, toscaServiceModel, null); + return typeExistInServiceTemplateHierarchy + .orElseThrow(() -> new CoreException(new ToscaElementTypeNotFoundErrorBuilder(objectType).build())); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new SdcRuntimeException(e); } } } - - diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java index 7c0d1271fb..90047aa6df 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaFileOutputServiceCsarImpl.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.tosca.services.impl; import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.CREATED_BY_ENTRY; @@ -21,6 +20,15 @@ import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.CSAR_VERSION_ENTRY; import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.ENTRY_DEFINITIONS; import static org.openecomp.sdc.tosca.csar.ToscaMetaEntry.TOSCA_META_FILE_VERSION_ENTRY; +import java.io.BufferedOutputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; import org.onap.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.core.utilities.file.FileContentHandler; @@ -33,135 +41,108 @@ import org.openecomp.sdc.tosca.exceptions.CsarCreationErrorBuilder; import org.openecomp.sdc.tosca.exceptions.CsarMissingEntryPointErrorBuilder; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; - -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipOutputStream; - - public class ToscaFileOutputServiceCsarImpl implements ToscaFileOutputService { - static final String EXTERNAL_ARTIFACTS_FOLDER_NAME = "Artifacts"; - private static final String DEFINITIONS_FOLDER_NAME = "Definitions"; - private static final String ARTIFACTS_FOLDER_NAME = "Artifacts"; - //todo currently duplicated, to be changed when external artifacts are separated from internal - private static final String TOSCA_META_FOLDER_NAME = "TOSCA-Metadata"; - private static final String TOSCA_META_FILE_VERSION_VALUE = "1.0"; - private static final String TOSCA_META_FILE_NAME = "TOSCA.meta"; - private static final String CSAR_VERSION_VALUE = "1.1"; - private static final String CREATED_BY_VALUE = "ASDC Onboarding portal"; - private static final String META_FILE_DELIMITER = ":"; - private static final String SPACE = " "; - private static final String FILE_SEPARATOR = File.separator; - private static final Logger logger = LoggerFactory.getLogger(ToscaFileOutputServiceCsarImpl.class); - - @Override - public byte[] createOutputFile(ToscaServiceModel toscaServiceModel, - FileContentHandler externalArtifacts) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) { - packDefinitions(zos, toscaServiceModel.getServiceTemplates()); - FileContentHandler artifactFiles = toscaServiceModel.getArtifactFiles(); - if (artifactFiles != null && !artifactFiles.isEmpty()) { - packArtifacts(zos, artifactFiles); - } - if (toscaServiceModel.getEntryDefinitionServiceTemplate() == null) { - throw new CoreException(new CsarMissingEntryPointErrorBuilder().build()); - } - createAndPackToscaMetaFile(zos, toscaServiceModel.getEntryDefinitionServiceTemplate()); - if (externalArtifacts != null) { - packExternalArtifacts(zos, externalArtifacts); - } - } catch (IOException ex) { - throw new CoreException(new CsarCreationErrorBuilder().build(), ex); + static final String EXTERNAL_ARTIFACTS_FOLDER_NAME = "Artifacts"; + private static final String DEFINITIONS_FOLDER_NAME = "Definitions"; + private static final String ARTIFACTS_FOLDER_NAME = "Artifacts"; + //todo currently duplicated, to be changed when external artifacts are separated from internal + private static final String TOSCA_META_FOLDER_NAME = "TOSCA-Metadata"; + private static final String TOSCA_META_FILE_VERSION_VALUE = "1.0"; + private static final String TOSCA_META_FILE_NAME = "TOSCA.meta"; + private static final String CSAR_VERSION_VALUE = "1.1"; + private static final String CREATED_BY_VALUE = "ASDC Onboarding portal"; + private static final String META_FILE_DELIMITER = ":"; + private static final String SPACE = " "; + private static final String FILE_SEPARATOR = File.separator; + private static final Logger logger = LoggerFactory.getLogger(ToscaFileOutputServiceCsarImpl.class); + + @Override + public byte[] createOutputFile(ToscaServiceModel toscaServiceModel, FileContentHandler externalArtifacts) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos))) { + packDefinitions(zos, toscaServiceModel.getServiceTemplates()); + FileContentHandler artifactFiles = toscaServiceModel.getArtifactFiles(); + if (artifactFiles != null && !artifactFiles.isEmpty()) { + packArtifacts(zos, artifactFiles); + } + if (toscaServiceModel.getEntryDefinitionServiceTemplate() == null) { + throw new CoreException(new CsarMissingEntryPointErrorBuilder().build()); + } + createAndPackToscaMetaFile(zos, toscaServiceModel.getEntryDefinitionServiceTemplate()); + if (externalArtifacts != null) { + packExternalArtifacts(zos, externalArtifacts); + } + } catch (IOException ex) { + throw new CoreException(new CsarCreationErrorBuilder().build(), ex); + } + return baos.toByteArray(); } - return baos.toByteArray(); - } - - - @Override - public String createMetaFile(String entryDefinitionsFileName) { - return TOSCA_META_FILE_VERSION_ENTRY.getName() + META_FILE_DELIMITER + SPACE + TOSCA_META_FILE_VERSION_VALUE - + System.lineSeparator() - + CSAR_VERSION_ENTRY.getName() + META_FILE_DELIMITER + SPACE + CSAR_VERSION_VALUE + System.lineSeparator() - + CREATED_BY_ENTRY.getName() + META_FILE_DELIMITER + SPACE + CREATED_BY_VALUE + System.lineSeparator() - + ENTRY_DEFINITIONS.getName() + META_FILE_DELIMITER + SPACE + DEFINITIONS_FOLDER_NAME - + FILE_SEPARATOR - + entryDefinitionsFileName; - } - - @Override - public String getArtifactsFolderName() { - return ARTIFACTS_FOLDER_NAME; - } - private void createAndPackToscaMetaFile(ZipOutputStream zos, String entryDefinitionsFileName) - throws IOException { - String metaFile = createMetaFile(entryDefinitionsFileName); - zos.putNextEntry( - new ZipEntry(TOSCA_META_FOLDER_NAME + FILE_SEPARATOR + TOSCA_META_FILE_NAME)); - writeBytesToZip(zos, new ByteArrayInputStream(metaFile.getBytes())); - } - - private void packDefinitions(ZipOutputStream zos, Map serviceTemplates) - throws IOException { - for (Map.Entry serviceTemplate : serviceTemplates.entrySet()) { - String fileName = serviceTemplate.getKey(); - zos.putNextEntry(new ZipEntry(DEFINITIONS_FOLDER_NAME + FILE_SEPARATOR + fileName)); - writeBytesToZip(zos, - FileUtils.convertToInputStream(serviceTemplate.getValue(), FileUtils.FileExtension.YAML)); + @Override + public String createMetaFile(String entryDefinitionsFileName) { + return TOSCA_META_FILE_VERSION_ENTRY.getName() + META_FILE_DELIMITER + SPACE + TOSCA_META_FILE_VERSION_VALUE + System.lineSeparator() + + CSAR_VERSION_ENTRY.getName() + META_FILE_DELIMITER + SPACE + CSAR_VERSION_VALUE + System.lineSeparator() + CREATED_BY_ENTRY.getName() + + META_FILE_DELIMITER + SPACE + CREATED_BY_VALUE + System.lineSeparator() + ENTRY_DEFINITIONS.getName() + META_FILE_DELIMITER + SPACE + + DEFINITIONS_FOLDER_NAME + FILE_SEPARATOR + entryDefinitionsFileName; } - } - private void packExternalArtifacts(ZipOutputStream zos, FileContentHandler externalArtifacts) { + @Override + public String getArtifactsFolderName() { + return ARTIFACTS_FOLDER_NAME; + } - for (String filenameIncludingPath : externalArtifacts.getFileList()) { - try { - zos.putNextEntry(new ZipEntry(filenameIncludingPath)); - writeBytesToZip(zos, externalArtifacts.getFileContentAsStream(filenameIncludingPath)); + private void createAndPackToscaMetaFile(ZipOutputStream zos, String entryDefinitionsFileName) throws IOException { + String metaFile = createMetaFile(entryDefinitionsFileName); + zos.putNextEntry(new ZipEntry(TOSCA_META_FOLDER_NAME + FILE_SEPARATOR + TOSCA_META_FILE_NAME)); + writeBytesToZip(zos, new ByteArrayInputStream(metaFile.getBytes())); + } - } catch (IOException ex) { - throw new RuntimeException(ex); - } finally { - try { - zos.closeEntry(); - } catch (IOException ignore) { - logger.debug(ignore.getMessage(), ignore); + private void packDefinitions(ZipOutputStream zos, Map serviceTemplates) throws IOException { + for (Map.Entry serviceTemplate : serviceTemplates.entrySet()) { + String fileName = serviceTemplate.getKey(); + zos.putNextEntry(new ZipEntry(DEFINITIONS_FOLDER_NAME + FILE_SEPARATOR + fileName)); + writeBytesToZip(zos, FileUtils.convertToInputStream(serviceTemplate.getValue(), FileUtils.FileExtension.YAML)); } - } } - } - - private void packArtifacts(ZipOutputStream zos, FileContentHandler artifacts) { - - for (String fileName : artifacts.getFileList()) { - try { - zos.putNextEntry(new ZipEntry(ARTIFACTS_FOLDER_NAME + FILE_SEPARATOR + fileName)); - writeBytesToZip(zos, artifacts.getFileContentAsStream(fileName)); - - } catch (IOException ex) { - throw new RuntimeException(ex); - } finally { - try { - zos.closeEntry(); - } catch (IOException ignore) { - logger.debug(ignore.getMessage(), ignore); + private void packExternalArtifacts(ZipOutputStream zos, FileContentHandler externalArtifacts) { + for (String filenameIncludingPath : externalArtifacts.getFileList()) { + try { + zos.putNextEntry(new ZipEntry(filenameIncludingPath)); + writeBytesToZip(zos, externalArtifacts.getFileContentAsStream(filenameIncludingPath)); + } catch (IOException ex) { + throw new RuntimeException(ex); + } finally { + try { + zos.closeEntry(); + } catch (IOException ignore) { + logger.debug(ignore.getMessage(), ignore); + } + } } - } } - } + private void packArtifacts(ZipOutputStream zos, FileContentHandler artifacts) { + for (String fileName : artifacts.getFileList()) { + try { + zos.putNextEntry(new ZipEntry(ARTIFACTS_FOLDER_NAME + FILE_SEPARATOR + fileName)); + writeBytesToZip(zos, artifacts.getFileContentAsStream(fileName)); + } catch (IOException ex) { + throw new RuntimeException(ex); + } finally { + try { + zos.closeEntry(); + } catch (IOException ignore) { + logger.debug(ignore.getMessage(), ignore); + } + } + } + } - private void writeBytesToZip(ZipOutputStream zos, InputStream is) throws IOException { - if(is != null){ - IOUtils.copy(is, zos); + private void writeBytesToZip(ZipOutputStream zos, InputStream is) throws IOException { + if (is != null) { + IOUtils.copy(is, zos); + } } - } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/AddContributorCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/AddContributorCommand.java index 8bdf178938..33bf2f1762 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/AddContributorCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/AddContributorCommand.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import java.io.IOException; @@ -51,24 +50,46 @@ public class AddContributorCommand extends Command { private static final String COMMAND_ADD_CONTRIBUTOR_FAILED = "Command AddContributor execution failed."; AddContributorCommand() { - options.addOption(Option.builder(ITEMS_PATH_OPTION).hasArg().argName("file") - .desc("file containing list of item ids, mandatory").build()); - options.addOption(Option.builder(UUSERS_PATH_OPTION).hasArg().argName("file") - .desc("file containing list of users, mandatory").build()); + options.addOption(Option.builder(ITEMS_PATH_OPTION).hasArg().argName("file").desc("file containing list of item ids, mandatory").build()); + options.addOption(Option.builder(UUSERS_PATH_OPTION).hasArg().argName("file").desc("file containing list of users, mandatory").build()); + } + + private static List getItemList(String itemListPath) throws IOException { + List itemList; + if (itemListPath != null) { + itemList = load(itemListPath).collect(Collectors.toList()); + } else { + itemList = new ItemHandler().getItemList(); + } + return itemList; + } + + private static void executeAllTasks(ExecutorService executor, Collection> tasks) throws InterruptedException { + List> futureTasks; + futureTasks = executor.invokeAll(tasks); + boolean isThreadOpen = true; + while (isThreadOpen) { + isThreadOpen = futureTasks.stream().anyMatch(future -> !future.isDone()); + } + } + + private static ItemAddContributorsTask createTask(String itemId, List users) { + return new ItemAddContributorsTask(new PermissionHandler(), new NotificationHandler(), itemId, users); + } + + private static Stream load(String filePath) throws IOException { + return Files.lines(Paths.get(filePath)); } @Override public boolean execute(String[] args) { CommandLine cmd = parseArgs(args); - if (!cmd.hasOption(ITEMS_PATH_OPTION) || !cmd.hasOption(UUSERS_PATH_OPTION)) { LOGGER.error("Arguments p and u are mandatory"); return false; } - String itemListPath = cmd.getOptionValue(ITEMS_PATH_OPTION); String userListPath = cmd.getOptionValue(UUSERS_PATH_OPTION); - List itemList; try { itemList = getItemList(itemListPath); @@ -81,12 +102,8 @@ public class AddContributorCommand extends Command { } catch (IOException e) { throw new CommandExecutionRuntimeException(ERROR_TRYING_TO_READ_FILE + "from:" + userListPath, e); } - - List tasks = - itemList.stream().map(itemid -> createTask(itemid, userList)).collect(Collectors.toList()); - + List tasks = itemList.stream().map(itemid -> createTask(itemid, userList)).collect(Collectors.toList()); ExecutorService executor = null; - try { executor = Executors.newFixedThreadPool(DEFAULT_THREAD_NUMBER); executeAllTasks(executor, tasks); @@ -105,38 +122,4 @@ public class AddContributorCommand extends Command { public CommandName getCommandName() { return CommandName.ADD_CONTRIBUTOR; } - - private static List getItemList(String itemListPath) throws IOException { - List itemList; - if (itemListPath != null) { - itemList = load(itemListPath).collect(Collectors.toList()); - } else { - itemList = new ItemHandler().getItemList(); - } - - return itemList; - } - - private static void executeAllTasks(ExecutorService executor, Collection> tasks) - throws InterruptedException { - List> futureTasks; - futureTasks = executor.invokeAll(tasks); - boolean isThreadOpen = true; - while (isThreadOpen) { - isThreadOpen = futureTasks.stream().anyMatch(future -> !future.isDone()); - - } - } - - - private static ItemAddContributorsTask createTask(String itemId, List users) { - return new ItemAddContributorsTask(new PermissionHandler(), new NotificationHandler(), itemId, users); - } - - private static Stream load(String filePath) throws IOException { - return Files.lines(Paths.get(filePath)); - - } - - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CleanUserDataCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CleanUserDataCommand.java index abca1e895f..cb54ea2f77 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CleanUserDataCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CleanUserDataCommand.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.CommandName.CLEAN_USER_DATA; @@ -41,11 +40,16 @@ public class CleanUserDataCommand extends Command { private static final String USER_OPTION = "u"; CleanUserDataCommand() { + options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName("item_id").desc("id of the item to clean, mandatory").build()); options.addOption( - Option.builder(ITEM_ID_OPTION).hasArg().argName("item_id").desc("id of the item to clean, mandatory") - .build()); - options.addOption(Option.builder(USER_OPTION).hasArg().argName("user") - .desc("the user of which the item data will be cleaned for, mandatory").build()); + Option.builder(USER_OPTION).hasArg().argName("user").desc("the user of which the item data will be cleaned for, mandatory").build()); + } + + private static SessionContext createSessionContext(String user) { + SessionContext sessionContext = new SessionContext(); + sessionContext.setUser(new UserInfo(user)); + sessionContext.setTenant("dox"); + return sessionContext; } @Override @@ -57,19 +61,15 @@ public class CleanUserDataCommand extends Command { } String itemId = cmd.getOptionValue(ITEM_ID_OPTION); String user = cmd.getOptionValue(USER_OPTION); - SessionContext context = createSessionContext(user); ZusammenConnector zusammenConnector = ZusammenConnectorFactory.getInstance().createInterface(); - Id itemIdObj = new Id(itemId); Collection versions = zusammenConnector.listPublicVersions(context, itemIdObj); for (ItemVersion version : versions) { try { zusammenConnector.cleanVersion(context, itemIdObj, version.getId()); } catch (Exception e) { - LOGGER.error( - String.format("Error occurred while cleaning item %s version %s from user %s space", itemId, - version.getId(), user), e); + LOGGER.error(String.format("Error occurred while cleaning item %s version %s from user %s space", itemId, version.getId(), user), e); } } return true; @@ -79,11 +79,4 @@ public class CleanUserDataCommand extends Command { public CommandName getCommandName() { return CLEAN_USER_DATA; } - - private static SessionContext createSessionContext(String user) { - SessionContext sessionContext = new SessionContext(); - sessionContext.setUser(new UserInfo(user)); - sessionContext.setTenant("dox"); - return sessionContext; - } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/Command.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/Command.java index 6dc78f158e..875c951754 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/Command.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/Command.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import org.apache.commons.cli.CommandLine; @@ -34,8 +33,7 @@ public abstract class Command { protected final Options options = new Options(); protected Command() { - options.addOption( - Option.builder(COMMAND_OPTION).hasArg().argName("command").desc(getCommandName().name()).build()); + options.addOption(Option.builder(COMMAND_OPTION).hasArg().argName("command").desc(getCommandName().name()).build()); } protected CommandLine parseArgs(String[] args) { @@ -54,7 +52,7 @@ public abstract class Command { formater.printHelp("zusammenMainTool", options); } - public void register(){ + public void register() { CommandsHolder.addCommand(this); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandName.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandName.java index f53cd95c35..4e08c4600a 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandName.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandName.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,17 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; public enum CommandName { - RESET_OLD_VERSION, - EXPORT, - IMPORT, - HEAL_ALL, - POPULATE_USER_PERMISSIONS, - ADD_CONTRIBUTOR, - CLEAN_USER_DATA, - DELETE_PUBLIC_VERSION, - SET_HEAL_BY_ITEM_VERSION + RESET_OLD_VERSION, EXPORT, IMPORT, HEAL_ALL, POPULATE_USER_PERMISSIONS, ADD_CONTRIBUTOR, CLEAN_USER_DATA, DELETE_PUBLIC_VERSION, SET_HEAL_BY_ITEM_VERSION } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandsHolder.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandsHolder.java index 1c632a6ccf..3984ec702b 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandsHolder.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/CommandsHolder.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.Command.COMMAND_OPTION; @@ -43,11 +42,10 @@ public class CommandsHolder { private static final Map COMMANDS = new EnumMap<>(CommandName.class); static { - OPTIONS.addOption( - Option.builder(COMMAND_OPTION).hasArg().argName("command").desc("command name, mandatory").build()); + OPTIONS.addOption(Option.builder(COMMAND_OPTION).hasArg().argName("command").desc("command name, mandatory").build()); registerCommands(); } - + private CommandsHolder() { } @@ -65,9 +63,8 @@ public class CommandsHolder { public static Optional getCommand(String[] args) { CommandLine cmd = parseArgs(args); - return cmd == null || !cmd.hasOption(COMMAND_OPTION) || cmd.getOptionValue(COMMAND_OPTION) == null - ? Optional.empty() - : getCommandName(cmd.getOptionValue(COMMAND_OPTION)).map(COMMANDS::get); + return cmd == null || !cmd.hasOption(COMMAND_OPTION) || cmd.getOptionValue(COMMAND_OPTION) == null ? Optional.empty() + : getCommandName(cmd.getOptionValue(COMMAND_OPTION)).map(COMMANDS::get); } public static void printUsages() { @@ -95,8 +92,7 @@ public class CommandsHolder { static void addCommand(Command command) { CommandName commandName = command.getCommandName(); if (COMMANDS.containsKey(commandName)) { - throw new IllegalArgumentException( - String.format("Command with the name %s was already registered", commandName)); + throw new IllegalArgumentException(String.format("Command with the name %s was already registered", commandName)); } COMMANDS.put(commandName, command); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/DeletePublicVersionCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/DeletePublicVersionCommand.java index 85b28ec695..450d497510 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/DeletePublicVersionCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/DeletePublicVersionCommand.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.CommandName.DELETE_PUBLIC_VERSION; @@ -39,10 +38,16 @@ public class DeletePublicVersionCommand extends Command { private static final String VERSION_ID_OPTION = "v"; DeletePublicVersionCommand() { - options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName("item_id") - .desc("id of the item to delete from public, mandatory").build()); - options.addOption(Option.builder(VERSION_ID_OPTION).hasArg().argName("version_id") - .desc("id of the version to delete from public, mandatory").build()); + options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName("item_id").desc("id of the item to delete from public, mandatory").build()); + options.addOption( + Option.builder(VERSION_ID_OPTION).hasArg().argName("version_id").desc("id of the version to delete from public, mandatory").build()); + } + + private static SessionContext createSessionContext() { + SessionContext sessionContext = new SessionContext(); + sessionContext.setUser(new UserInfo("public")); + sessionContext.setTenant("dox"); + return sessionContext; } @Override @@ -54,15 +59,12 @@ public class DeletePublicVersionCommand extends Command { } String itemId = cmd.getOptionValue(ITEM_ID_OPTION); String versionId = cmd.getOptionValue(VERSION_ID_OPTION); - SessionContext context = createSessionContext(); ZusammenConnector zusammenConnector = ZusammenConnectorFactory.getInstance().createInterface(); - try { zusammenConnector.cleanVersion(context, new Id(itemId), new Id(versionId)); } catch (Exception e) { - LOGGER.error(String.format("Error occurred while deleting item %s version %s from public space", itemId, - versionId), e); + LOGGER.error(String.format("Error occurred while deleting item %s version %s from public space", itemId, versionId), e); } return true; } @@ -71,11 +73,4 @@ public class DeletePublicVersionCommand extends Command { public CommandName getCommandName() { return DELETE_PUBLIC_VERSION; } - - private static SessionContext createSessionContext() { - SessionContext sessionContext = new SessionContext(); - sessionContext.setUser(new UserInfo("public")); - sessionContext.setTenant("dox"); - return sessionContext; - } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/HealAll.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/HealAll.java index 7b4e05f615..fbbec19149 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/HealAll.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/HealAll.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import java.io.BufferedWriter; @@ -25,13 +24,10 @@ import java.io.FileWriter; import java.io.IOException; import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.Future; import java.util.stream.Stream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; @@ -57,35 +53,49 @@ public class HealAll extends Command { private HealingManager healingManager; HealAll() { - options.addOption( - Option.builder(THREAD_NUM_OPTION).hasArg().argName("number").desc("number of threads").build()); + options.addOption(Option.builder(THREAD_NUM_OPTION).hasArg().argName("number").desc("number of threads").build()); + } + + private static void executeAllTasks(ExecutorService executor, BufferedWriter log) { + } + + private static Version resolveVersion(VersionInfoEntity versionInfoEntity) { + if (Objects.nonNull(versionInfoEntity.getCandidate())) { + return versionInfoEntity.getCandidate().getVersion(); + } else if (!CollectionUtils.isEmpty(versionInfoEntity.getViewableVersions())) { + return versionInfoEntity.getViewableVersions().stream().max(Version::compareTo).orElse(new Version()); + } + return versionInfoEntity.getActiveVersion(); + } + + private static void writeToLog(String message, BufferedWriter log) { + try { + log.write(message); + log.newLine(); + } catch (IOException e) { + throw new HealingRuntimeException("unable to write to healing all log file.", e); + } + } + + private static Stream filterByEntityType(Collection versionInfoEntities, String entityType) { + return versionInfoEntities.stream().filter(versionInfoEntity -> versionInfoEntity.getEntityType().equals(entityType)); } @Override public boolean execute(String[] args) { CommandLine cmd = parseArgs(args); - vspManager = VspManagerFactory.getInstance().createInterface(); healingManager = HealingManagerFactory.getInstance().createInterface(); - String logFileName = "healing.log"; try (BufferedWriter log = new BufferedWriter(new FileWriter(logFileName, true))) { - writeToLog("----starting healing------", log); Instant startTime = Instant.now(); - - int numberOfThreads = - cmd.hasOption(THREAD_NUM_OPTION) && Objects.nonNull(cmd.getOptionValue(THREAD_NUM_OPTION)) - ? Integer.valueOf(cmd.getOptionValue(THREAD_NUM_OPTION)) - : DEFAULT_THREAD_NUMBER; + int numberOfThreads = cmd.hasOption(THREAD_NUM_OPTION) && Objects.nonNull(cmd.getOptionValue(THREAD_NUM_OPTION)) ? Integer + .valueOf(cmd.getOptionValue(THREAD_NUM_OPTION)) : DEFAULT_THREAD_NUMBER; ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads); - - filterByEntityType(VersionInfoCassandraLoader.list(), - VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE) - .forEach(this::addTaskToTasks); - + filterByEntityType(VersionInfoCassandraLoader.list(), VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE) + .forEach(this::addTaskToTasks); executeAllTasks(executor, log); - writeToLog("----finished healing------", log); Instant endTime = Instant.now(); writeToLog("Total runtime was: " + Duration.between(startTime, endTime), log); @@ -100,38 +110,6 @@ public class HealAll extends Command { return CommandName.HEAL_ALL; } - private static void executeAllTasks(ExecutorService executor, BufferedWriter log) { - - } - - - private static Version resolveVersion(VersionInfoEntity versionInfoEntity) { - if (Objects.nonNull(versionInfoEntity.getCandidate())) { - return versionInfoEntity.getCandidate().getVersion(); - } else if (!CollectionUtils.isEmpty(versionInfoEntity.getViewableVersions())) { - - return versionInfoEntity.getViewableVersions().stream().max(Version::compareTo).orElse(new Version()); - } - return versionInfoEntity.getActiveVersion(); - } - - private static void writeToLog(String message, BufferedWriter log) { - try { - log.write(message); - log.newLine(); - } catch (IOException e) { - throw new HealingRuntimeException("unable to write to healing all log file.", e); - } - } - - private static Stream filterByEntityType(Collection versionInfoEntities, - String entityType) { - return versionInfoEntities.stream() - .filter(versionInfoEntity -> versionInfoEntity.getEntityType().equals(entityType)); - } - private void addTaskToTasks(VersionInfoEntity versionInfoEntity) { - } - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/PopulateUserPermissions.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/PopulateUserPermissions.java index ad280e16c6..3958b2b5e9 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/PopulateUserPermissions.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/PopulateUserPermissions.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.CommandName.POPULATE_USER_PERMISSIONS; @@ -23,21 +22,18 @@ import java.util.List; import org.openecomp.core.tools.store.PermissionHandler; import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; - public class PopulateUserPermissions extends Command { @Override public boolean execute(String[] args) { PermissionHandler permissionHandler = new PermissionHandler(); List permissions = permissionHandler.getAll(); - permissions.forEach(itemPermissionsEntity -> { if (!itemPermissionsEntity.getUserId().isEmpty() && !itemPermissionsEntity.getPermission().isEmpty()) { - permissionHandler.addItem(Collections.singleton(itemPermissionsEntity.getItemId()), - itemPermissionsEntity.getUserId(), itemPermissionsEntity.getPermission()); + permissionHandler.addItem(Collections.singleton(itemPermissionsEntity.getItemId()), itemPermissionsEntity.getUserId(), + itemPermissionsEntity.getPermission()); } }); - return true; } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlag.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlag.java index df9b9a5ae9..b5a879d976 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlag.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlag.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.CommandName.RESET_OLD_VERSION; @@ -30,7 +29,6 @@ import org.openecomp.core.tools.store.HealingHandler; import org.openecomp.core.tools.store.VersionCassandraLoader; import org.openecomp.core.tools.store.zusammen.datatypes.HealingEntity; - /** * Created by ayalaben on 10/15/2017 */ @@ -46,18 +44,13 @@ public class SetHealingFlag extends Command { public boolean execute(String[] args) { CommandLine cmd = parseArgs(args); String oldVersion = cmd.hasOption(VERSION_OPTION) ? cmd.getOptionValue(VERSION_OPTION) : null; - VersionCassandraLoader versionCassandraLoader = new VersionCassandraLoader(); ResultSet listItemVersion = versionCassandraLoader.listItemVersion(); - ArrayList healingEntities = new ArrayList<>(); - - listItemVersion.iterator().forEachRemaining(entry -> healingEntities.add(new HealingEntity(entry.getString(0), - entry.getString(1), entry.getString(2), true, oldVersion))); - + listItemVersion.iterator().forEachRemaining( + entry -> healingEntities.add(new HealingEntity(entry.getString(0), entry.getString(1), entry.getString(2), true, oldVersion))); HealingHandler healingHandler = new HealingHandler(); healingHandler.populateHealingTable(healingEntities); - return true; } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlagByItemVersionCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlagByItemVersionCommand.java index ce2f9acf62..00b4339b6f 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlagByItemVersionCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/commands/SetHealingFlagByItemVersionCommand.java @@ -1,28 +1,25 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.commands; import static org.openecomp.core.tools.commands.CommandName.SET_HEAL_BY_ITEM_VERSION; import com.datastax.driver.core.ResultSet; - import java.util.List; import java.util.stream.Collectors; - import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.openecomp.core.tools.store.HealingHandler; @@ -41,12 +38,10 @@ public class SetHealingFlagByItemVersionCommand extends Command { private static final String VERSION_ID = "version_id"; SetHealingFlagByItemVersionCommand() { - options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName(ITEM_ID) - .desc("id of the item to reset healing flag, mandatory").build()); - options.addOption(Option.builder(VERSION_ID_OPTION).hasArg().argName(VERSION_ID) - .desc("id of the version to delete from public, mandatory").build()); - options.addOption(Option.builder(PROJECT_OPTION).hasArg().argName("old_project_version") - .desc("old project version, mandatory").build()); + options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName(ITEM_ID).desc("id of the item to reset healing flag, mandatory").build()); + options.addOption( + Option.builder(VERSION_ID_OPTION).hasArg().argName(VERSION_ID).desc("id of the version to delete from public, mandatory").build()); + options.addOption(Option.builder(PROJECT_OPTION).hasArg().argName("old_project_version").desc("old project version, mandatory").build()); } @Override @@ -59,19 +54,14 @@ public class SetHealingFlagByItemVersionCommand extends Command { String itemId = cmd.getOptionValue(ITEM_ID_OPTION); String versionId = cmd.getOptionValue(VERSION_ID_OPTION); String projectVersion = cmd.getOptionValue(PROJECT_OPTION); - VersionCassandraLoader versionCassandraLoader = new VersionCassandraLoader(); ResultSet listItemVersion = versionCassandraLoader.listItemVersion(); - - List healingEntities = listItemVersion.all().stream().filter( - entry -> (entry.getString(ITEM_ID).equals(itemId) - && entry.getString(VERSION_ID).equals(versionId))).map(entry -> - new HealingEntity(entry.getString("space"), entry.getString(ITEM_ID), - entry.getString(VERSION_ID), true, projectVersion)).collect(Collectors.toList()); - + List healingEntities = listItemVersion.all().stream() + .filter(entry -> (entry.getString(ITEM_ID).equals(itemId) && entry.getString(VERSION_ID).equals(versionId))) + .map(entry -> new HealingEntity(entry.getString("space"), entry.getString(ITEM_ID), entry.getString(VERSION_ID), true, projectVersion)) + .collect(Collectors.toList()); HealingHandler healingHandler = new HealingHandler(); healingHandler.populateHealingTable(healingEntities); - return true; } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemAddContributorsTask.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemAddContributorsTask.java index f6cb427005..bc8c0722f7 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemAddContributorsTask.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/concurrent/ItemAddContributorsTask.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,59 +17,54 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.concurrent; -import org.openecomp.core.tools.store.NotificationHandler; -import org.openecomp.core.tools.store.PermissionHandler; - import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Callable; - +import org.openecomp.core.tools.store.NotificationHandler; +import org.openecomp.core.tools.store.PermissionHandler; public class ItemAddContributorsTask implements Callable { - private static final String CONTRIBUTOR = "Contributor"; - private static final String SUCCESSFUL_RETURN_MESSAGE = "Users added successfully as " + - "contributors to item id:%s."; - private final String itemId; - private final List users; - private final PermissionHandler permissionHandler; - private final NotificationHandler notificationHandler; + private static final String CONTRIBUTOR = "Contributor"; + private static final String SUCCESSFUL_RETURN_MESSAGE = "Users added successfully as " + "contributors to item id:%s."; + private final String itemId; + private final List users; + private final PermissionHandler permissionHandler; + private final NotificationHandler notificationHandler; - public ItemAddContributorsTask(PermissionHandler permissionHandler, NotificationHandler - notificationHandler, String itemId, List users) { - this.itemId = itemId.trim(); - this.users = new ArrayList<>(users); - this.permissionHandler = permissionHandler; - this.notificationHandler = notificationHandler; - } + public ItemAddContributorsTask(PermissionHandler permissionHandler, NotificationHandler notificationHandler, String itemId, List users) { + this.itemId = itemId.trim(); + this.users = new ArrayList<>(users); + this.permissionHandler = permissionHandler; + this.notificationHandler = notificationHandler; + } - @Override - public String call() { - users.forEach(this::handleUser); - return String.format(SUCCESSFUL_RETURN_MESSAGE, itemId); - } + @Override + public String call() { + users.forEach(this::handleUser); + return String.format(SUCCESSFUL_RETURN_MESSAGE, itemId); + } - private void handleUser(String user) { - Optional userPermission = getUserPermission(user); - if (!userPermission.isPresent()) { - setUserPermission(user, CONTRIBUTOR); - registerUserNotificationSubscription(user); + private void handleUser(String user) { + Optional userPermission = getUserPermission(user); + if (!userPermission.isPresent()) { + setUserPermission(user, CONTRIBUTOR); + registerUserNotificationSubscription(user); + } } - } - private void registerUserNotificationSubscription(String user) { - notificationHandler.registerNotificationForUserOnEntity(user, itemId); - } + private void registerUserNotificationSubscription(String user) { + notificationHandler.registerNotificationForUserOnEntity(user, itemId); + } - private void setUserPermission(String user, String permission) { - permissionHandler.setItemUserPermission(itemId, user, permission); - } + private void setUserPermission(String user, String permission) { + permissionHandler.setItemUserPermission(itemId, user, permission); + } - private Optional getUserPermission(String user) { - return permissionHandler.getItemUserPermission(itemId, user); - } + private Optional getUserPermission(String user) { + return permissionHandler.getItemUserPermission(itemId, user); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/CommandExecutionRuntimeException.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/CommandExecutionRuntimeException.java index d4eff2b40f..daffa68fb8 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/CommandExecutionRuntimeException.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/CommandExecutionRuntimeException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.exceptions; public class CommandExecutionRuntimeException extends RuntimeException { + public CommandExecutionRuntimeException(String message, Exception exception) { super(message, exception); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/HealingRuntimeException.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/HealingRuntimeException.java index 036cf1bf89..fa8d67cd96 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/HealingRuntimeException.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exceptions/HealingRuntimeException.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,10 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.exceptions; public class HealingRuntimeException extends RuntimeException { + public HealingRuntimeException(String message, Exception exception) { super(message, exception); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java index 2907d1e0cc..893c605784 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportDataCommand.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -58,32 +58,69 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.yaml.snakeyaml.Yaml; - public final class ExportDataCommand extends Command { - private static final Logger LOGGER = LoggerFactory.getLogger(ExportDataCommand.class); - private static final String ITEM_ID_OPTION = "i"; - static final String JOIN_DELIMITER = "$#"; public static final String JOIN_DELIMITER_SPLITTER = "\\$\\#"; - static final String MAP_DELIMITER = "!@"; public static final String MAP_DELIMITER_SPLITTER = "\\!\\@"; - private static final int THREAD_POOL_SIZE = 6; public static final String NULL_REPRESENTATION = "nnuullll"; + static final String JOIN_DELIMITER = "$#"; + static final String MAP_DELIMITER = "!@"; + private static final Logger LOGGER = LoggerFactory.getLogger(ExportDataCommand.class); + private static final String ITEM_ID_OPTION = "i"; + private static final int THREAD_POOL_SIZE = 6; public ExportDataCommand() { - options.addOption( - Option.builder(ITEM_ID_OPTION).hasArg().argName("item id").desc("id of item to export, mandatory").build()); + options.addOption(Option.builder(ITEM_ID_OPTION).hasArg().argName("item id").desc("id of item to export, mandatory").build()); + } + + private static void executeQuery(final Session session, final String query, final Set filteredItems, final String filteredColumn, + final Set vlms, final CountDownLatch donequerying, Executor executor) { + ResultSetFuture resultSetFuture = session.executeAsync(query); + Futures.addCallback(resultSetFuture, new FutureCallback() { + @Override + public void onSuccess(ResultSet resultSet) { + try { + Utils.printMessage(LOGGER, "Start to serialize " + query); + new ExportSerializer().serializeResult(resultSet, filteredItems, filteredColumn, vlms); + donequerying.countDown(); + } catch (Exception e) { + Utils.logError(LOGGER, "Serialization failed :" + query, e); + System.exit(-1); + } + } + + @Override + public void onFailure(Throwable t) { + Utils.logError(LOGGER, "Query failed :" + query, t); + System.exit(-1); + } + }, executor); + } + + private static void zipPath(final Path rootDir) throws ZipException { + final LocalDateTime date = LocalDateTime.now(); + final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; + final String dateStr = date.format(formatter).replace(":", "_"); + final Path zipFile = Paths.get(System.getProperty("user.home"), String.format("onboarding_import%s.zip", dateStr)); + ZipUtils.createZipFromPath(rootDir, zipFile); + Utils.printMessage(LOGGER, "Zip file was created " + zipFile.toString()); + Utils.printMessage(LOGGER, "Exported file :" + zipFile.toString()); + } + + public static void initDir(Path rootDir) throws IOException { + if (rootDir.toFile().exists()) { + FileUtils.forceDelete(rootDir.toFile()); + } + createDirectories(rootDir); } @Override public boolean execute(String[] args) { CommandLine cmd = parseArgs(args); - if (!cmd.hasOption(ITEM_ID_OPTION) || cmd.getOptionValue(ITEM_ID_OPTION) == null) { LOGGER.error("Argument i is mandatory"); return false; } - ExecutorService executor = null; try { CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); @@ -91,8 +128,7 @@ public final class ExportDataCommand extends Command { initDir(rootDir); try (Session session = CassandraSessionFactory.getSession()) { final Set filteredItems = Sets.newHashSet(cmd.getOptionValue(ITEM_ID_OPTION)); - Set fis = - filteredItems.stream().map(fi -> fi.replaceAll("\\r", "")).collect(Collectors.toSet()); + Set fis = filteredItems.stream().map(fi -> fi.replaceAll("\\r", "")).collect(Collectors.toSet()); Map> queries; Yaml yaml = new Yaml(); try (InputStream is = ExportDataCommand.class.getResourceAsStream("/queries.yaml")) { @@ -112,7 +148,6 @@ public final class ExportDataCommand extends Command { for (int i = 0; i < queriesList.size(); i++) { executeQuery(session, queriesList.get(i), vlms, itemsColumns.get(i), null, doneVmls, executor); } - doneVmls.await(); } } @@ -132,47 +167,4 @@ public final class ExportDataCommand extends Command { public CommandName getCommandName() { return EXPORT; } - - private static void executeQuery(final Session session, final String query, final Set filteredItems, - final String filteredColumn, final Set vlms, final CountDownLatch donequerying, Executor executor) { - ResultSetFuture resultSetFuture = session.executeAsync(query); - Futures.addCallback(resultSetFuture, new FutureCallback() { - @Override - public void onSuccess(ResultSet resultSet) { - try { - Utils.printMessage(LOGGER, "Start to serialize " + query); - new ExportSerializer().serializeResult(resultSet, filteredItems, filteredColumn, vlms); - donequerying.countDown(); - } catch (Exception e) { - Utils.logError(LOGGER, "Serialization failed :" + query, e); - System.exit(-1); - } - } - - @Override - public void onFailure(Throwable t) { - Utils.logError(LOGGER, "Query failed :" + query, t); - System.exit(-1); - } - }, executor); - } - - private static void zipPath(final Path rootDir) throws ZipException { - final LocalDateTime date = LocalDateTime.now(); - final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; - final String dateStr = date.format(formatter).replace(":", "_"); - final Path zipFile = Paths.get(System.getProperty("user.home"),String.format("onboarding_import%s.zip", dateStr)); - ZipUtils.createZipFromPath(rootDir, zipFile); - Utils.printMessage(LOGGER, "Zip file was created " + zipFile.toString()); - Utils.printMessage(LOGGER, "Exported file :" + zipFile.toString()); - } - - - public static void initDir(Path rootDir) throws IOException { - if (rootDir.toFile().exists()) { - FileUtils.forceDelete(rootDir.toFile()); - } - createDirectories(rootDir); - } - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java index 3454b99dc2..152141bc17 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/exportinfo/ExportSerializer.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,6 +25,7 @@ import static org.openecomp.core.tools.importinfo.ImportSingleTable.dataTypesMap import com.datastax.driver.core.DataType.Name; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; @@ -32,10 +33,15 @@ import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.file.Paths; -import java.util.*; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; -import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.core.tools.importinfo.ImportProperties; import org.openecomp.core.tools.model.ColumnDefinition; import org.openecomp.core.tools.model.TableData; @@ -49,11 +55,11 @@ public class ExportSerializer { private static final String ELEMENT_TABLE_NAME = "element"; private static final String ELEMENT_INFO_COLUMN_NAME = "info"; - public void serializeResult(final ResultSet resultSet, final Set filteredItems, final String filteredColumn, Set vlms) { try { TableData tableData = new TableData(); - tableData.getDefinitions().addAll(resultSet.getColumnDefinitions().asList().stream().map(ColumnDefinition::new).collect(Collectors.toList())); + tableData.getDefinitions() + .addAll(resultSet.getColumnDefinitions().asList().stream().map(ColumnDefinition::new).collect(Collectors.toList())); String table = tableData.getDefinitions().iterator().next().getTable(); boolean isElementTable = table.equals(ELEMENT_TABLE_NAME); Iterator iterator = resultSet.iterator(); @@ -75,7 +81,6 @@ public class ExportSerializer { String fileName = ImportProperties.ROOT_DIRECTORY + File.separator + table + "_" + System.currentTimeMillis() + ".json"; objectMapper.writeValue(Paths.get(fileName).toFile(), tableData); Utils.printMessage(logger, "File exported is :" + fileName); - } catch (IOException e) { Utils.logError(logger, e); System.exit(1); @@ -135,8 +140,9 @@ public class ExportSerializer { case MAP: Map map = (Map) row.getObject(i); Set> entrySet = map.entrySet(); - Object mapAsString = entrySet.parallelStream().map(entry -> entry.getKey().toString() + ExportDataCommand.MAP_DELIMITER + entry.getValue().toString()) - .collect(Collectors.joining(ExportDataCommand.JOIN_DELIMITER)); + Object mapAsString = entrySet.parallelStream() + .map(entry -> entry.getKey().toString() + ExportDataCommand.MAP_DELIMITER + entry.getValue().toString()) + .collect(Collectors.joining(ExportDataCommand.JOIN_DELIMITER)); data = Base64.getEncoder().encodeToString(mapAsString.toString().getBytes()); break; default: diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java index cff8eb98cf..4f58df6276 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportDataCommand.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.importinfo; - import static org.openecomp.core.tools.commands.CommandName.IMPORT; import java.io.IOException; @@ -53,7 +51,6 @@ public class ImportDataCommand extends Command { @Override public boolean execute(String[] args) { CommandLine cmd = parseArgs(args); - if (!cmd.hasOption(FILE_OPTION) || cmd.getOptionValue(FILE_OPTION) == null) { LOGGER.error("Argument f is mandatory"); return false; diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java index 9d9530d860..1339ed5dc6 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportProperties.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.importinfo; import java.io.File; public class ImportProperties { - public static final String ROOT_DIRECTORY = System.getProperty("user.home")+File.separator+ "onboarding_import"; + + public static final String ROOT_DIRECTORY = System.getProperty("user.home") + File.separator + "onboarding_import"; } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java index 64c595caa5..71cce34fe4 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/importinfo/ImportSingleTable.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.importinfo; import static org.openecomp.core.tools.exportinfo.ExportDataCommand.NULL_REPRESENTATION; @@ -26,11 +25,21 @@ import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.DataType.Name; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Sets; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Path; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; -import com.fasterxml.jackson.databind.ObjectMapper; import org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory; import org.openecomp.core.tools.exportinfo.ExportDataCommand; import org.openecomp.core.tools.model.ColumnDefinition; @@ -39,21 +48,22 @@ import org.openecomp.core.tools.util.Utils; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.file.Path; -import java.util.*; -import java.util.stream.Collectors; - public class ImportSingleTable { + public static final ImmutableMap dataTypesMap; private static final Logger logger = LoggerFactory.getLogger(ImportSingleTable.class); - private static final String INSERT_INTO = "INSERT INTO "; private static final String VALUES = " VALUES "; private static final Map statementsCache = new HashMap<>(); - - public static final ImmutableMap dataTypesMap; + + static { + Builder builder = ImmutableMap.builder(); + Name[] values = Name.values(); + for (Name name : values) { + builder.put(name.name().toLowerCase(), name); + } + dataTypesMap = builder.build(); + } public void importFile(Path file) { try { @@ -65,7 +75,6 @@ public class ImportSingleTable { } catch (IOException e) { Utils.logError(logger, e); } - } private PreparedStatement getPrepareStatement(TableData tableData, Session session) { @@ -101,7 +110,7 @@ public class ImportSingleTable { bind.setBytes(i, ByteBuffer.wrap(Base64.getDecoder().decode(rowData.getBytes()))); break; case TIMESTAMP: - if (StringUtils.isEmpty(rowData)){ + if (StringUtils.isEmpty(rowData)) { bind.setTimestamp(i, null); } else { bind.setTimestamp(i, new Date(Long.parseLong(rowData))); @@ -148,7 +157,6 @@ public class ImportSingleTable { break; default: throw new UnsupportedOperationException("Name is not supported :" + name); - } } @@ -156,21 +164,9 @@ public class ImportSingleTable { ColumnDefinition def = tableData.getDefinitions().iterator().next(); StringBuilder sb = new StringBuilder(1024); sb.append(INSERT_INTO).append(def.getKeyspace()).append(".").append(def.getTable()); - sb.append(tableData.getDefinitions().stream().map(ColumnDefinition::getName) - .collect(Collectors.joining(" , ", " ( ", " ) "))); - sb.append(VALUES).append(tableData.getDefinitions().stream().map(definition -> "?") - .collect(Collectors.joining(" , ", " ( ", " ) "))).append(";"); + sb.append(tableData.getDefinitions().stream().map(ColumnDefinition::getName).collect(Collectors.joining(" , ", " ( ", " ) "))); + sb.append(VALUES).append(tableData.getDefinitions().stream().map(definition -> "?").collect(Collectors.joining(" , ", " ( ", " ) "))) + .append(";"); return sb.toString(); } - - - static { - Builder builder = ImmutableMap.builder(); - Name[] values = Name.values(); - for (Name name : values) { - builder.put(name.name().toLowerCase(), name); - } - dataTypesMap = builder.build(); - } - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/itemvalidation/ItemValidation.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/itemvalidation/ItemValidation.java index 40ed4f8fec..19ba419c94 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/itemvalidation/ItemValidation.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/itemvalidation/ItemValidation.java @@ -1,21 +1,28 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.itemvalidation; +import static org.openecomp.core.tools.util.Utils.logError; +import static org.openecomp.core.tools.util.Utils.printMessage; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; import org.openecomp.core.tools.store.ElementCassandraLoader; import org.openecomp.core.tools.store.ItemHandler; import org.openecomp.core.tools.store.VersionCassandraLoader; @@ -28,14 +35,8 @@ import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.stream.Collectors; - -import static org.openecomp.core.tools.util.Utils.printMessage; -import static org.openecomp.core.tools.util.Utils.logError; - public class ItemValidation { + private static final Logger logger = LoggerFactory.getLogger(ItemValidation.class); private static final String NEW_LINE = System.getProperty("line.separator"); private static final String PUBLIC_SPACE = "public"; @@ -46,131 +47,96 @@ public class ItemValidation { public static void main(String[] args) { for (int i = 0; i < args.length; i++) { if ("-i".equals(args[i])) { - if (args[i+1] != null) { + if (args[i + 1] != null) { itemId = args[i + 1]; } break; } } - if (itemId == null) { printMessage(logger, "-i 123456 "); System.exit(-1); } - ItemValidation itemValidation = new ItemValidation(); itemValidation.validate(); System.exit(1); } private void validate() { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); subElementsList = new LinkedList<>(); validationMessage = new LinkedList<>(); - try { SessionContextProviderFactory.getInstance().createInterface().create("GLOBAL_USER", "dox"); CassandraConnectionInitializer.setCassandraConnectionPropertiesToSystem(); - List itemList = new ItemHandler().getItemList(); if (itemList.stream().filter(item -> item.equals(itemId)).collect(Collectors.toList()).isEmpty()) { - printMessage(logger,String.format("%s No data found for itemId: %s %s", NEW_LINE, itemId, NEW_LINE)); + printMessage(logger, String.format("%s No data found for itemId: %s %s", NEW_LINE, itemId, NEW_LINE)); return; } - printMessage(logger,String.format("%s Validation started at %s %S", NEW_LINE, - sdf.format(new Date()), NEW_LINE)); - - List versionEntityList = new VersionCassandraLoader().list().all().stream(). - filter(entry -> entry.getItemId().equals(itemId)).collect(Collectors.toList()); - - versionEntityList.sort(( VersionEntity e1, VersionEntity e2) -> { - if (e1.getSpace().equals(PUBLIC_SPACE)) { - return -1; - } else if (e2.getSpace().equals(PUBLIC_SPACE)) { - return 1; - } else { - return e1.getSpace().compareTo(e2.getSpace()); - } + printMessage(logger, String.format("%s Validation started at %s %S", NEW_LINE, sdf.format(new Date()), NEW_LINE)); + List versionEntityList = new VersionCassandraLoader().list().all().stream() + .filter(entry -> entry.getItemId().equals(itemId)).collect(Collectors.toList()); + versionEntityList.sort((VersionEntity e1, VersionEntity e2) -> { + if (e1.getSpace().equals(PUBLIC_SPACE)) { + return -1; + } else if (e2.getSpace().equals(PUBLIC_SPACE)) { + return 1; + } else { + return e1.getSpace().compareTo(e2.getSpace()); + } }); - versionEntityList.forEach((VersionEntity versionEntity) -> { - List versionElementsEntityList = new VersionElementsCassandraLoader(). - listVersionElementsByPK(versionEntity.getSpace(), versionEntity.getItemId(), - versionEntity.getVersionId()).all(); + List versionElementsEntityList = new VersionElementsCassandraLoader() + .listVersionElementsByPK(versionEntity.getSpace(), versionEntity.getItemId(), versionEntity.getVersionId()).all(); versionElementsEntityList.forEach(this::accept); }); - }catch (Exception ex) { - logError(logger,ex); + } catch (Exception ex) { + logError(logger, ex); } if (validationMessage.isEmpty()) { - printMessage(logger,String.format("%s Item %s is successfully validated.", NEW_LINE, itemId)); + printMessage(logger, String.format("%s Item %s is successfully validated.", NEW_LINE, itemId)); } else { - printMessage(logger,"\n Errors:"); + printMessage(logger, "\n Errors:"); for (String message : validationMessage) { - printMessage(logger,message); + printMessage(logger, message); } } - printMessage(logger,String.format("%s Validation ended at %s %s", NEW_LINE, sdf.format(new Date()), NEW_LINE)); + printMessage(logger, String.format("%s Validation ended at %s %s", NEW_LINE, sdf.format(new Date()), NEW_LINE)); } - private void validateElement(String space, String itemId, String versionId, - String elementId, String revisionId) { - - ElementEntity elementEntity = - new ElementCassandraLoader().getByPK(space, itemId, versionId, elementId, revisionId).one(); - + private void validateElement(String space, String itemId, String versionId, String elementId, String revisionId) { + ElementEntity elementEntity = new ElementCassandraLoader().getByPK(space, itemId, versionId, elementId, revisionId).one(); if (elementEntity == null) { - validationMessage.add(String.format( - "Element is defined in VERSION_ELEMENTS.element_ids is not found in ELEMENT. " + - "Space:%s, ItemID:%s ,VersionID:%s, ElementID:%s, element revisionID:%s", - space, itemId, versionId, elementId, revisionId)); + validationMessage.add(String.format("Element is defined in VERSION_ELEMENTS.element_ids is not found in ELEMENT. " + + "Space:%s, ItemID:%s ,VersionID:%s, ElementID:%s, element revisionID:%s", space, itemId, versionId, elementId, revisionId)); return; } - if (elementEntity.getSubElementIds() != null) { subElementsList.addAll(elementEntity.getSubElementIds()); } } private void accept(VersionElementsEntity versionElementsEntity) { - printMessage(logger, String.format( - "Found VERSION_ELEMENTS entry. Space: %s, ItemID: %s, VersionId: %s, Revision: %s", - versionElementsEntity.getSpace(), - versionElementsEntity.getItemId(), - versionElementsEntity.getVersionId(), - versionElementsEntity.getRevisionId())); - + printMessage(logger, String + .format("Found VERSION_ELEMENTS entry. Space: %s, ItemID: %s, VersionId: %s, Revision: %s", versionElementsEntity.getSpace(), + versionElementsEntity.getItemId(), versionElementsEntity.getVersionId(), versionElementsEntity.getRevisionId())); subElementsList.clear(); if (versionElementsEntity.getElementIds().isEmpty()) { - validationMessage.add(String.format - ("Empty field VERSION_ELEMENT.element_ids. Space: %s, ItemID: %s, VersionId: %s, Revision: %s", - versionElementsEntity.getSpace(), - versionElementsEntity.getItemId(), - versionElementsEntity.getVersionId(), - versionElementsEntity.getRevisionId())); + validationMessage.add(String.format("Empty field VERSION_ELEMENT.element_ids. Space: %s, ItemID: %s, VersionId: %s, Revision: %s", + versionElementsEntity.getSpace(), versionElementsEntity.getItemId(), versionElementsEntity.getVersionId(), + versionElementsEntity.getRevisionId())); } else { - //loop over element_ids stored in version_elements - versionElementsEntity.getElementIds().forEach((key, value) -> - validateElement(versionElementsEntity.getSpace(), - versionElementsEntity.getItemId(), - versionElementsEntity.getVersionId(), - key, - value) - ); - + versionElementsEntity.getElementIds().forEach( + (key, value) -> validateElement(versionElementsEntity.getSpace(), versionElementsEntity.getItemId(), + versionElementsEntity.getVersionId(), key, value)); //loop over collected sub-elements to insure existence in version_elements.elements_ids subElementsList.forEach((String key) -> { if (!versionElementsEntity.getElementIds().containsKey(key)) { - validationMessage.add(String.format( - "Element is defined in table ELEMENT but not found in VERSION_ELEMENTS.element_ids." - + " Space:%s, ItemID:%s, VersionID:%s, Version RevisionID:%s, ElementID:%s", - versionElementsEntity.getSpace(), - versionElementsEntity.getItemId(), - versionElementsEntity.getVersionId(), - versionElementsEntity.getRevisionId(), - key)); + validationMessage.add(String.format("Element is defined in table ELEMENT but not found in VERSION_ELEMENTS.element_ids." + + " Space:%s, ItemID:%s, VersionID:%s, Version RevisionID:%s, ElementID:%s", versionElementsEntity.getSpace(), + versionElementsEntity.getItemId(), versionElementsEntity.getVersionId(), versionElementsEntity.getRevisionId(), key)); } }); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/VersionInfoCassandraLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/VersionInfoCassandraLoader.java index 970f26ac21..4f70cce460 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/VersionInfoCassandraLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/loaders/VersionInfoCassandraLoader.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,29 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.loaders; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.Collection; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; -import java.util.Collection; - public class VersionInfoCassandraLoader { - private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static VersionInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static VersionInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + public static Collection list() { + return accessor.getAll().all(); + } - public static Collection list() { - return accessor.getAll().all(); - } + @Accessor + interface VersionInfoAccessor { - @Accessor - interface VersionInfoAccessor { - @Query("select * from version_info ") - Result getAll(); - } + @Query("select * from version_info ") + Result getAll(); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/main/ZusammenMainTool.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/main/ZusammenMainTool.java index 1eca7bc2e3..816b06e907 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/main/ZusammenMainTool.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/main/ZusammenMainTool.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.main; import static org.openecomp.core.tools.util.Utils.printMessage; @@ -37,7 +36,6 @@ public class ZusammenMainTool { public static void main(String[] args) { Command command = getCommandToRun(args); - Instant startTime = Instant.now(); SessionContextProviderFactory.getInstance().createInterface().create("GLOBAL_USER", "dox"); if (!command.execute(args)) { @@ -45,7 +43,6 @@ public class ZusammenMainTool { System.exit(-1); } Instant stopTime = Instant.now(); - printDuration(command, startTime, stopTime); System.exit(0); } @@ -64,8 +61,7 @@ public class ZusammenMainTool { Duration duration = Duration.between(startTime, stopTime); long minutesPart = duration.toMinutes(); long secondsPart = duration.minusMinutes(minutesPart).getSeconds(); - - printMessage(LOGGER, String.format("Zusammen tools command %s finished. Total run time was %s:%s minutes.", - command.getCommandName(), minutesPart, secondsPart)); + printMessage(LOGGER, String + .format("Zusammen tools command %s finished. Total run time was %s:%s minutes.", command.getCommandName(), minutesPart, secondsPart)); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java index 35e25f2e7d..6d1ebbf83a 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/ColumnDefinition.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,7 +21,6 @@ package org.openecomp.core.tools.model; import com.datastax.driver.core.ColumnDefinitions.Definition; import com.datastax.driver.core.DataType; - import java.util.Arrays; public class ColumnDefinition { @@ -88,13 +87,10 @@ public class ColumnDefinition { @Override public final boolean equals(Object o) { - if (!(o instanceof ColumnDefinition)) + if (!(o instanceof ColumnDefinition)) { return false; - + } ColumnDefinition other = (ColumnDefinition) o; - return keyspace.equals(other.keyspace) - && table.equals(other.table) - && name.equals(other.name) - && type.equals(other.type); + return keyspace.equals(other.keyspace) && table.equals(other.table) && name.equals(other.name) && type.equals(other.type); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java index 77b6ca1b76..8dfcc79cb8 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/model/TableData.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,6 +25,7 @@ import lombok.Getter; @Getter public class TableData { + private final List definitions = new ArrayList<>(); private final List> rows = new ArrayList<>(); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementCassandraLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementCassandraLoader.java index d7f2ba63d6..faf2528a50 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementCassandraLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementCassandraLoader.java @@ -1,75 +1,61 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.store; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import com.datastax.driver.mapping.annotations.QueryParameters; +import java.nio.ByteBuffer; +import java.util.Set; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.tools.store.zusammen.datatypes.ElementEntity; -import java.nio.ByteBuffer; -import java.util.Set; - public class ElementCassandraLoader { private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); private static ElementAccessor accessor = noSqlDb.getMappingManager().createAccessor(ElementAccessor.class); public void createEntity(ElementEntity elementEntity) { - accessor.insertElement(elementEntity.getSpace(), - elementEntity.getItemId(), - elementEntity.getVersionId(), - elementEntity.getElementId(), - elementEntity.getData(), - elementEntity.getInfo(), - elementEntity.getNamespace(), - elementEntity.getParentId(), - elementEntity.getRelations(), - elementEntity.getSearchableData(), - elementEntity.getSubElementIds()); + accessor.insertElement(elementEntity.getSpace(), elementEntity.getItemId(), elementEntity.getVersionId(), elementEntity.getElementId(), + elementEntity.getData(), elementEntity.getInfo(), elementEntity.getNamespace(), elementEntity.getParentId(), elementEntity.getRelations(), + elementEntity.getSearchableData(), elementEntity.getSubElementIds()); } public Result list() { return accessor.getAll(); } - public Result getByPK(String space, String itemId, String versionId, String elementId, - String revisionId) { + + public Result getByPK(String space, String itemId, String versionId, String elementId, String revisionId) { return accessor.getByPK(space, itemId, versionId, elementId, revisionId); } + @Accessor interface ElementAccessor { - @Query("insert into zusammen_dox.element (space,item_id,version_id,element_id,data,info," + - "namespace,parent_id,relations,searchable_data,sub_element_ids) values (?,?,?,?,?,?,?,?,?,?,?)") - void insertElement(String space, String itemId, String versionId, String elementId, ByteBuffer data, - String info, String namespaceStr, String parentId, String relations, ByteBuffer searchable, - Set subElementsIds); - + @Query("insert into zusammen_dox.element (space,item_id,version_id,element_id,data,info, namespace,parent_id,relations,searchable_data,sub_element_ids) values (?,?,?,?,?,?,?,?,?,?,?)") + void insertElement(String space, String itemId, String versionId, String elementId, ByteBuffer data, String info, String namespaceStr, + String parentId, String relations, ByteBuffer searchable, Set subElementsIds); @Query("select * from zusammen_dox.element ") @QueryParameters(fetchSize = 100) Result getAll(); - @Query("select * from zusammen_dox.element where space = ? and item_id = ? and version_id = ? and " + - "element_id = ? and revision_id = ?") - Result getByPK(String space, String itemId, String versionId, String elementId, - String revisionId); + + @Query("select * from zusammen_dox.element where space = ? and item_id = ? and version_id = ? and element_id = ? and revision_id = ?") + Result getByPK(String space, String itemId, String versionId, String elementId, String revisionId); } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementNamespaceHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementNamespaceHandler.java index c8ceaabf82..fe19ecfe03 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementNamespaceHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ElementNamespaceHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; - import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; @@ -30,18 +28,17 @@ import org.openecomp.core.tools.store.zusammen.datatypes.ElementEntity; public class ElementNamespaceHandler { - private static NoSqlDb nnoSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static ElementNamespaceAccessor accessor = nnoSqlDb.getMappingManager().createAccessor(ElementNamespaceAccessor.class); + private static NoSqlDb nnoSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static ElementNamespaceAccessor accessor = nnoSqlDb.getMappingManager().createAccessor(ElementNamespaceAccessor.class); public void createElementNamespace(ElementEntity elementEntity) { - accessor.create(elementEntity.getSpace(),elementEntity.getItemId(),elementEntity.getElementId(),elementEntity.getNamespace()); + accessor.create(elementEntity.getSpace(), elementEntity.getItemId(), elementEntity.getElementId(), elementEntity.getNamespace()); } @Accessor interface ElementNamespaceAccessor { + @Query("UPDATE zusammen_dox.element_namespace SET namespace=:ns WHERE space=:space AND item_id=:item AND element_id=:id ") void create(@Param("space") String space, @Param("item") String item, @Param("id") String id, @Param("ns") String ns); } - - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java index e5c541216c..2d0a5b5d5a 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/HealingHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,58 +17,49 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; +import java.util.List; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.tools.store.zusammen.datatypes.HealingEntity; -import java.util.List; - /** * Created by ayalaben on 10/15/2017 */ public class HealingHandler { - private static NoSqlDb nnoSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static HealingAccessor accessor = - nnoSqlDb.getMappingManager().createAccessor(HealingAccessor.class); - - - public void populateHealingTable(List healingEntities) { - healingEntities.forEach(healingEntity -> { - if (isHealingRecordExist(healingEntity)) { - accessor.updateFlag(healingEntity.isHealingFlag(), healingEntity.getSpace(), - healingEntity.getItemId(), healingEntity.getVersionId()); - } else { - accessor.create(healingEntity.getSpace(), healingEntity.getItemId(), - healingEntity.getVersionId(), healingEntity.isHealingFlag(), - healingEntity.getOldVersion()); - } - }); - } + private static NoSqlDb nnoSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static HealingAccessor accessor = nnoSqlDb.getMappingManager().createAccessor(HealingAccessor.class); - private boolean isHealingRecordExist(HealingEntity healingEntity) { - return accessor.getFlag(healingEntity.getSpace(), healingEntity.getItemId(), - healingEntity.getVersionId()).getAvailableWithoutFetching() == 1; - } + public void populateHealingTable(List healingEntities) { + healingEntities.forEach(healingEntity -> { + if (isHealingRecordExist(healingEntity)) { + accessor.updateFlag(healingEntity.isHealingFlag(), healingEntity.getSpace(), healingEntity.getItemId(), healingEntity.getVersionId()); + } else { + accessor.create(healingEntity.getSpace(), healingEntity.getItemId(), healingEntity.getVersionId(), healingEntity.isHealingFlag(), + healingEntity.getOldVersion()); + } + }); + } - @Accessor - interface HealingAccessor { + private boolean isHealingRecordExist(HealingEntity healingEntity) { + return accessor.getFlag(healingEntity.getSpace(), healingEntity.getItemId(), healingEntity.getVersionId()).getAvailableWithoutFetching() == 1; + } - @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?") - ResultSet getFlag(String space, String itemId, String versionId); + @Accessor + interface HealingAccessor { - @Query("Insert into healing (space, item_id, version_id, healing_needed, old_version) " + - "values (?,?,?,?,?)") - void create(String space, String itemId, String versionId, boolean flag, String oldVersion); + @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?") + ResultSet getFlag(String space, String itemId, String versionId); - @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?") - void updateFlag(boolean flag, String space, String itemId, String versionId); - } + @Query("Insert into healing (space, item_id, version_id, healing_needed, old_version) " + "values (?,?,?,?,?)") + void create(String space, String itemId, String versionId, boolean flag, String oldVersion); + @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?") + void updateFlag(boolean flag, String space, String itemId, String versionId); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ItemHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ItemHandler.java index 8260d0c09b..67d0ba717f 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ItemHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/ItemHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,36 +17,32 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; - import java.util.Collections; import java.util.List; import java.util.stream.Collectors; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; public class ItemHandler { - public List getItemList() { - ResultSet resultSet = NoSqlDbFactory.getInstance().createInterface() - .getMappingManager().createAccessor(ItemAccessor.class).list(); - List rows = resultSet.all(); - - if (rows != null) { - return rows.stream().map(row -> row.getString("item_id")).collect(Collectors.toList()); + public List getItemList() { + ResultSet resultSet = NoSqlDbFactory.getInstance().createInterface().getMappingManager().createAccessor(ItemAccessor.class).list(); + List rows = resultSet.all(); + if (rows != null) { + return rows.stream().map(row -> row.getString("item_id")).collect(Collectors.toList()); + } + return Collections.emptyList(); } - return Collections.emptyList(); - } - @Accessor - interface ItemAccessor { - @Query("SELECT item_id FROM zusammen_dox.item") - ResultSet list(); - } + @Accessor + interface ItemAccessor { + @Query("SELECT item_id FROM zusammen_dox.item") + ResultSet list(); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/NotificationHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/NotificationHandler.java index 6b3bcb6a3a..9dd111cd73 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/NotificationHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/NotificationHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,32 +17,27 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; - import java.util.HashSet; import java.util.Set; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; public class NotificationHandler { - public void registerNotificationForUserOnEntity(String user, String entityId) { - - Set userSet = new HashSet<>(); - userSet.add(user); - NoSqlDbFactory.getInstance().createInterface().getMappingManager() - .createAccessor(NotificationAccessor.class) - .updateNotificationSubscription(userSet, entityId); - } + public void registerNotificationForUserOnEntity(String user, String entityId) { + Set userSet = new HashSet<>(); + userSet.add(user); + NoSqlDbFactory.getInstance().createInterface().getMappingManager().createAccessor(NotificationAccessor.class) + .updateNotificationSubscription(userSet, entityId); + } - @Accessor - interface NotificationAccessor { + @Accessor + interface NotificationAccessor { - @Query("UPDATE dox.notification_subscribers SET subscribers = subscribers + ? where " + - "entity_id = ?") - void updateNotificationSubscription(Set users, String entityId); - } + @Query("UPDATE dox.notification_subscribers SET subscribers = subscribers + ? where " + "entity_id = ?") + void updateNotificationSubscription(Set users, String entityId); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/PermissionHandler.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/PermissionHandler.java index 1a339e80f3..d3e31b12e0 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/PermissionHandler.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/PermissionHandler.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.core.ResultSet; @@ -25,62 +24,54 @@ import com.datastax.driver.core.Row; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; -import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; -import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; - import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; public class PermissionHandler { - private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static PermissionAccessor accessor = - noSqlDb.getMappingManager().createAccessor(PermissionAccessor.class); - - - public Optional getItemUserPermission(String itemId, String user) { - ResultSet resultSet = accessor.getItemUserPermission(itemId, user); - Row row = resultSet.one(); - - if (Objects.nonNull(row)) { - return Optional.of(row.getString("permission")); - } else { - return Optional.empty(); + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static PermissionAccessor accessor = noSqlDb.getMappingManager().createAccessor(PermissionAccessor.class); + + public Optional getItemUserPermission(String itemId, String user) { + ResultSet resultSet = accessor.getItemUserPermission(itemId, user); + Row row = resultSet.one(); + if (Objects.nonNull(row)) { + return Optional.of(row.getString("permission")); + } else { + return Optional.empty(); + } } - } - - public void setItemUserPermission(String itemId, String user, String permission) { - accessor.setItemUserPermission(itemId, user, permission); - } - - public void addItem(Set items, String userId, String permission){ - accessor.addItem(items,userId,permission); - } - - public List getAll(){ - return accessor.getAll().all(); - } - - @Accessor - interface PermissionAccessor { + public void setItemUserPermission(String itemId, String user, String permission) { + accessor.setItemUserPermission(itemId, user, permission); + } + public void addItem(Set items, String userId, String permission) { + accessor.addItem(items, userId, permission); + } - @Query("INSERT into dox.item_permissions (item_id,user_id,permission) VALUES (?,?,?)") - void setItemUserPermission(String permission, String itemId, String userId); + public List getAll() { + return accessor.getAll().all(); + } + @Accessor + interface PermissionAccessor { - @Query("SELECT permission FROM dox.item_permissions WHERE item_id=? AND user_id=?") - ResultSet getItemUserPermission(String itemId, String userId); + @Query("INSERT into dox.item_permissions (item_id,user_id,permission) VALUES (?,?,?)") + void setItemUserPermission(String permission, String itemId, String userId); - @Query("SELECT * from dox.item_permissions") - Result getAll(); + @Query("SELECT permission FROM dox.item_permissions WHERE item_id=? AND user_id=?") + ResultSet getItemUserPermission(String itemId, String userId); - @Query("update dox.user_permission_items set item_list=item_list+? WHERE user_id = ? AND permission = ?") - void addItem(Set items, String userId, String permission); - } + @Query("SELECT * from dox.item_permissions") + Result getAll(); + @Query("update dox.user_permission_items set item_list=item_list+? WHERE user_id = ? AND permission = ?") + void addItem(Set items, String userId, String permission); + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionCassandraLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionCassandraLoader.java index 38bb21ccf1..10d3099cfa 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionCassandraLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionCassandraLoader.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.core.ResultSet; @@ -27,14 +26,13 @@ import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import com.datastax.driver.mapping.annotations.QueryParameters; import com.google.common.collect.Sets; +import java.util.Date; +import java.util.Set; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.tools.store.zusammen.datatypes.ElementEntity; import org.openecomp.core.tools.store.zusammen.datatypes.VersionEntity; -import java.util.Date; -import java.util.Set; - public class VersionCassandraLoader { private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); @@ -42,37 +40,32 @@ public class VersionCassandraLoader { private static VersionAccessor accessor = noSqlDb.getMappingManager().createAccessor(VersionAccessor.class); public void insertElementToVersion(ElementEntity elementEntity) { - accessor.addElements(Sets.newHashSet(elementEntity.getElementId()), elementEntity.getSpace(), elementEntity.getItemId(), elementEntity.getVersionId()); + accessor.addElements(Sets.newHashSet(elementEntity.getElementId()), elementEntity.getSpace(), elementEntity.getItemId(), + elementEntity.getVersionId()); } public void insertVersion(VersionEntity versionEntity) { - accessor.insertVersion( versionEntity.getSpace(), - versionEntity.getItemId(), - versionEntity.getVersionId(), - versionEntity.getBaseVersionId(), - versionEntity.getCreationTime(), - versionEntity.getInfo(), - versionEntity.getModificationTime(), - versionEntity.getRelations()); + accessor.insertVersion(versionEntity.getSpace(), versionEntity.getItemId(), versionEntity.getVersionId(), versionEntity.getBaseVersionId(), + versionEntity.getCreationTime(), versionEntity.getInfo(), versionEntity.getModificationTime(), versionEntity.getRelations()); } - public Result list() { return accessor.getAll(); } - public ResultSet listItemVersion() { return accessor.getAllItemVersion();} + public ResultSet listItemVersion() { + return accessor.getAllItemVersion(); + } @Accessor interface VersionAccessor { - @Query("UPDATE zusammen_dox.version_elements SET element_ids=element_ids+? " + - "WHERE space=? AND item_id=? AND version_id=?") + @Query("UPDATE zusammen_dox.version_elements SET element_ids=element_ids+? " + "WHERE space=? AND item_id=? AND version_id=?") void addElements(Set elementIds, String space, String itemId, String versionId); @Query("insert into zusammen_dox.version (space,item_id,version_id,base_version_id,creation_time,info,modification_time,relations) values (?,?,?,?,?,?,?,?)") - void insertVersion(String space, String itemId, String versionId, String baseVersionId, Date createTime, String info, Date modificationTime, String relations); - + void insertVersion(String space, String itemId, String versionId, String baseVersionId, Date createTime, String info, Date modificationTime, + String relations); @Query("select * from zusammen_dox.version ") @QueryParameters(fetchSize = 400) diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionElementsCassandraLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionElementsCassandraLoader.java index 5c02af408f..17b6730258 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionElementsCassandraLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionElementsCassandraLoader.java @@ -1,19 +1,18 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.store; import com.datastax.driver.mapping.Result; @@ -25,9 +24,9 @@ import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.tools.store.zusammen.datatypes.VersionElementsEntity; public class VersionElementsCassandraLoader { + private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static VersionElementsAccessor accessor = noSqlDb.getMappingManager(). - createAccessor(VersionElementsAccessor.class); + private static VersionElementsAccessor accessor = noSqlDb.getMappingManager().createAccessor(VersionElementsAccessor.class); public Result listVersionElementsByPK(String space, String itemId, String versionId) { return accessor.getByPK(space, itemId, versionId); @@ -36,9 +35,7 @@ public class VersionElementsCassandraLoader { @Accessor interface VersionElementsAccessor { - @Query("SELECT space, item_id, version_id, revision_id, element_ids " + - "FROM zusammen_dox.version_elements WHERE space=? and item_id=? and version_id=?") - + @Query("SELECT space, item_id, version_id, revision_id, element_ids FROM zusammen_dox.version_elements WHERE space=? and item_id=? and version_id=?") @QueryParameters(fetchSize = 400) Result getByPK(String space, String itemId, String versionId); } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionInfoCassandraLoader.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionInfoCassandraLoader.java index 1d66aa32bf..7a2dd79869 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionInfoCassandraLoader.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/VersionInfoCassandraLoader.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store; import com.datastax.driver.mapping.Mapper; @@ -25,23 +24,19 @@ import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import com.datastax.driver.mapping.annotations.QueryParameters; +import java.util.Collection; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; -import java.util.Collection; - public class VersionInfoCassandraLoader { private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static Mapper mapper = - noSqlDb.getMappingManager().mapper(VersionInfoEntity.class); - private static VersionInfoAccessor accessor = - noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); - private static VersionInfoDao versionInfoDao = - VersionInfoDaoFactory.getInstance().createInterface(); + private static Mapper mapper = noSqlDb.getMappingManager().mapper(VersionInfoEntity.class); + private static VersionInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(VersionInfoAccessor.class); + private static VersionInfoDao versionInfoDao = VersionInfoDaoFactory.getInstance().createInterface(); public void insertVersionInfo(VersionInfoEntity versionInfoEntity) { versionInfoDao.create(versionInfoEntity); @@ -53,10 +48,9 @@ public class VersionInfoCassandraLoader { @Accessor interface VersionInfoAccessor { + @Query("select * from dox.version_info ") @QueryParameters(fetchSize = 400) Result getAll(); } - - } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/ElementEntity.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/ElementEntity.java index d1fd93dd71..d88f36b8dd 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/ElementEntity.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/ElementEntity.java @@ -1,25 +1,23 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.store.zusammen.datatypes; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.nio.ByteBuffer; import java.util.Set; @@ -40,49 +38,35 @@ import java.util.Set; * PRIMARY KEY ((space, item_id, version_id, element_id)) * ) */ -@Table( - keyspace = "zusammen_dox", - name = "element" -) +@Table(keyspace = "zusammen_dox", name = "element") public class ElementEntity { - @Column( name = "space" ) + + @Column(name = "space") @PartitionKey(0) private String space; - - @Column( name = "item_id" ) + @Column(name = "item_id") @PartitionKey(1) private String itemId; - - @Column( name = "version_id" ) + @Column(name = "version_id") @PartitionKey(2) private String versionId; - @Column(name = "element_id") @PartitionKey(3) private String elementId; - @Column(name = "data") private ByteBuffer data; - @Column(name = "info") private String info; - @Column(name = "namespace") private String namespace; - @Column(name = "parent_id") private String parentId; - @Column(name = "relations") private String relations; - @Column(name = "searchable_data") private ByteBuffer searchableData; - @Column(name = "sub_element_ids") private Set subElementIds; - - @Column(name = "visualization") private ByteBuffer visualization; diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java index 155c8e2215..bde7855c9c 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/HealingEntity.java @@ -33,21 +33,17 @@ import lombok.Setter; @Table(keyspace = "dox", name = "healing") public class HealingEntity { - @Column(name = "space") - @PartitionKey(0) - private String space; - - @Column(name = "item_id") - @PartitionKey(1) - private String itemId; - - @Column(name = "version_id") - @PartitionKey(2) - private String versionId; - - @Column(name = "healing_needed") - private boolean healingFlag; - - @Column(name = "old_version") - private String oldVersion; + @Column(name = "space") + @PartitionKey(0) + private String space; + @Column(name = "item_id") + @PartitionKey(1) + private String itemId; + @Column(name = "version_id") + @PartitionKey(2) + private String versionId; + @Column(name = "healing_needed") + private boolean healingFlag; + @Column(name = "old_version") + private String oldVersion; } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionElementsEntity.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionElementsEntity.java index 936d7198c8..41649d2b48 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionElementsEntity.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionElementsEntity.java @@ -1,26 +1,24 @@ /* -* Copyright © 2016-2018 European Support Limited -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - + * Copyright © 2016-2018 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package org.openecomp.core.tools.store.zusammen.datatypes; import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.util.Map; /** @@ -39,63 +37,61 @@ import java.util.Map; * PRIMARY KEY ((space, item_id, version_id), revision_id)) * WITH CLUSTERING ORDER BY (revision_id ASC) */ - -@Table( - keyspace = "zusammen_dox", - name = "version_elements" -) +@Table(keyspace = "zusammen_dox", name = "version_elements") public class VersionElementsEntity { - @Column( name = "space" ) + + @Column(name = "space") @PartitionKey(0) private String space; - - @Column( name = "item_id" ) + @Column(name = "item_id") @PartitionKey(1) private String itemId; - - @Column( name = "version_id" ) + @Column(name = "version_id") @PartitionKey(2) private String versionId; - @Column(name = "revision_id") @ClusteringColumn private String revisionId; - @Column(name = "element_ids") - private Map elementIds; + private Map elementIds; - public void setSpace(String space) { - this.space = space; - } public String getSpace() { return space; } - public void setItemId(String itemId) { - this.itemId = itemId; + public void setSpace(String space) { + this.space = space; } + public String getItemId() { return itemId; } - public void setVersionId(String versionId) { - this.versionId = versionId; + public void setItemId(String itemId) { + this.itemId = itemId; } + public String getVersionId() { return versionId; } - public void setRevisionId(String revisionId) { - this.revisionId = revisionId; + public void setVersionId(String versionId) { + this.versionId = versionId; } + public String getRevisionId() { return revisionId; } - public void setElementIds(Map elementIds) { - this.elementIds = elementIds; + public void setRevisionId(String revisionId) { + this.revisionId = revisionId; } - public Map getElementIds() { + + public Map getElementIds() { return elementIds; } + + public void setElementIds(Map elementIds) { + this.elementIds = elementIds; + } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionEntity.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionEntity.java index e9f7d51038..652565d35b 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionEntity.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/store/zusammen/datatypes/VersionEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,13 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.store.zusammen.datatypes; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - import java.util.Date; /** @@ -52,35 +50,26 @@ import java.util.Date; * AND read_repair_chance = 0.0 * AND speculative_retry = '99.0PERCENTILE'; */ -@Table( - keyspace = "zusammen_dox", - name = "version" -) +@Table(keyspace = "zusammen_dox", name = "version") public class VersionEntity { + @Column(name = "space") @PartitionKey(0) private String space; - @Column(name = "item_id") @PartitionKey(1) private String itemId; - @Column(name = "version_id") @PartitionKey(2) private String versionId; - @Column(name = "base_version_id") private String baseVersionId; - @Column(name = "creation_time") private Date creationTime; - @Column(name = "info") private String info; - @Column(name = "modification_time") private Date modificationTime; - @Column(name = "relations") private String relations; diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ToolsUtil.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ToolsUtil.java index a7ef55ecab..0727e3c21d 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ToolsUtil.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/ToolsUtil.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.util; public class ToolsUtil { - public static String getParam(String key, String[] args) { - - for (int j = 0; j < args.length; j++) { - if (args[j].equals("-" + key)) { - return args[j + 1]; - } + public static String getParam(String key, String[] args) { + for (int j = 0; j < args.length; j++) { + if (args[j].equals("-" + key)) { + return args[j + 1]; + } + } + return null; } - return null; - } } diff --git a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/Utils.java b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/Utils.java index 018019eac8..67bcefe355 100644 --- a/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/Utils.java +++ b/openecomp-be/tools/zusammen-tools/src/main/java/org/openecomp/core/tools/util/Utils.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,42 +17,41 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.tools.util; import org.openecomp.sdc.logging.api.Logger; /** * Copyright © 2016-2017 European Support Limited. + * * @author Avrahamg * @since April 24, 2017 * Since it is a command line tools writing to console will be helpful to users. */ public class Utils { - public static void printMessage(Logger logger, String message) { - /** - * Since it is a command line tools writing to console will be helpful to users. - */ - System.out.println(message); - logger.debug(message); - } + public static void printMessage(Logger logger, String message) { + /** + * Since it is a command line tools writing to console will be helpful to users. + */ + System.out.println(message); + logger.debug(message); + } - public static void logError(Logger logger, Throwable ex) { - /** - * Since it is a command line tools writing to console will be helpful to users. - */ - ex.printStackTrace(); - logger.error(ex.getMessage(),ex); - } + public static void logError(Logger logger, Throwable ex) { + /** + * Since it is a command line tools writing to console will be helpful to users. + */ + ex.printStackTrace(); + logger.error(ex.getMessage(), ex); + } - public static void logError(Logger logger, String message, Throwable ex) { - /** - * Since it is a command line tools writing to console will be helpful to users. - */ - System.out.println(message); - ex.printStackTrace(); - logger.error(message,ex); - } + public static void logError(Logger logger, String message, Throwable ex) { + /** + * Since it is a command line tools writing to console will be helpful to users. + */ + System.out.println(message); + ex.printStackTrace(); + logger.error(message, ex); + } } - -- cgit 1.2.3-korg